// string holder of search values
var searchVal = '';

// Value for ensuring last checked box applies after a search
var lastChecked = "a";

// Search options
var options;

// Search tool
var fuse;

$(document).ready(function () {

	// URL value for the first page
	var startInt = 0;

	for (startInt = 0; startInt < 400; startInt += 100) {

		// Folder that containes the pager objects
		url = window.location.href;
		url = url.substring(0, url.indexOf("policies-and-procedures") + 24) + "/pageholder" + "?b_start:int=" + startInt;

		// Sets onclick for checkboxes since plone strips it by default for some reason
		$("#checkboxes input").attr("onclick", 'checkOnlyOne(this.value)');

		// Request for pagerholder folder content
		$.get(url).done(function (data) {
			// Fix based on weather youre logged in or not then pull the page object list
			if (data.indexOf('<div id="content-core">') > -1) {
				content = data.substring(data.indexOf('<div id="content-core">'), data.length);
			} else {
				content = data.substring(data.indexOf('<div id="content-body"'), data.length);
			}

			content = content.substring(content, content.indexOf("</div>") + 6);
			// While there's still an image in the content that hasn't been added to the arrays
			while (content.indexOf('href="') != -1) {
				// Crops content
				content = content.substring(content.indexOf('href="') + 6, content.length);
				// console.log('content in while: ', content);

				// Gets image URL and adds it to the valueList array
				pageURL = content.substring(content, content.indexOf('"'));
				// console.log('the pageURL is:', pageURL);
				// gets page name, and keywords and insets them into an array
				if ((pageURL.indexOf("author") == -1 || pageURL.indexOf("authority") !== -1 || pageURL.indexOf("authorization") !== -1) && (pageURL.indexOf("b_star") == -1)) {
					content = content.substring(content.indexOf('"'), content.length);
					// console.log('content in if: ' + content);
					name = content.substring(content.indexOf(">") + 1, content.indexOf("</a>")).trim();
					// console.log('the name is:', name);
					keyWordString = content.substring(content.indexOf('<span class="description">') + 26, content.length);
					keyWordString = keyWordString.substring(0, keyWordString.indexOf('</span>'));
					// remove empties from array
					keywords = keyWordString.split(" ");
					// remove empties from array
					keywords = keywords.filter(Boolean);
					// console.log('the keywords are:', keywords);
					searchVal += '{"name": "' + name + '",';
					searchVal += '"url": "' + pageURL + '",';
					searchVal += '"tags": [' + '"' + keywords.join('","') + '"' + ']}, {';
				}
			}
			// Final of the string
			searchVal = searchVal.substring(0, searchVal.length - 3);
			searchVal = searchVal.replace('"]}{"', '"]}, {{"');
			// searchVal = '[' + searchVal + ']';
			// console.log('searchVal before timeout: ', searchVal);

			// set timeout to give time for data scraping
			setTimeout(function () {
				searchVal = searchVal.split(', {');
				// console.log('searchVal after split: ', searchVal);

				// create array of objects from array of strings
				var ppObjectsArray = [];
				for (i = 0; i < searchVal.length; i++) {
					var ppObject = JSON.parse(searchVal[i]);
					ppObjectsArray.push(ppObject);
				}

				// console.log('ppObjectsArray after JSON.parse', ppObjectsArray)

				// Search options use this page for testing/modifying.
				// http://fusejs.io/
				options = {
					shouldSort: true,
					threshold: 0.2,
					location: 0,
					distance: 1000,
					maxPatternLength: 32,
					minMatchCharLength: 3,
					keys: [
						"name",
						"tags"
					]
				};

				// Initalizes search
				fuse = new Fuse(ppObjectsArray, options);

				// Sorts search value by policy/procedure name
				ppObjectsArray = ppObjectsArray.sort(function (a, b) {
					return ('' + a.name.substring(4, a.name.length)).localeCompare(b.name.substring(4, b.name.length));
				});

				// Generates a list of policy/procedures with onclick that loads the full doc
				htmlString = "";

				for (i = 0; i < ppObjectsArray.length; i++) {
					htmlString += '<div class="row-fluid"><div class="span12 ' + ppObjectsArray[i].name.substring(0, 3) + '" data-link="' + ppObjectsArray[i].url + '" onclick="setViewable(this);"><p>' + ppObjectsArray[i].name.substring(4, ppObjectsArray[i].name.length) + '</p></div></div>';
				}

				// hide loading text
				$('.css-wait-display').css('display', 'none');

				// add data to the page
				$('#policyListHolder').css('overflow-y', 'scroll').append(htmlString);

				footerFix();
			}, 3000);
		});
	}
});

