'use strict';
var shrk = shrk || {};

shrk.swipers = {
	instances: {},
	cur_index: 0,

	initialize: function( $elem , swiper_params, attr_from ) {
		/**
		 * Swiper structure
		 *
		 * Swiper elem
		 * 		|	|
		 * 		|	|________________________
		 * 		|		|			|		|			
		 * 		|		|			|		|
		 * 		|		Next arr 	Prev 	Pagination div
		 * 	 	|
		 * 		Swiper wrapper
		 * 			\
		 * 			Swiper children (slides)
		 * 	
		 */
		var $                = jQuery;
		var swiper_params_gl = {};

		// Abort when $elem is empty.
		if ( typeof( $elem ) === 'object' && $elem.length === 0 ) {
			return;
		}

		$elem            = (typeof $elem !== 'undefined') ? $elem : $('.shrk-swiper-container');
		swiper_params    = (typeof swiper_params !== 'undefined') ? swiper_params : {};
		swiper_params_gl = $.extend(true, {}, swiper_params);

		$elem.each( function () {
			var swiper_data_prefix = 'data-swiper-';
			var $sw                = $(this);
			var $attr_elem;

			// Abort if swiper already initialized for element
			if ( typeof( $sw[0].swiper ) === 'object' ) {
				return true;
			}

			shrk.swipers.cur_index++;

			if ( $sw.children('.swiper-wrapper').length === 0 ) {
				if ( $sw.children().eq(0).children().length > 0 ) {
					$sw.children().eq(0).addClass('swiper-wrapper');
				} else {
					shrk.debug__log('Swiper['+shrk.swipers.cur_index+'] stucture unknown. Aborting.');
					return true;
				}
			}

			$sw.addClass('shrk-swiper-container');

			$sw.children('.swiper-wrapper').children().addClass('swiper-slide');

			if ( $sw.children('.swiper-pagination').length === 0 ) {
				$sw.append('<div class="swiper-pagination"><div class="pagination"></div></div>');
			}
		
			if ( $sw.children('.prev_swipe').length === 0 ) {
				$sw.append('<div class="prev_swipe"><i class="icon-ws-arrow-left"></i></div>');
			}
		
			if ( $sw.children('.next_swipe').length === 0 ) {
				$sw.append('<div class="next_swipe"><i class="icon-ws-arrow-right"></i></div>');
			}

			var swiper_defaults = {
				effect: 'slide',
				parallax: false,
				pagination: '.pagination',
				paginationClickable: true,
				direction: 'horizontal',
				loop: false,
				slidesPerView: shrk.swipers.getUserSPVoption(3),
				slidesPreloadBg: 3,
				autoHeight: true,
				autoplay: null,
				speed: 300,
				centeredSlides: false,
				grabCursor: false,
				nextButton: '.next_swipe',
				prevButton: '.prev_swipe',
				scrollbar: null,
				showScrollbar: false,
				spaceBetween: '3%',
				updateOnImagesReady: true,
				preloadImages: false,
				shortSwipes: true,
				breakpoints: shrk.swipers.getUserBreakpoints({
					768: {
						slidesPerView: 1
					},
					992: {
						slidesPerView: 2
					}
				}),
				onInit: function (swiper) {
					shrk.swipers.fixWidths( swiper );
					shrk.swipers.fixHeights( swiper );
					shrk.swipers.lazyloadImages( swiper );
					swiper.update();
				},
				onImagesReady: function (swiper) {
					shrk.swipers.fixWidths( swiper );
					shrk.swipers.fixHeights( swiper );
				},
				onSlideChangeStart: function (swiper) {
					shrk.swipers.lazyloadImages(swiper);
				},
				onTouchStart: function (swiper) {
					jQuery(swiper.container).addClass('swiper-dragging');
				},
				onTouchEnd: function (swiper) {
					jQuery(swiper.container).removeClass('swiper-dragging');
				},
				onLazyImageReady: function(swiper, slide, image) {
					jQuery(slide).removeClass('swiper-lazy-not-loaded');
				}
			};

			if ( typeof(attr_from) !== 'undefined' && attr_from === 'parent' ) {
				$attr_elem = $sw.parent();
			} else {
				$attr_elem = $sw;
			}

			for (var prop in swiper_defaults) {
				var prop_lc = prop.toLowerCase();
				if ( $attr_elem.attr(swiper_data_prefix+prop_lc) ) {
					var data_prop = $attr_elem.attr(swiper_data_prefix+prop_lc);
					if ( !isNaN(parseInt(data_prop, 10)) ) { data_prop = parseInt(data_prop, 10); }
					if ( data_prop === 'true' ) { data_prop = true; }
					if ( data_prop === 'false' ) { data_prop = false; }
					swiper_params[prop] = data_prop;
				} else if ( typeof(swiper_params[prop]) === 'undefined' ) {
					if ( swiper_defaults[prop] !== null ) {
						swiper_params[prop] = swiper_defaults[prop];					
					}

					// Special treatment for breakpoints
					// Dont allow default breakpoints to define a slidesPerView larger than the original explicitly set.
					if ( prop === 'breakpoints' ) {
						for( var bp in swiper_params['breakpoints'] ) {
							if ( swiper_params['breakpoints'][bp]['slidesPerView'] > swiper_params['slidesPerView'] ) {
								swiper_params['breakpoints'][bp]['slidesPerView'] = swiper_params['slidesPerView'];
							}
						}
					}
				} 
			}

			if ( swiper_params.showScrollbar === true ) {
				if ( $sw.children('.swiper-scrollbar').length === 0 ) {
					$sw.append('<div class="swiper-scrollbar"></div>');
				}
				swiper_params.scrollbar = '.swiper-scrollbar';
			} else {
				swiper_params.scrollbar = null;
			}

			//store swiper index
			$sw.attr('data-swiper-index', shrk.swipers.cur_index);
			$sw.find('.pagination').attr('data-swiper-index', shrk.swipers.cur_index);
			//initiate swiper
			shrk.swipers.instances[shrk.swipers.cur_index] = $sw.swiper( swiper_params );

			$(window).trigger('shrk_swiper_init', shrk.swipers.instances[shrk.swipers.cur_index]);

			//reset array var
			swiper_params = $.extend(true, {}, swiper_params_gl);
		});

		$(window).trigger('shrk_swipers_init');
	},

	getIndex: function ( $elem ) {
		return parseInt($elem.attr('data-swiper-index'), 10);
	},

	getSwiper: function ( $elem ) {
		return shrk.swipers.instances[ shrk.swipers.getIndex( $elem ) ];
	},

	updateAll: function () {
		jQuery.each(shrk.swipers.instances, function() { 
			this.update(true);
			shrk.swipers.fixWidths( this );
			shrk.swipers.fixHeights( this );
			shrk.swipers.xyPaginationUpdate( this );
			shrk.swipers.xyResizeHandler( this );
			this.update(); // Again after fix heights
		});
	},

	getUserBreakpoints: function ( defaults_bp ) {
		var user_bps = {}
		var i = 0;

		if ( !(typeof shrk.theme_options !== 'undefined' && typeof shrk.theme_options.woo_shop_columns_grid !== 'undefined' ) ) {
			return defaults_bp;
		}

		jQuery.each(shrk.theme_options.woo_shop_columns_grid, function(key, bp) {
			if ( bp.opr === 'max' ) {
		    	user_bps[bp.width] = { slidesPerView : parseInt(bp.cols, 10) };
				i++;
			}
		});

		return i > 0 ? user_bps : defaults_bp;
	},

	getUserSPVoption: function ( default_spv ) {
		var spv = false;
		if ( !(typeof shrk.theme_options !== 'undefined' && typeof shrk.theme_options.woo_shop_columns_grid !== 'undefined' ) ) {
			return default_spv;
		}

		jQuery.each(shrk.theme_options.woo_shop_columns_grid, function(key, bp) {
			if ( bp.opr === 'min' ) {
		    	spv = parseInt(bp.cols, 10);
		    	return false;
			}
		});

		return spv ? spv : default_spv;
	},

	fixWidths: function ( swiper ) {
		var $swiper_container = jQuery(swiper.container);

		//Partials max-width
		if ( $swiper_container.attr('data-swiper-slidesperview') === 'auto' && $swiper_container.attr('data-swiper-partialmaxwidth') ) {
			$swiper_container.find('.swiper-slide').css({
				maxWidth: $swiper_container.attr('data-swiper-partialmaxwidth')
			});

			swiper.updateSlidesSize();
		}
	},

	fixHeights: function ( swiper ) {
		var $swiper_container = jQuery(swiper.container);

		if ( $swiper_container.attr('data-swiper-heightmode') === 'windowheight_mh' ) {
			$swiper_container.css({ 'height' : jQuery( window ).height() - jQuery( '.site-header' ).height() - jQuery( '#wpadminbar' ).height() });
		}
	},

	lazyloadImages: function (swiper, nextSlidesToLoad) {
		var slidesFrom, slidesTo;

		if ( typeof(nextSlidesToLoad) === 'undefined' ) {
			nextSlidesToLoad = swiper.params.slidesPreloadBg;
		}

		slidesFrom 	= swiper.activeIndex;
		slidesTo 	= slidesFrom + nextSlidesToLoad;

		for (var i = slidesFrom; i <= slidesTo; i++) {

			var $slide = jQuery(swiper.slides[i]);
			var $lazy_target = $slide.find('.lazyload-bg'); //inner sliders should fire on their own.		

			if ( $slide.closest('.xy-slider').length ) {
				$lazy_target = $slide.find('> .lazyload-bg');	
			}

			if ( $slide.length && $lazy_target.length ) {
				var bg;
				if ( typeof( shrk.helpers.get_lazyload_bg ) ) {
					bg = shrk.helpers.get_lazyload_bg( $lazy_target );
				} else {
					bg = $lazy_target.attr('data-image-bg');
				} 

				if ( typeof(bg) === 'undefined' ) {
					$lazy_target = $slide.find('.slide-inner-image');
					bg = $lazy_target.attr('data-image-bg');
				}

				if ( typeof(bg) !== 'undefined' ) {
					$lazy_target.css({ 'background-image': 'url('+bg+')' });

					if ( typeof( imagesLoaded ) !== 'undefined' ) {
						$lazy_target.addClass('lazyloading-bg');
						$lazy_target.removeClass('lazyload-bg');
						$lazy_target.parent().imagesLoaded({ background: '.lazyloading-bg' }, function () { 
							shrk.debug__log('Loaded bg: '+bg);
							jQuery(this.elements).find('.lazyloading-bg').removeClass('lazyload-bg lazyloading-bg');
						});
					} else {
						$lazy_target.removeClass('lazyload-bg');
						shrk.debug__log('Loaded bg: '+bg);
					}
				}
			}
		}
	},

	fix_too_lazyImages: function($swiper) {
		var sw_index = shrk.swipers.getIndex( jQuery( $swiper ) );
		$swiper.find( '.swiper-lazy-not-loaded.swiper-slide-active' ).each( function () {
			var s = shrk.swipers.instances[sw_index];

			s.lazy.loadImageInSlide( shrk.swipers.instances[sw_index].activeIndex );
			s.on('onLazyImageReady', function (s) {
				s.update(); 		// Fix sliders not working in tabs
				s.slideTo(1, 0);	// Fix wrong active slide on tta slides
			});
		});
	},

	xyPaginationUpdate: function(swiper) {
		var $pagination = jQuery(swiper.container).find('.swiper-nav-thumbs-wrapper');
		var $indicator  = jQuery(swiper.container).find('.swiper-nav-wrapper .active-bar');
		var $pag_active = $pagination.find('[data-slide-id="'+swiper.activeIndex+'"]');

		if ( !$pagination.length || !$pag_active.length ) {
			return false;
		}

		$pagination.children().removeClass('active');
		$pag_active.addClass('active');

        if ( typeof jQuery.fn.isOnScreen === 'function' ) {
            if ( $pag_active.isOnScreen(1, 1, $pagination) === false ) {
            	var offset;
            	var cur_y = $pagination.scrollTop();

            	if ( $pag_active.position().top < 0 ) {
            		offset = $pag_active.position().top;
            	} else if ( ($pag_active.position().top + $pag_active.outerHeight() ) > $pagination.height() ) {
            		offset = $pag_active.position().top + $pag_active.outerHeight() - $pagination.height();
            	}

            	if ( offset ) {
            		$pagination.animate({scrollTop: cur_y+offset}, 200);
            	}
            }
        }
		$indicator.css({
			'opacity'   : '1',
			'transform' : 'translateY(' + ($pag_active.position().top + $pagination.scrollTop()) + 'px)',
			'height'    : $pag_active.outerHeight()
		});
	},

	xyResizeHandler: function(swiper) {
		if ( jQuery(swiper.container).hasClass('inner') ) {
			jQuery(swiper.container).find('.prev_swipe, .next_swipe').css({ 'transform' : '' });
		}
	},

	sc_load_posts: function( args, swiper ) {
		var $sw = jQuery(swiper.container);

		if ( $sw.hasClass('swiper-loading-posts') || $sw.hasClass('no-more-posts') ) { return false; }

		$sw.addClass('swiper-loading-posts');
		$sw.find('.next_swipe').addClass('loading');
		var data = { _ajax_nonce: shrk.ajax.nonce };

		jQuery.extend(data, args);
		jQuery.post(shrk.ajax.ajaxurl, data, function(response) {
			if ( response.result === 'OK' ) {
				swiper.appendSlide(response.data);
				$sw.data('swiperQryPage', response.page);							
			} else if (response.result === 'NO_POSTS_FOUND' ) {
				$sw.addClass('no-more-posts');
			}
			$sw.find('.next_swipe').removeClass('loading');
			$sw.removeClass('swiper-loading-posts');
		});
	},

	vcAnimations: function() {
		// Get (only) slides that have animated elements in them and are not active
		var $slides = jQuery('.wpb_animate_when_almost_visible').closest('.swiper-slide:not(.swiper-slide-active)');
		$slides.each( function () {
			$slides.find('.wpb_animate_when_almost_visible').removeClass('animated wpb_start_animation');
			var sw_index = shrk.swipers.getIndex( jQuery(this).closest('.shrk-swiper-container') );
			shrk.swipers.instances[sw_index].on( 'onSlideChangeEnd', function(swiper) { 
				jQuery(swiper.container).find('.swiper-slide.swiper-slide-active .wpb_animate_when_almost_visible').addClass('wpb_start_animation animated');
				jQuery(swiper.container).find('.swiper-slide:not(.swiper-slide-active) .wpb_animate_when_almost_visible').removeClass('wpb_start_animation animated');
			});
		});
	}
};

