/**
 * Query Loop Scripts
 * - post-slider
 * - sorting
 * - table sorting
 * 
 * Moved from classic greyd default.js
 */

var greyd = greyd || {};

( function() {
	jQuery( function() {
		if ( typeof $ === 'undefined' ) $ = jQuery;

		greyd.query.init();

		console.log( "Query Scripts: loaded" );
	} );
} )( jQuery );


/**
 * init greyd.query var
 */
greyd.query = greyd.query || {};

/**
 * init all query features
 */
greyd.query.init = function() {
	greyd.query.slider.init();
	greyd.query.sorting.init();
	greyd.query.table.init();
}


/**
 * slider features
 * 
 * was global default.js variable 'post'
 */
greyd.query.slider = new function() {
	
	this.init = function() {
		this.addEvents();
		// console.log('Posts Pagination Script: loaded');
	}
	
	this.addEvents = function() {
		var wrapper = $(".greyd-posts-slider.js");
		if (wrapper.length > 0) {

			wrapper.each(function() {
				if ($(this).hasClass('autoplay')) {
					var time = $(this).data('interval')*1000;
					var that = this;
					$(this).timer = setInterval(function() {
						if (!$(that).hasClass('pause') && !$(that).hasClass('forcePause')) {
							greyd.query.slider.paginateNext($(that));
						}
					}, time);
					// $(this).on('mouseenter', function() {
					//     if ( !$(that).hasClass('pause') ) {
					//         $(that).addClass('pause');
					//         $(this).on('mouseleave', function() {
					//             $(that).removeClass('pause');
					//         });
					//     }
					// });
				}
				
				$(this).off('next').on('next', function() {
					greyd.query.slider.paginateNext(this);
				});
				$(this).off('prev').on('prev', function() {
					greyd.query.slider.paginatePrevious(this);
				});
				$(this).off('first').on('first', function() {
					greyd.query.slider.paginate(this, 1);
				});
				$(this).off('last').on('last', function() {
					var pages = $(this).find('.query-page');
					greyd.query.slider.paginate(this, pages.length);
				});
				$(this).off('stop').on('stop', function() {
					$(this).addClass('forcePause pause');
				});
				$(this).off('start').on('start', function() {
					$(this).removeClass('forcePause pause');
				});
			});

			// next/previous
			$('.greyd-posts-slider.js .pagination > a, .greyd-posts-slider.js a.pgn_arrows, .greyd-posts-slider.js .pgn_arrows a').off('click').on("click", function(e) {
				var wrapper = $(this).closest('.greyd-posts-slider');
				wrapper.trigger( $(this).data('pagelink') );
				wrapper.trigger('stop');
			});
			
			// numbers
			$('.greyd-posts-slider.js .pagination > .pgn_numbers > a').off('click').on("click", function(e) {
				var wrapper = $(this).closest('.greyd-posts-slider');
				greyd.query.slider.paginate( wrapper, $(this).data('pagelink') );
				wrapper.trigger('stop');
			});

			// touch support
			$('.greyd-posts-slider.js').off('touchstart').on('touchstart', function(e) { 
				greyd.query.slider.touchStart(this, e);
				$(this).trigger('stop');
			});
			$('.greyd-posts-slider.js').off('touchmove').on('touchmove', function(e) {
				greyd.query.slider.touchMove(this, e);
				$(this).trigger('stop');
			});

			// size wrapper
			window.addEventListener("resize", function() { 
				greyd.query.slider.calc()
			});
			setTimeout(function(){
				greyd.query.slider.calc()
			}, 100);
			
			$(document).keydown(function(e){
				// arrow left
				if (e.keyCode == 37) {
					var wrapper = $(".greyd-posts-slider.js:hover");
					if ( wrapper.length > 0 ) {
						wrapper.trigger('prev');
						wrapper.trigger('stop');
					}
					return false;
				}
				// arrow right
				if (e.keyCode == 39) {
					var wrapper = $(".greyd-posts-slider.js:hover");
					if ( wrapper.length > 0 ) {
						wrapper.trigger('next');
						wrapper.trigger('stop');
					}
					return false;
				}
			});
		}
	}

	this.calc = function() {
		$('.greyd-posts-slider.js .query-pages-wrapper').each(function(e) {
			var pages   = $(this).find('.query-page');
			var wrapper = $(this).closest('.greyd-posts-slider');
			var current = wrapper.data('currentpage');

			var offset  = pages[current-1].offsetLeft;

			// console.log(offset);
			// $(this).finish().animate({ scrollLeft: offset }, 0);
			
			// get slider height
			var height = $(this)[0].offsetHeight+"px";
			var newHeight = null;

			/**
			 * Adjust the slider height.
			 * 
			 * The naming of the options are misleading:
			 * (1) 'auto'   =>  'as high as highest slide'
			 *                  This is called auto, because the height of the slider
			 *                  is automatically this way due to 'display: flex'. We
			 *                  do not need to do anything in JS.
			 * (2) 'max'    =>  'adjust automatically'
			 *                  We need to adjust the slider's height to the height
			 *                  of the current slide each step.
			 * (3) 'custom' =>  'manual height'
			 *                  Set the height to a manual input.
			 */
			if ( wrapper.data('height') == 'auto' ) {
				// (1)
			}
			else if ( wrapper.data('height') === 'max') {
				// (2)
				newHeight = pages.length > 1 ? pages[current-1].offsetHeight+"px" : null;
			}
			else {
				// (3)
				newHeight = wrapper.data('height');
				if ( screen.width <= 767 && typeof wrapper.data('height_mobile') != 'undefined' && wrapper.data('height_mobile') != 'max' ) {
					newHeight = wrapper.data('height_mobile');
				}
			}

			// set height for new slider
			if (newHeight) {
				height = newHeight;
				$(this).css('height', height);
			}
		});
	}

	this.paginateNext = function(wrapper) {
		// console.log("next page");
		var newpage = $(wrapper).data('currentpage')+1;
		this.paginate(wrapper, newpage);
	}
	this.paginatePrevious = function(wrapper) {
		// console.log("previous page");
		var newpage = $(wrapper).data('currentpage')-1;
		this.paginate(wrapper, newpage);
	}
	this.paginate = function(wrapper, newpage) {

		var current = $(wrapper).data('currentpage');
		var pages = $(wrapper).find('.query-page');//.children();
		// console.log("current page: "+current);
		// console.log("new page: "+newpage);
		// console.log(pages);
		if (current == newpage) return;
		if ($(wrapper).hasClass('loop')) {
			if (newpage < 1) newpage = pages.length;
			if (newpage > pages.length) newpage = 1;
		}
		else {
			if (newpage < 1) return;
			if (newpage > pages.length) return;
		}

		var resultsWrapper = $(wrapper).find('.query-pages-wrapper');
		var activeStep = pages[newpage-1];
		
		$(wrapper).data('currentpage', newpage);
		pages.removeClass('is-current is-prev is-next');
		$(pages[newpage-2]).addClass('is-prev');
		$(activeStep).addClass('is-current');
		$(pages[newpage]).addClass('is-next');

		// offset
		var offset = activeStep.offsetLeft;

		// speed
		var speed = 200; // $('.navigation').data('mod-anim')*1000;
		if ( $(wrapper).data('animation') == 'none' ) {
			speed = 0;
		}

		var height = pages.offsetHeight+"px"; // default height
		var prev = $(wrapper).find('.pgn_previous');//.children()[0];
		var next = $(wrapper).find('.pgn_next');//.children()[2];
		
		// custom height
		if ($(wrapper).data('height') != 'auto') {
			if ($(wrapper).data('height') === 'max') {
				height = activeStep.offsetHeight+"px";
			} else {
				height = $(wrapper).data('height');
				if ( screen.width <= 767 && typeof $(wrapper).data('height_mobile') != 'undefined' && $(wrapper).data('height_mobile') != 'max' )
					height = $(wrapper).data('height_mobile');
			}
		}

		// animate slider
		if ($(wrapper).data('animation') == 'fade') {
			$(resultsWrapper).finish().animate({ opacity: 0 }, speed);
			setTimeout(function() {
				$(resultsWrapper).animate({ scrollLeft: offset }, 0);
				$(resultsWrapper).finish().animate({ opacity: 1, height: height }, speed);
			}, speed);
		}
		else if ($(wrapper).data('animation') == 'cover') {
			// the cover-flow animation is entirely handled by CSS
			$(resultsWrapper).finish().animate({ height: height }, speed, 'swing');
		}
		else {
			$(resultsWrapper).finish().animate({ scrollLeft: offset, height: height }, speed, 'swing');
		}

		// scroll to top
		if ( $(wrapper).hasClass('slider_scroll_top') ) {
			var offsetTop = $(wrapper).offset().top - 100;
			if ( $(document).scrollTop() > offsetTop ) {
				if ( typeof nav !== 'undefined' ) nav.scrollTo( offsetTop );
				else $( 'html, body' ).animate( { scrollTop: offsetTop }, 0.3 );
			}
		}
		
		// pagination
		var pg_wrapper = $(wrapper).find('.pagination');
		if ( pg_wrapper.length ) {
			var pg_pages = $(pg_wrapper).find('.pgn_numbers').children();
			var iconnormal = $(pg_wrapper).data('iconnormal') ?? $(pg_wrapper).find('.pgn_numbers').data('iconnormal');
			var iconactive = $(pg_wrapper).data('iconactive') ?? $(pg_wrapper).find('.pgn_numbers').data('iconactive');
			var imgnormal = $(pg_wrapper).data('imgnormal') ?? $(pg_wrapper).find('.pgn_numbers').data('imgnormal');
			var imgactive = $(pg_wrapper).data('imgactive') ?? $(pg_wrapper).find('.pgn_numbers').data('imgactive');
	
			for (var i=0; i<pg_pages.length; i++) {
				// console.log("pagination ");
				// console.log($(pg_pages[i]));
				var p = $(pg_pages[i]);
				if (!$(p).hasClass('pgn_number')) p = $(p).find('.pgn_number');
				if ($(pg_pages[i]).data('pagelink') == current) {
					$(p).removeClass('pgn_current');
					if (typeof iconactive !== 'undefined') $(p).removeClass(iconactive);
					if (typeof iconnormal !== 'undefined') $(p).addClass(iconnormal);
					if (typeof imgnormal !== 'undefined') $(p).children().attr('src', imgnormal);
				}
				if ($(pg_pages[i]).data('pagelink') == newpage) {
					$(p).addClass('pgn_current');
					if (typeof iconnormal !== 'undefined') $(p).removeClass(iconnormal);
					if (typeof iconactive !== 'undefined') $(p).addClass(iconactive);
					if (typeof imgactive !== 'undefined') $(p).children().attr('src', imgactive);
				}
			}
		}

		$(prev).removeClass('pgn_current');
		if (newpage == 1) $(prev).addClass('pgn_current');
		$(next).removeClass('pgn_current');
		if (newpage == pages.length) $(next).addClass('pgn_current');

		// trigger custom JS event
		$(wrapper).trigger("greyd_slider_paginate", [newpage] );
	}
	 
	this.xDown = null; 
	this.touchStart = function(el, evt) {
		greyd.query.slider.xDown = evt.originalEvent.touches[0].clientX;
	}
	this.touchMove = function(el, evt) {
		if (!greyd.query.slider.xDown) {
			return;
		}
		var xUp = evt.originalEvent.touches[0].clientX;    
		var xDiff = greyd.query.slider.xDown - xUp;    
		if (xDiff > 50) {
			// console.log("scroll right");
			$(el).trigger('next');
			$(el).trigger('stop');
			greyd.query.slider.xDown = null; 
		}
		else if (xDiff < -50)  {
			// console.log("scroll left");
			$(el).trigger('prev');
			$(el).trigger('stop');
			greyd.query.slider.xDown = null; 
		}
	}
	
	this.triggerNext = function(el) {
		// console.log(el);
		$(el).closest('.wp-block-query').find('.greyd-posts-slider.js').trigger('next');
	}
	this.triggerPrevious = function(el) {
		// console.log(el);
		$(el).closest('.wp-block-query').find('.greyd-posts-slider.js').trigger('prev');
	}
	this.triggerIndex = function(el, index) {
		// console.log(el);
		$(el).closest('.wp-block-query').find('.greyd-posts-slider.js').each(function() {
			greyd.query.slider.paginate(this, index);
		});
	}
	
}

