﻿var Search = {};


Search.Results = (function ($) {
	var config = {
		CurrentPage: 0,
		ItemsPerPage: 0,
		TotalResults: 0,
		PagingSelector: "",
		PagignURLTemplate: "",
		PagingChunkSize: 15,
		TotalPages: 0
	};

	var facetsMenu;

	var init = function (settings) {
		$.extend(config, true, settings);
		SetOptions(config.PagingSelector + " .Options");
		SetupPageLinks(config.PagingSelector + " .PageLinks", config.CurrentPage);
		SetLinks();


		// collapse button
		$(".MenuSectionHeader").click(function () {
			$(this).next().toggle();
		});

		$(".FacetCutoffMoreLink").click(function () {
			$(this).parent().parent().find(".CutoffFacetHide").each(function () {
				if ($(this).is(":visible")) {
					$(this).hide();
				}
				else {
					$(this).show();
				}
			});

			// switch the text
			var altText = $(this).attr("rel");
			$(this).attr("rel", $(this).text());
			$(this).text(altText);

			return false;
		});
	};

	var SetupPageLinks = function (parentElementSelector, currentPage) {
		var pageLinksHTML = "";

		// work out which "chunk" the paging appears in
		var startPage = 1;
		if (currentPage > config.PagingChunkSize) {
			var diff = currentPage % config.PagingChunkSize;
			if (diff != 0) {
				startPage = (currentPage + 1) - diff;
			}
			else {
				startPage = (currentPage - (config.PagingChunkSize - 1));
			}
		}

		var end = startPage + config.PagingChunkSize;
		if (end > config.TotalResults) {
			end = config.TotalResults + 1;
		}
		if (end > config.TotalPages) {
			end = config.TotalPages + 1;
		}

		if (startPage > 1) {
			pageLinksHTML += "<a href=\"#\" class=\"LessLinks\">...</a>";
		}

		for (var i = startPage; i < end; i++) {
			var url = config.PagignURLTemplate.replace("{Page}", i).replace("{ItemsPerPage}", config.ItemsPerPage);
			var isSelected = "";

			if (i == config.CurrentPage) {
				isSelected = " class=\"selected\"";
			}

			pageLinksHTML += "<a href=\"" + url + "\"" + isSelected + ">" + i + "</a>";
		}

		if (end <= config.TotalPages) {
			pageLinksHTML += "<a href=\"#\" class=\"MoreLinks\">...</a>";
		}

		$(parentElementSelector).html(pageLinksHTML);

		// Bind event handlers
		$(parentElementSelector + " a.LessLinks").click(function () {
			SetupPageLinks(parentElementSelector, startPage - config.PagingChunkSize);
			return false;
		});

		$(parentElementSelector + " a.MoreLinks").click(function () {
			SetupPageLinks(parentElementSelector, end);
			return false;
		});
	}

	var SetLinks = function (parentElementSelector) {
	}

	var SetOptions = function (parentElementSelector) {
		$(parentElementSelector + " .OptionsButton").click(function () {
			$(parentElementSelector + " .OptionsPanel").toggle();
			return false;
		});
	}

	return { Init: init };
} (jQuery));