jQuery( document ).ready(function( $ ) {

	// Bind to VC resize events
	$(window).on('shrk_resize shrk_swipers_init vc_js resize.vcRowBehaviour shrk_after_vc-full-width-row', function () {
		shrk.swipers.updateAll();
	});

	// Take care of VC animations in swipers
	$(window).on('shrk_swipers_init vc_js', function () {
		setTimeout( function () {
			shrk.swipers.vcAnimations();
		}, 1000);	
	});

	// Bind to swipers init. Could get called somewhere else
	$(window).on('shrk_swipers_init', function () {
		// Lock swiping when not needed
		$('.one-slide > .shrk-swiper-container, .one-slide.shrk-swiper-container').each( function () {
			shrk.swipers.instances[shrk.swipers.getIndex($(this))].lockSwipes();
		});

		$('.xy-slider .inner.swiper-auto-load-slides').each( function() {
			var s = shrk.swipers.instances[shrk.swipers.getIndex($(this))];

			if ( typeof(s) === 'undefined' ) {
				return;
			}

			s.on('onReachEnd', function( s ) { 
				var ajax_args = {
					action: 'shrk_get_slide_products'
				};

				var qry_att_prefix = 'swiperQry';
				var atts = jQuery(s.container).data();

				for (var prop in atts) {
					if ( prop.indexOf(qry_att_prefix) === 0 ) {
						ajax_args[prop.slice(qry_att_prefix.length).toLowerCase()] = atts[prop];
					}
				}

				//advance page
				ajax_args.page++;

				if ( typeof(shrk.swipers.sc_load_posts) === 'function' ) {
					shrk.swipers.sc_load_posts( ajax_args, s );				
				}
			});
		});

		jQuery('.xy-slider .open-inner-slide').on('click', function (e) {
			shrk.swipers.instances[shrk.swipers.getIndex(jQuery(this).closest('.shrk-swiper-container'))].slideNext();
			e.stopImmediatePropagation();
			return false;
		});

		jQuery('.xy-slider .shrk-swiper-container.inner').each( function () {
			var s = shrk.swipers.instances[shrk.swipers.getIndex(jQuery(this))];

			if ( typeof(s) === 'undefined' ) {
				return;
			}

			s.on('onSlideChangeStart', function (s) {
				if ( s.activeIndex === 0 ) {
					$(s.container).closest('.xy-slider').removeClass('inner-slide-open');
				} else {
					$(s.container).closest('.xy-slider').addClass('inner-slide-open');
					$(s.container).find('.swiper-product-count span.count').html(s.activeIndex);

					if ( parseInt( $(s.container).find('.swiper-product-count').attr('data-count'), 10 ) === s.activeIndex ) {
						$(s.container).addClass('no-more-posts');
						$(s.container).removeClass('swiper-loading-posts');
						$(s.container).find('.next_swipe').removeClass('loading');
					}

					// Trim arrows position on mobile
					if ( $(window).width() < 768 ) {
						$(s.container).find('.prev_swipe, .next_swipe').css({
							'transform' : 'translateY(' + ( ( 80 - $(s.container).find('.swiper-slide-active .slide-content').outerHeight() ) / 2 ) + 'px)'
						});
					}
				}
			});
		});

		jQuery('.xy-slider > .shrk-swiper-container').each( function () { //outer
			var s = shrk.swipers.instances[shrk.swipers.getIndex(jQuery(this))];

			if ( typeof(s) === 'undefined' ) {
				return;
			}

			s.on('onSlideChangeStart', function (s) { //on each outer slide change
				//reset inner to 1st slide, after 300ms to hide the change
				setTimeout( function () {
					$(s.container).find('.shrk-swiper-container.inner').each( function () {
						shrk.swipers.instances[shrk.swipers.getIndex($(this))].slideTo(0);	
					});
				}, 300);

				$(s.container).closest('.xy-slider').removeClass('inner-slide-open'); //but remove class now
				shrk.swipers.xyPaginationUpdate( s );
			});
		});

		jQuery('.xy-slider .shrk-swiper-container .swiper-nav-outer .nav-thumb').on('click', function () {
			var sw_el = jQuery(this).closest('.shrk-swiper-container');
			var swiper = shrk.swipers.instances[shrk.swipers.getIndex( sw_el )];
			var clicked_index = jQuery(this).data('slide-id');
			swiper.slideTo( clicked_index );
			shrk.swipers.xyPaginationUpdate( swiper );
			jQuery(this).closest('.swiper-nav-wrapper').removeClass('swiper-nav-force-show');

			return false;
		});

		jQuery('.xy-slider .shrk-swiper-container .swiper-nav-wrapper .toggle-button').on('click', function () {
			jQuery(this).closest('.swiper-nav-wrapper').toggleClass('swiper-nav-force-show');
		});


	});

	$(window).on('shrk_swiper_init', function (e, s) {
		if ( typeof( imagesLoaded ) !== 'undefined' ) {
			// Re set swiper autoheight when images are loaded
			jQuery(s.container).find('.swiper-slide.swiper-slide-active').imagesLoaded( function () {
				var $container = jQuery(this.elements).closest('.shrk-swiper-container');
				var swiper = shrk.swipers.getSwiper( $container );

				if ( typeof(swiper) !== 'undefined' && swiper.params.autoHeight ) {
					swiper.updateAutoHeight();
				}

				// Also fix arrows position while we are it.
				if ( typeof ( shrk.woo ) !== 'undefined' && typeof ( shrk.woo.swiper_fix_nav_loc ) !== 'undefined' ) {
					shrk.woo.swiper_fix_nav_loc();
				}
			});
		}
	});

	// Bind to init_page. Could get called via ajax.
	$(window).on('shrk_init_page', function () {
		shrk.swipers.initialize();
	});

	jQuery('.vc_tta-tabs-list .vc_tta-tab > a').on('click', function() {
		var tab_id = jQuery(this).attr('href');

		jQuery( tab_id ).find( '.shrk-swiper-container' ).each( function () {
			shrk.swipers.fix_too_lazyImages( jQuery( this ) );
		});
	});

	jQuery("[data-vc-accordion]").on("show.vc.accordion", function(e) {
		setTimeout( function () {
			jQuery( '.vc_tta .vc_tta-panel.vc_active' ).find( '.shrk-swiper-container' ).each( function () {
				shrk.swipers.fix_too_lazyImages( jQuery(this) );
			});
		}, 100);
	});

	if ( typeof( imagesLoaded ) !== 'undefined' ) {
		jQuery('.swiper-nav-outer .nav-thumb').imagesLoaded({ background: '.thumb-bg' }, function () { 
			jQuery(this.elements).find('.thumb-bg').addClass('ready');
		});
	} else {
		jQuery('.swiper-nav-outer .nav-thumb .thumb-bg').addClass('ready');
	}

});