/* jshint esversion: 6 */
( function( $ ) {

	'use strict';

//	const jQueryLoaded = ( 'function' === typeof jQuery );

	if ( 'function' !== typeof window.vcexLoadMore ) {
		window.vcexLoadMore = function( $context ) {

			$( '.vcex-loadmore' ).each( function() {

				var $buttonWrap = $( this );
				var $button     = $buttonWrap.find( '.vcex-loadmore-button' );

				if ( ! $button.length ) {
					return;
				}

				var $grid = $buttonWrap.parent().find( '> .wpex-row, > .entries, > .vcex-recent-news, .vcex-image-grid, .wpex-post-cards-list, .wpex-post-cards-grid' );
				var grid = $grid[0];
				var loading = false;
				var ajaxUrl = vcex_loadmore_params.ajax_url;
				var loadMoreData = $button.data();
				var page = loadMoreData.page + 1;
				var maxPages = loadMoreData.maxPages;
				var $textSpan = $button.find( '.vcex-txt' );
				var text = loadMoreData.text;
				var loadingText = loadMoreData.loadingText;
				var failedText = loadMoreData.failedText;
				const infiniteScroll = loadMoreData.infiniteScroll;
				var $newElements = '';

				if ( ! infiniteScroll ) {
					$buttonWrap.css( 'min-height', $buttonWrap.outerHeight() ); // prevent jump when showing loader icon
				}

				var renderGrid = function( res ) {
					if ( 'object' === typeof wpex && 'function' === typeof wpex.equalHeights ) {
						wpex.equalHeights();
					}

					if ( 'function' === typeof Isotope && ( $grid.hasClass( 'vcex-isotope-grid' ) || $grid.hasClass( 'vcex-navbar-filter-grid' ) || $grid.hasClass( 'wpex-masonry-grid' ) ) ) {
						var isotope = Isotope.data( grid );
						if ( isotope ) {
							isotope.appended( $newElements );
							isotope.layout();
						} else {
							$newElements.css( 'opacity', '' );
						}
					} else {
						$newElements.css( 'opacity', '' );
					}

					if ( $grid.hasClass( 'justified-gallery' ) && 'undefined' !== typeof $.fn.justifiedGallery ) {
						$grid.justifiedGallery( 'norewind' );
					}

					if ( 'object' === typeof wpex ) {
						if ( 'function' === typeof wpex.hoverStyles ) {
							wpex.hoverStyles();
						}
					}

					if ( 'function' === typeof vc_waypoints ) {
						vc_waypoints();
					} else {
						$( '.wpb_animate_when_almost_visible', $grid ).addClass( 'wpb_start_animation animated' );
					}

					if ( 'function' === typeof window.wpexSliderPro ) {
						window.wpexSliderPro( $newElements );
					}

					if ( 'undefined' !== typeof $.fn.mediaelementplayer ) {
						$newElements.find( 'audio, video' ).mediaelementplayer();
					}

					$grid.trigger( 'vcexLoadMoreFinished', [$newElements] ); // Use this trigger if you need to run other js functions after items are loaded

					// Update loadMoreData with new data (used for clearing floats, running count, etc).
					var newData  = $( res.data ).find( '.vcex-loadmore-button' ).data();
					loadMoreData = newData ? newData : loadMoreData;

					if ( infiniteScroll ) {
						$buttonWrap.addClass( 'wpex-invisible' );
					}

					$button.parent().removeClass( 'vcex-loading' );
					$textSpan.text( text );

					// Set correct focus.
					if ( ! infiniteScroll ) {
						var $firstLink = $newElements.first().find( 'a' );
						if ( $firstLink.length ) {
							$firstLink.eq(0).focus();
						}
					}

					// Hide button after last page.
					if ( ( page - 1 ) == maxPages ) {
						$buttonWrap.hide();
					}

					// Set loading to false.
					loading = false;
				};

				$button.on( 'click', function( e ) {

					var shortcodeParams = loadMoreData.shortcodeParams; // this gets updated on each refresh

					shortcodeParams.paged = page; // update paged value

					if ( ! loading ) {

						loading = true;

						if ( infiniteScroll ) {
							$buttonWrap.removeClass( 'wpex-invisible' );
						}

						$button.parent().addClass( 'vcex-loading' );
						$textSpan.text( loadingText );

						var data = {
							action: 'vcex_loadmore_ajax_render',
							nonce: loadMoreData.nonce,
							shortcodeTag: loadMoreData.shortcodeTag,
							shortcodeParams: shortcodeParams
						};

						$.post( ajaxUrl, data, function( res ) {

							if ( res.success ) {

								page = page + 1;

								if ( $grid.parent().hasClass( 'vcex-post-type-archive' ) ) {
									$newElements = $( res.data ).find( '> .wpex-row > .col, > .wpex-row > .blog-entry, #blog-entries > .blog-entry' );
								} else {
									$newElements = $( res.data ).find( '> .wpex-row > .vcex-grid-item, > .vcex-recent-news > .vcex-recent-news-entry-wrap, .vcex-image-grid-entry, .wpex-post-cards-entry, .wpex-card-list-divider' );
								}

								if ( $newElements.length ) {

									$newElements.css( 'opacity', 0 ); // hide until images are loaded

									$newElements.each( function() {
										var $this = $( this );
										if ( $this.hasClass( 'sticky' ) ) {
											$this.addClass( 'vcex-duplicate' );
										}
									} );

									// Append items.
									$grid.append( $newElements );

									// Render the grid.
									if ( 'function' === typeof imagesLoaded ) {
										imagesLoaded( grid, function() {
											renderGrid( res );
										} );
									} else {
										renderGrid( res );
									}

									// Refesh waypoints.
									if ( 'function' === typeof VcWaypoint ) {
										VcWaypoint.refreshAll();
									}
									if ( 'function' === typeof Waypoint ) {
										Waypoint.refreshAll();
									}

								} // End $newElements check.

								else {

									console.log( res );

								}

							} // End success.

							else {
								$button.text( failedText );
								console.log( res );
							}

						} ).fail( function( xhr, textGridster, e ) {
							console.log( xhr.responseText );
						} );

					} // end loading check

					return false;

				} ); // end click event

			} );

		};
	}

	if ( 'function' !== typeof window.vcexLoadMoreInfiniteScroll ) {
		window.vcexLoadMoreInfiniteScroll = function() {
			const isTargets = document.querySelectorAll( '.vcex-loadmore--infinite-scroll .vcex-loadmore-button' );
			let scrollPos = 0;

			if ( ! isTargets ) {
				return;
			}

			const debounce = (callback, wait = 10) => {
				let timeoutId = null;
				return (...args) => {
					window.clearTimeout(timeoutId);
					timeoutId = window.setTimeout(() => {
					  callback.apply(null, args);
					}, wait);
				};
			};

			const isInViewport = ( element ) => {
				const elementTop     = $(element).offset().top;
				const elementBottom  = elementTop + $(element).outerHeight();
				const viewportTop    = $(window).scrollTop();
				const viewportBottom = viewportTop + $(window).height();
				return elementBottom > viewportTop && elementTop < viewportBottom;
			};

			const scrollMonitor = debounce( (ev) => {
				let windowY = window.scrollY;
				if ( windowY > scrollPos ) {
					isTargets.forEach( ( button ) => {
						if ( isInViewport( button ) ) {
							button.click();
						}
					} );
				}
				scrollPos = windowY;
			}, 10);

			window.addEventListener( 'scroll', scrollMonitor );
		};
	}

	$( window ).on( 'load', function() {
		vcexLoadMoreInfiniteScroll();
		vcexLoadMore();
	} );

} ) ( jQuery );