// Function to load policy object from url
function setViewable(pageObject) {
	$('#policyHolder').load(pageObject.getAttribute("data-link") + ' #PolicyWrapper', function () {
		$("#policyHolder").prepend('<div id=printButtonWrapper class="span12"><a id=print class="btn">Print</a></div>');
		$("#print").attr("onclick", "$('#PolicyWrapper').printThis({importStyle: true});");

		footerFix();

		if ($(window).width() < 1200) {
			$('html,body').animate({
				scrollTop: $("#policyHolder").offset().top
			});
		}
	});
}

// Function that ensures one of the checkboxes is selected, and also that only one is selected
function checkOnlyOne(b) {
	// Failsafe value. Uses last check box, only is used on search
	if (b == "lolPls") {
		b = lastChecked
	}

	// Hides no results message
	$(".resultsMessage").hide();

	// Gets all of the checkboxes
	var x = document.getElementsByClassName('selector');

	// Makes sure only one checkbox is selected, and that one is always selected.
	for (i = 0; i < x.length; i++) {
		if (x[i].value != b) {
			x[i].checked = false;
		} else {
			x[i].checked = true;
		}
	}

	// Show/hide based off what is selected.
	if (b == "a") {
		$(".Pol").show();
		$(".Pro").show();
	} else if (b == "p") {
		$(".Pol").show();
		$(".Pro").hide();
	} else {
		$(".Pol").hide();
		$(".Pro").show();
	}

	// Value of last checked object
	lastChecked = b;

	// If no policies are shown, show no results message. This happens with a combo
	// of search and selected.
	if ($('#policyListHolder .span12:visible').length == 0) {
		if ($(".resultsMessage").html() != "Sorry there were no results for your query.") {
			$('#policyListHolder').append("<h4 class=resultsMessage>Sorry there were no results for your query.</h4>");
		} else {
			$(".resultsMessage").show();
		}
	}
}

// Handles searching/updating policy list.
function policySearch(searchString) {
	htmlString = "";

	// Removes no results message
	$(".resultsMessage").remove();

	// If there is a string in the search box generate searched list..
	// else generate a full list.
	if (searchString) {
		searchList = fuse.search(searchString);

		searchList = searchList.sort(function (a, b) {
			return ('' + a.name.substring(4, a.name.length)).localeCompare(b.name.substring(4, b.name.length));
		});

		for (i = 0; i < searchList.length; i++) {
			htmlString += '<div class="row-fluid"><div class="span12 ' + searchList[i].name.substring(0, 3) + '" data-link="' + searchList[i].url + '" onclick="setViewable(this);"><p>' + searchList[i].name.substring(4, searchList[i].name.length) + '</p></div></div>';
		}

		if (htmlString) {
			$('#policyListHolder').html(htmlString);
		} else {
			$('#policyListHolder').html("");
		}
	} else {
		for (i = 0; i < searchVal.length; i++) {
			htmlString += '<div class="row-fluid"><div class="span12 ' + searchVal[i].name.substring(0, 3) + '" data-link="' + searchVal[i].url + '" onclick="setViewable(this);"><p>' + searchVal[i].name.substring(4, searchVal[i].name.length) + '</p></div></div>';
		}
		$('#policyListHolder').html(htmlString);
	}

	// Failsafe value to rerun check only one without changing the current box
	checkOnlyOne("lolPls");
}