/**
 * sort posts in frontend via dropdown
 * 
 * was global default.js variable 'sorting'
 */
greyd.query.sorting = new function() {

	this.init = function() {
		// return if not needed
		if ($(".greyd-posts-slider").length === 0) return false;
		
		// normal pages
		if (!($(".greyd-posts-slider.js").length === 0)) {
			this.addEvents();
		}
		// search page
		else {
			if ($('.greyd-posts-slider').attr("live-search") == "true") {
				return false
			} else {
				this.startQuery();
			}
		}
	}

	this.addEvents = function() {
		const sortingDropdown = $('.greyd-posts-slider').find('.sorting');
		sortingDropdown.each(function() {
			var wrapper = $(this);
			var select  = wrapper.find("select");
			var slider  = wrapper.parent();
			var results = slider.find($(".query-post"));

			// sort and redistribute search results
			select.off("change").on("change", function() {
				console.log(slider);
				console.log(results);
				var sorted_elements = greyd.query.sorting.sortElements($(this).val(), results);
				// console.log(sorted_elements);
				greyd.query.sorting.distributeElements(sorted_elements, slider);
			});
		});
		
		$('[id^="filter_"]').each(function() {
			var results = $(this).siblings('[id^="slider_"]').find($(".query-post"));
			if (results) {
				var select = $(this).find("select");
				var filter = select.val();
				$(results).each(function() {
					greyd.query.sorting.filterElements(this, filter);
				});
				select.off("change").on("change", function() {
					var filter = $(this).val();
					$(results).each(function() {
						greyd.query.sorting.filterElements(this, filter);
					});
				});
			}
		});
	}

	this.filterElements = function(el, filter) {
		var vals = JSON.parse(decodeURIComponent($(el).data('filter')));
		filter = parseInt(filter);
		if (filter == null || filter == -1 || vals.indexOf(filter) != -1)
			$(el).css('display', 'block');
		else
			$(el).css('display', 'none');
	}

	this.sortElements = function(mode, search_results) {

		search_results.sort(function (a, b) {

			if (~mode.indexOf("title")) {
				// propably do that via php...
				// var compA = a.dataset.title.toLowerCase().replace(/[^a-zA-Z0-9 ]/g, "");
				// var compB = b.dataset.title.toLowerCase().replace(/[^a-zA-Z0-9 ]/g, "");
				var compA = a.dataset.title;
				var compB = b.dataset.title;
			}
			else if (~mode.indexOf("date")) {
				var compA = a.dataset.date;
				var compB = b.dataset.date;
			}
			else if (~mode.indexOf("views")) {
				// propably do that via php...
				// var compA = (a.dataset.postviews != 0) ? parseInt(a.dataset.postviews) : 0; 
				// var compB = (b.dataset.postviews != 0) ? parseInt(b.dataset.postviews) : 0;
				var compA = parseInt(a.dataset.postviews); 
				var compB = parseInt(b.dataset.postviews);
			}
			//compare
			if (~mode.indexOf("ASC")) {
				return ((compA < compB) ? -1 : ((compA > compB) ? 1 : 0));
			}
			else if (~mode.indexOf("DESC")) {
				return ((compA > compB) ? -1 : ((compA < compB) ? 1 : 0));
			}
		});  
		return search_results;
	}
	this.distributeElements = function(sorted_elements, parent) {
		var posts_per_page = $(".query-pages-wrapper").data("ppp");
		var pages  = $(".query-page").length;
		var i = 0;

		for (var x = 1; x <= pages; x++) {
			var limit_per_page = 1;
			for (; i < sorted_elements.length;) {
				
				parent.find($('.query-page[data-page="' + x + '"]')).append(sorted_elements[i]);
				i++;
				if (limit_per_page == posts_per_page) {
					break;
				}
				limit_per_page++;
			}                
		} 
	}
	this.startQuery = function() {
		const sortingDropdown = $('.greyd-posts-slider').find('.sorting');
		sortingDropdown.find("select").off("change").on('change', function () {
			var url = $(this).val(); // get selected value
			if (url) { // require a URL
				window.location = url; // redirect
			}
			return false;
		});
	}
	
}

