//jQuery won't conflict with other libraries that might use $
jQuery.noConflict();

jQuery(function($) {
	//jQuery Document Ready
	console.log('oh heck. you are doing me an inspect');

	// http://isotope.metafizzy.co/

	// recipe isotope init

	var currentFilterWith = '';

	//region pagination variables
	var pagerClass = 'isotope-product-pager';
	var pageAttribute = 'data-page';
	var currentPaginatedFilterSelector = '';
	var currentNumberPages = 1;
	var currentPage = 1;
	//endregion

	var itemSelector = '.product-tile';

	var $isotopedProd = $('#product_tiles').imagesLoaded(function() {
		$isotopedProd.isotope({
			itemSelector: itemSelector,
			// containerStyle: null,
			layoutMode: 'masonry'
		});
	});
	console.log($isotopedProd);
	// note... containerStyle: null works just fine on recipes, regardless of if there's a filter section
	// but if there's no filter section on Products, having containerStyle: null will break the layout.
	// product_tiles gets an assigned height, but doesn't get "position:relative" like it's supposed to


	function updateProductFilter() {
		console.log("updateProductFilter");
		// prefixes are
		// prodcat-
		// this is for use with hash so we can tell what's what, to update the filter dropdowns/tiles
		// if the user comes to the page already with a hash
		var tagClasses = '';

		$('.type-tile:not(.off)').each(function() {
			tagClasses += $(this).data('tagslug') + ', ';
		});

		if (tagClasses != '') {
			// clip off the trailing ", "
			tagClasses = tagClasses.substring(0, tagClasses.length - 2);
		}

		$isotopedProd.isotope({filter: tagClasses});
		console.log(tagClasses);


		// show results count (if enabled)
		if ($('#results_count').length) {
			showResultsCount();
		}

		// update the hash (if enabled)
		if ($('#products_filters').data('usefilterhash') === 'please') {
			// var hashit = tagClasses.replace(/\./g, '+').replace(/ /g, '').replace('+','');
			var hashit = tagClasses
			.replace(/\./g, '+')
			.replace(/ /g, '')
			.replace(/,/g, '')
			.replace('+', ''); // dumps the first + that shows up (at the beginning)
			// I'm using this instead of escape() so the url doesn't look completely unreadable
			window.location.hash = hashit;
		}

		// pagination (if enabled)
		/*
		if ($('.products_pagination').length) {
			setPagination();
			goToPage(1);
		}
		*/
	}



	// if there's already a hash... use it to pre-set the filters
	if (window.location.hash.length > 0) {
		// if we are actually USING the hash, pre-set the filters
		if ($('#products_filters').data('usefilterhash') == 'please') {
			var hashthing = window.location.hash.replace('#', '');

			// if there's more than one, break it apart
			if (hashthing.indexOf('+') !== -1) {
				var selections = hashthing.split("+");
			} else {
				// if there's just one, put it into an array by itself
				var selections = Array(hashthing);
			}
			console.log(selections);

			selections.forEach(function(onething) {
				if (/^type-/.test(onething)) {
					$(".type-tile[data-tagslug='." + onething + "']").removeClass("off");
				}
			});
		} else {
			// if there is a hash but we're not using it, clean it off
			if ("pushState" in history) {
				// cleans it off including the hash mark
				var scrollV, scrollH, loc = window.location;
				history.pushState("", document.title, loc.pathname + loc.search);
			} else {
				// if browser isn't capable of this (IE 9 and below *shakes fist*)
				// just do this, which leaves the hash but doesn't cause the page to reload
				window.location.hash = '';
			}
		}
	}



	function showResultsCount() {
		var resultCount = $('.product-tile' + currentFilterWith).not('#apicius_middle_products_content').length;

		var itemWord;
		if (resultCount == 1) {
			itemWord = 'product';
		}
		else {
			itemWord = 'products';
		}

		if (resultCount === 0) {
			$('#results_count').html('No ' + itemWord + ' to show with this filter selection');
		} else {

			if ($('.product_pagination').length) {
				var showingStart, showingEnd;

				var itemsPerPage = $('.product_pagination').data('items-count');

				showingStart = ((currentPage - 1) * itemsPerPage) + 1;
				showingEnd = currentPage * itemsPerPage;
				if (showingEnd > resultCount) {
					showingEnd = resultCount;
				}

				$('#results_count').html('Showing ' + showingStart + '-' + showingEnd + ' of ' + resultCount + ' ' + itemWord);
			} else {
				$('#results_count').html('Found ' + resultCount + ' ' + itemWord);
			}
		}
	}





	//region pagination
	// modified from http://codepen.io/Igorxp5/pen/ojJLQE
	/*
	function setPagination() {
		var SetPageDataOnItems = function() {
			var itemsPerPage = $('.recipes_pagination:first').data('items-count');
			// console.log('itemsPerPage in SetPageDataOnItems: '+itemsPerPage);

			// not currently in use; but could be used to display "1 of xxx pages" or something
			// var itemsLength = $(itemSelector + filterWith).length;
			// console.log('itemsLength in SetPageDataOnItems: '+itemsLength);
			// var pages = Math.ceil(itemsLength / itemsPerPage);

			var item = 1;
			var page = 1;

			$('.recipe-tile' + currentFilterWith).each(function() {
				if (item > itemsPerPage) {
					page++;
					item = 1;
				}
				$(this).attr(pageAttribute, page);
				item++;
			});
			currentNumberPages = page;
		}();

		var CreatePagers = function() {
			var $pagerDisplayBlock = $('<div class="' + pagerClass + '"></div>');
			$pagerDisplayBlock.html('');

			if (currentNumberPages > 1) {
				$pagerDisplayBlock.append('<div class="recipe_pager_prev_arrow"></div>');
				for (var i = 0; i < currentNumberPages; i++) {
					var $pager = $('<div class="pager" ' + pageAttribute + '="' + (i + 1) + '"></div>');
					$pager.html(i + 1);

					$pager.click(function() {
						var page = $(this).eq(0).attr(pageAttribute);
						goToPage(page);
					});
					$pager.appendTo($pagerDisplayBlock);
				}

				$pagerDisplayBlock.append('<div class="recipe_pager_next_arrow"></div>');
			}
			$('.recipes_pagination *').replaceWith($pagerDisplayBlock);
		}();
	}

	function goToPage(n) {
		currentPage = n;
		var exploded = currentFilterWith.split(',');
		var selector = '';
		for (var i = 0; i < exploded.length; i++) {
			selector += exploded[i] + '[' + pageAttribute + '="' + currentPage + '"], ';
		}
		currentPaginatedFilterSelector = selector.slice(0, -2);

		$isotoped.isotope({filter: currentPaginatedFilterSelector});

		// need to collapse the middle numbers if there's too many
		// keep the first and the last
		// show the ones left and right of current page
		// collapse anything else
		// so there should be at least 7 pages for this to happen
		if (currentNumberPages > 6 && ($('.recipes_pagination:first').data('collapse') === true)) {
			var ellipsisOn = false;

			// whether or not the ellipsis is "on" handles the logic for
			// whether to show just one ellipsis, or two; if there's anything collapsed between
			// the beginning and the current page, but also between the current page and the end
			// 1 ... 4 5 6 ... 9  < 5 is the current page
			// 1 2 ... 9 < 1 is the current page
			// 1 ... 7 8 9 < 8 is the current page
			// 1 ... 8 9 < 9 is the current page

			$('.apicius-ellipsis').remove();

			$('.' + pagerClass + ' .pager').each(function() {
				var thisOne = $(this);
				var thisOnesNumber = parseFloat(thisOne.data('page'));

				thisOne.removeClass('collapse');
				if (
					// not the first
				(thisOnesNumber !== 1)
				// not the last
				&& (thisOnesNumber !== parseFloat(currentNumberPages))
				// not the current
				&& (thisOnesNumber !== parseFloat(currentPage))
				// not the one before the current
				&& (thisOnesNumber !== parseFloat(currentPage) - 1)
				// not the one after the current
				&& (thisOnesNumber !== parseFloat(currentPage) + 1)
				) {
					thisOne.addClass('collapse');
					if (!ellipsisOn) {
						thisOne.after('<span class="apicius-ellipsis">...</span>');
					}
					ellipsisOn = true;
				} else {
					ellipsisOn = false;
				}
			});
		}

		$('.' + pagerClass + ' .pager').removeClass('current');
		$('.' + pagerClass + ' .pager[' + pageAttribute + '=' + n + ']').addClass('current');

		//region prev/next button activation/deactivation
		if (parseFloat(currentPage) > 1) {
			$('.recipe_pager_prev_arrow').addClass('active');
		} else {
			$('.recipe_pager_prev_arrow').removeClass('active');
		}

		if (parseFloat(currentPage) < parseFloat(currentNumberPages)) {
			$('.recipe_pager_next_arrow').addClass('active');
		} else {
			$('.recipe_pager_next_arrow').removeClass('active');
		}
		//endregion

		showResultsCount();

		// placeMiddleBlock();
	}


	$('.products_pagination').on('click', '.product_pager_prev_arrow.active', function() {
		goToPage(parseFloat(currentPage) - 1);
	});
	$('.products_pagination').on('click', '.product_pager_next_arrow.active', function() {
		goToPage(parseFloat(currentPage) + 1);
	});
*/
	//endregion





	// in case they later want to be able to link in with a category already selected
	// this needs to be run when the page loads
	if (isFilterable()) {
		updateProductFilter();
	}



	//region on change of any filters
	$('#products_list .type-tile').on('click', function() {
		$(this).toggleClass('off');
		updateProductFilter();
	});

	$('#products_list #view_all').on('click', function() {
		$('.type-tile').addClass('off');
		updateProductFilter();
	});
	//endregion




	function isFilterable() {
		return ($('#product_types').length);
	}



});

