﻿$(function () {
	var body = $('body'),
	
		collections = $('#collections'),

		addCommas = function(value) {
			var parts = value.toFixed(2).split('.'),
				n = parts[0],
				regex = /(\d+)(\d{3})/;

			while (regex.test(n)) {
				n = n.replace(regex, '$1,$2');
			}

			return n + '.' + parts[1];
		},

		initializeMolinaCollectionFiltering = function() {
			var products = $('li.product'),
				categories = $('ul.categories input'),
				departments = $('ul.departments input'),
				viewSize = $('#viewsize-no-navigate'),
				productsPerPage = viewSize.val(),
				pagination = $('.pager .pagination'),
				pages = $('.pages', pagination),
				previous = $('.previous', pagination),
				next = $('.next', pagination),
				currentPage = 1,
				slider = $('#price-slider'),
				minPriceContainer = $('.minPrice'),
				maxPriceContainer = $('.maxPrice'),
				prices = products.map(function(n, product) {
					return Number($(product).data('price'));
				}).get(),
				originalMinPrice = -1,
				originalMaxPrice = -1,
				minPrice = -1,
				maxPrice = -1,

				showViewSizeAndPagination = function () {
					viewSize.val('');
					limitViewSize();

					viewSize.show();
				},

				hideViewSizeAndPagination = function () {
					viewSize.add(pagination).hide();
				},

				page = function () {
					var productsToShow = products;

					if (currentPage > 1) {
						productsToShow = productsToShow.filter(':gt(' + (((currentPage - 1) * productsPerPage) - 1) + ')');
					}

					productsToShow = productsToShow.filter(':lt(' + productsPerPage + ')');

					products.hide();
					productsToShow.show();
				},

				renderPageNumbers = function() {
					var numberOfPages = Math.ceil(products.length / productsPerPage),
						pagesHtml = '',
						n;

					if (numberOfPages < 2) {
						pages.html('');
						pagination.hide();
					}
					else {
						previous.toggle(currentPage > 1);
						next.toggle(currentPage < numberOfPages);

						for (n = 1; n <= numberOfPages; n++) {
							if (n == currentPage) {
								pagesHtml += '<strong class="currentPage">' + n + '</strong>';
							}
							else {
								pagesHtml += '<a class="PageNumber" href="#" data-page-number="' + n + '">' + n + '</a>';
							}
						}

						pages.html(pagesHtml);

						$('a', pages).click(function (e) {
							e.preventDefault();

							currentPage = $(this).data('page-number');

							page();
							renderPageNumbers();
						});

						pagination.show();
					}
				},

				limitViewSize = function() {
					var numberOfPages;

					productsPerPage = viewSize.val();
					numberOfPages = Math.ceil(products.length / productsPerPage);
					currentPage = Math.min(numberOfPages, currentPage);

					if (!productsPerPage) {
						pagination.hide();
						products.show();
					}
					else {
						page();
						renderPageNumbers();
					}
				},

				setPriceTexts = function() {
					minPriceContainer.text('$' + addCommas(minPrice));
					maxPriceContainer.text('$' + addCommas(maxPrice));
				},

				filter = function() {
					var selectedCategories = categories.filter(':checked').map(function () {
							return Number(this.value);
						}).get(),

						selectedDepartments = departments.filter(':checked').map(function () {
							return Number(this.value);
						}).get();

					if (selectedCategories.length == 0 && selectedDepartments.length == 0 && minPrice == originalMinPrice && maxPrice == originalMaxPrice) {
						products.show();
						showViewSizeAndPagination();
					}
					else {
						hideViewSizeAndPagination();

						// Fade out all products.
						products.hide();
							// Filter products down to those that match the filter
							// criteria.
							products.filter(function() {
								var product = $(this),
									productCategories = product.data('categories'),
									productDepartments = product.data('departments'),
									productPrice = Number(product.data('price')),
									isCategoryMatch = false,
									isDepartmentMatch = false,
									isPriceMatch = productPrice >= minPrice && productPrice <= maxPrice;

								// Loop over each category that the product belongs to
								// and check if it is one of the selected categories.
								if (selectedCategories.length == 0) {
									isCategoryMatch = true;
								}
								else {
									$.each(productCategories, function (n, category) {
										isCategoryMatch = isCategoryMatch || ($.inArray(category, selectedCategories) > -1);
									});
								}

								// Loop over each department that the product belongs
								// to and check if it is one of the selected
								// departments.
								if (selectedDepartments.length == 0) {
									isDepartmentMatch = true;
								}
								else {
									$.each(productDepartments, function(n, department) {
										isDepartmentMatch = isDepartmentMatch || ($.inArray(department, selectedDepartments) > -1);
									});
								}

								// A product matches if it is in a selected category
								// and if it is in a selected department.
								return isCategoryMatch && isDepartmentMatch && isPriceMatch;
							})
							// Fade in the filtered products.
							.show();
					}
				};

			if (products.length < 4) {
				viewSize.hide();
				pagination.hide();
			}

			if (!viewSize.val()) {
				pagination.hide();
			}

			viewSize.unbind().change(limitViewSize);

			previous.click(function (e) {
				e.preventDefault();

				currentPage--;

				page();
				renderPageNumbers();
			});

			next.click(function (e) {
				e.preventDefault();

				currentPage++;

				page();
				renderPageNumbers();
			});

			for (var n = 0; n < prices.length; n++) {
				if (minPrice == -1 || prices[n] < minPrice) {
					minPrice = prices[n];
				}

				if (maxPrice == -1 || prices[n] > maxPrice) {
					maxPrice = prices[n];
				}
			}

			originalMinPrice = minPrice;
			originalMaxPrice = maxPrice;

			slider.slider({
				range: true,
				min: minPrice,
				max: maxPrice,
				values: [minPrice, maxPrice],
				slide: function(e, ui) {
					minPrice = ui.values[0];
					maxPrice = ui.values[1];

					setPriceTexts();
				},
				stop: function(e, ui) {
					filter();
				}
			});

			setPriceTexts();

			categories.add(departments).change(filter);

			$('a.clear-all').click(function(e) {
				e.preventDefault();

				categories.add(departments).removeAttr('checked');

				minPrice = originalMinPrice;
				maxPrice = originalMaxPrice;

				slider.slider('values', 0, minPrice).slider('values', 1, maxPrice);
				setPriceTexts();

				categories.first().change();

				showViewSizeAndPagination();
			});

			$('.collapse').click(function(e) {
				var a = $(this),
					div = $(this).closest('p').next('div').slideToggle(function () {
						if (div.is(':visible')) {
							a.html('&#9650;');
						}
						else {
							a.html('&#9660;');
						}
					});
			});
		};

	$('#newsletter-signup').colorbox({
		height: '260px',
		iframe: true,
		onOpen: function() {
			$('#cboxClose').addClass('newsletter-signup');
		},
		onClosed: function() {
			$('#cboxClose').removeClass('newsletter-signup');
		}
	});

	$('.pager a img[alt="Move Next"]').parent().html('&#9654;').addClass('arrow');
	$('.pager a img[alt="Move Previous"]').parent().html('&#9664;').addClass('arrow');
/*
	// hover functionality for /c-2-shop-online.

	if (collections.length) {
		$('li a', collections).hover(
			function() {
				var href = $(this).attr('href');

				if (href != '#') {
					collections.attr('class', '').addClass(href.substring(href.lastIndexOf('/') + 1));
				}
			},
			function() {
				collections.attr('class', '');
			}
		);
	}
*/
	if (body.hasClass('c-36-the-molina-collection')) {
		initializeMolinaCollectionFiltering();
}

});