/*
 * jq.TableSort -- jQuery Table sorter Plug-in
 * Copyright (c) 2017 Dmitry Zavodnikov
 * Licensed under the MIT License
 * 
 * was global default.js variable 'tablesort'
 */
greyd.query.table = new function() {
	
	this.init = function() {
		
		// do not init if classic theme is detected
		if ( typeof tablesort !== 'undefined' ) return;

		// return if not needed
		if ( $(".posts_table").length === 0 ) return false;

		this.config  = {
			styles: {
				'sort':     'sortable', 
				'asc':      'ascending', 
				'desc':     'descending', 
				'unsort':   'unsorted'
			},
			defaultColumn: 0,
			defaultOrder: 'asc',
			selector: function(tbody, column) {
				var groups = [];
				$.each($(tbody).find('tr'), function(index, tr) {
					var td = $(tr).find('td')[column];
					groups.push({
						'elem': [tr], 
						'text': $(td).text()
					});
				});
				return groups;
			},
			comparator: function(a, b) {
				function convertToNum(x) { return parseFloat( x.replace(',','.') ); }
				var regex = /^[0-9\s.,]+$/;
				a = a.text, b = b.text;
				if ( a.match(regex) && b.match(regex) ) return convertToNum(b) - convertToNum(a);
				return a.localeCompare(b);
			}
		};
		
		$(".posts_table").each( function(i, wrapper) {
			// Add click listener to the header.
			$.each(greyd.query.table.getSortableTableHeaders(wrapper), function(j, th) {
				$(th).off("click").on("click", function(event) {
					var clickColumn = $.inArray(event.currentTarget, greyd.query.table.getAllTableHeaders( $(this).closest("table") ));
					
					greyd.query.table.changeOrder(wrapper, clickColumn);
				});
				// $(th).append("<span class='icon'><span></span><span></span></span>"); // already added via php
			});
			// Table sort on load
			//greyd.query.table.changeOrder(table, greyd.query.table.config.defaultColumn);
		});
	}
	
	this.getAllTableHeaders = function(wrapper) {
		return $(wrapper).find('thead > tr > th');
	}
	
	this.getNthTableHeaders = function(wrapper, n) {
		return $(wrapper).find('thead > tr > th:nth-child('+(n+1)+')');
	}

	this.getSortableTableHeaders = function(wrapper) {
		return greyd.query.table.getAllTableHeaders(wrapper).filter(function(index){
			return $(this).hasClass(greyd.query.table.config.styles['sort']);
		});
	}

	this.changeOrder = function(wrapper, column) {
		var th = greyd.query.table.getNthTableHeaders(wrapper, column);
		
		// Order
		var sortOrder = greyd.query.table.config.defaultOrder;
		if (th.hasClass(greyd.query.table.config.styles['asc'])) {
			sortOrder = 'desc';
		}
		if (th.hasClass(greyd.query.table.config.styles['desc'])) {
			sortOrder = 'asc';
		}
		
		// Reset
		var headers = greyd.query.table.getSortableTableHeaders(wrapper);
		headers.removeClass( greyd.query.table.config.styles['asc']+" "+greyd.query.table.config.styles['desc'] );
		headers.addClass( greyd.query.table.config.styles['unsort'] );
		
		// Set classes
		th.removeClass(greyd.query.table.config.styles['unsort']);
		th.addClass(greyd.query.table.config.styles[sortOrder]);
		
		// Group
		var tbody = $(wrapper).find('tbody');
		var groups = greyd.query.table.config.selector(tbody, column);

		// Sorting
		groups.sort(function(a, b){
			var res = greyd.query.table.config.comparator(a, b);
			return sortOrder == 'asc' ? res : -1 * res;
		});

		// Change order
		var rows = parseInt( $(wrapper).data('rows') ), i = 0, k = 0;
		$.each(groups, function(i, trList) {
			if ( i === rows * ( k+1 ) ) k++;
			$.each(trList.elem, function(j, tr) {
				tbody[k].append(tr);
			});
			i++;
		});
	}

};
