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

jQuery(function($) {
	//jQuery Document Ready

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


	if ($('#recipes_list').length) {
		//region nice-select
		$('#apicius select').niceSelect();
		// tweak nice-select so that the dropdown is the same width as the imitation select it's coming from
		$('#apicius .nice-select ul.list').each(function() {
			var width = $(this).parents('.nice-select').css('width');
			$(this).css('width', width);
		});
		//endregion


		var currentFilterWith = '';

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

		var itemSelector = '.recipe-tile';

		// recipe isotope init
		var $isotoped = $('#recipe_tiles').imagesLoaded(function() {
			$isotoped.isotope({
				itemSelector: itemSelector,
				containerStyle: null,
				layoutMode: 'masonry'
			});
		});

		// isotope filtering
		function updateRecipeFilter() {
			// prefixes are
			// prod-
			// prodcat-
			// type-
			// 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

			//region collect all selected criteria
			if ($('#recipe_product').length) {
				var productFilter = $('#recipe_product option:selected').attr('value');
			} else {
				var productFilter = '';
			}

			if ($('#recipe_product_cat').length) {
				var catFilter = $('#recipe_product_cat option:selected').attr('value');
			} else {
				var catFilter = '';
			}

			// the string that will hold everything
			var tagClasses = '';

			// recipe types - tiles; can select more than one
			$('.type-tile:not(.off)').each(function() {
				tagClasses += catFilter + productFilter + $(this).data('tagslug') + ', ';
			});
			// there may be a recipe type dropdown, it needs to work the same as the tiles, in case some idiot
			// thinks it's a good idea to use the dropdown AND click a tile
			if ($('#recipe_type_select').length &&
				$('#recipe_type_select option:selected').attr('value') != "") {
				tagClasses += catFilter + productFilter + $('#recipe_type_select option:selected').attr('value') + ', '; // this version has -dropdown already on it
				// tagClasses += catFilter + productFilter + $('#recipe_type_select option:selected').attr('value') + '-dropdown, ';
			}

			if (tagClasses == '') {
				tagClasses = catFilter + productFilter;
			}
			else {
				// clip off the trailing ", "
				var tagClasses = tagClasses.substring(0, tagClasses.length - 2);
			}
			//endregion

			// ugh. I have to clean out any "-dropdown" to pass to isotope;
			// that's what I had to put to work with the hash and make it capable of differentiating
			// between the recipe type tiles and the recipe type dropdown selection

			currentFilterWith = tagClasses.replace('-dropdown', '');

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


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

			// update the hash (if enabled)
			if ($('#recipes_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 ($('.recipes_pagination').length) {
				setPagination();
				goToPage(1);
			} else {
				// placeMiddleBlock();
			}


		}

		// 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 ($('#recipes_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);
				}

				selections.forEach(function(onething) {
					if (/^prod-/.test(onething)) {
						$('#recipe_product').val('.' + onething).niceSelect('update');
					} else if (/^prodcat-/.test(onething)) {
						$('#recipe_product_cat').val('.' + onething).niceSelect('update');
					} else if (/^type-/.test(onething)) {
						// this gets the recipe type TILES
						$(".type-tile[data-tagslug='." + onething + "']").removeClass("off");
						// this gets the recipe type DROPDOWN
						if (/-dropdown$/.test(onething))
							$('#recipe_type_select').val('.' + onething).niceSelect('update');
					}
				});
			} 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 = '';
				}


			}
		}

		// when the user wants to link in with a category already selected
		// this needs to be run when the page loads
		if (isFilterable()) {
			updateRecipeFilter();
		}

		//region on change of any filters
		$('#recipes_list .filter-dropdown').on('change', function() {
			updateRecipeFilter();
		});
		$('#recipes_list .type-tile').on('click', function() {
			$(this).toggleClass('off');
			updateRecipeFilter();
		});
		$('#recipes_list #view_all').on('click', function() {
			$('.type-tile').addClass('off');
			$('#recipe_product, #recipe_product_cat').val('');
			updateRecipeFilter();
		});
		//endregion


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

			var itemWord;
			if (resultCount == 1) {
				itemWord = 'recipe';
			}
			else {
				itemWord = 'recipes';
			}

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

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

					var itemsPerPage = $('.recipes_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();
		}


		function placeMiddleBlock() {
			var middleThingContent = $('#apicius_middle_recipes_content').html();
			// this div will always be there, but if there's no content, don't bother with it
			if (middleThingContent.length) {
				// take out any that are already hanging around
				$('.middle-thing-content').remove();

				var middleThingie = $('<div class="middle-thing-content recipe-tile col-xs-12">'+middleThingContent+'</div>');

				var visibleObjects;
				var filterUsed;
				if (currentPaginatedFilterSelector !== '') {
					visibleObjects = $('.recipe-tile' + currentPaginatedFilterSelector).not('#apicius_middle_recipes_content');
					filterUsed = currentPaginatedFilterSelector;
				} else {
					visibleObjects = $('.recipe-tile' + currentFilterWith).not('#apicius_middle_recipes_content');
					filterUsed = currentFilterWith;
				}

				console.log(visibleObjects);

				var numVisible = visibleObjects.length;
				var middle = Math.ceil(parseFloat(numVisible)/2);

				visibleObjects.eq(middle-1).after(middleThingie);

				console.log(filterUsed);

				if (filterUsed === "") {
					$isotoped.isotope({filter: itemSelector});
				} else {
					$isotoped.isotope({filter: '.middle-thing-content, ' + filterUsed});
				}
				$isotoped.isotope('reloadItems');
			}


		}


		$('.recipes_pagination').on('click', '.recipe_pager_prev_arrow.active', function() {
			goToPage(parseFloat(currentPage) - 1);
		});
		$('.recipes_pagination').on('click', '.recipe_pager_next_arrow.active', function() {
			goToPage(parseFloat(currentPage) + 1);
		});

		//endregion
	}

	// on single recipe view, make any Products Used tiles the same height
	if ($('#recipe_single').length) {
		$('#apicius .rec-product').imagesLoaded(function() {
			var tallest_gray = 0;
			$('#apicius .rec-product').each(function() {
				if ($(this).height() > tallest_gray) {
					tallest_gray = $(this).height();
				}
			});
			$('#apicius .rec-product').css('height', tallest_gray + 'px');
			$('#apicius .rec-product .rec-product-name').addClass('final-pos');
		});
	}


	function isFilterable() {
		return ($('#recipe_product_cat').length ||
		$('#recipe_product').length ||
		$('#recipe_types').length ||
		$('#recipe_type_select').length);
	}


});


