﻿var g_viewedPages = {};

// constants
var c_thumbnailCount = 11;
var c_thumbnailHalfCount = 5;

function SetColorType(newColorType)
{
	g_colorType = newColorType;
	AjaxUtils.SetPreference(c_ColorTypePrefKey, newColorType, function() { });

	LoadMainPageImage();
}

function SetPageDisplayHeight(newHeight)
{
	g_height = newHeight;
	AjaxUtils.SetPreference(c_DisplayHeightPrefKey, newHeight, function() { });
	LoadMainPageImage();
}

function LoadImages(newOffset)
{
	if (isNaN(newOffset))
		return;

	Highlighter.RemoveHighlights();
	g_imageOffset = parseInt(newOffset, 10);

	if (g_imageOffset < 0)
		g_imageOffset = 0;
	else if (g_imageOffset >= g_totalPages)
		g_imageOffset = g_totalPages - 1;

	if ($("pageSelection"))
		$("pageSelection").value = g_imageOffset + 1;

	CoalesceLoadingOfMainPageImage();
	LoadThumbnails();
}

function GetStartImage()
{
	var startImage = g_imageOffset - c_thumbnailHalfCount;
	if (startImage < 0)
		startImage = 0;
	else if ((startImage + c_thumbnailCount) > g_totalPages)
		startImage = g_totalPages - c_thumbnailCount;
	return startImage;
}

// --------------------------------------------------------------------------------------------------
// COALESCE Page Arrow Clicks
// If a user rapidly clicks the next page arrow, coalesce all the rapid clicks together and only fire 
// the last one.  The first 2 next page requests are allowed to fire right away so any 
// preloaded/cached images are displayed immediately.
// --------------------------------------------------------------------------------------------------

var g_ResetPageRequestCounterTimerID;
var g_ProcessMainPageImageRequestTimerID;
var g_PageRequestCounter = 0;

function CoalesceLoadingOfMainPageImage()
{
	// Increment the page coutner for every next page click
	g_PageRequestCounter++;

	// Remove the last timer set to clear the page request counter
	clearTimeout(g_ResetPageRequestCounterTimerID);
	// Set a timer to clear the page request counter
	g_ResetPageRequestCounterTimerID = setTimeout(ResetPageRequestCounter, 500);

	// Do not coalesce main page load for first and second rapid page requests.
	// This enables the rendering of the next big page that is preloaded to happen immediately
	if (g_PageRequestCounter <= 2)
	{
		LoadMainPageImage();
	}

	// The user has rapidly clicked 3 or more pages in a row.
	// Coalesce loading these page requests until the user stops clicking for 500 ms
	else
	{
		clearTimeout(g_ProcessMainPageImageRequestTimerID);
		g_ProcessMainPageImageRequestTimerID = setTimeout(LoadMainPageImage, 500);
	}
}

function ResetPageRequestCounter()
{
	// This function will be called 500 ms from the last next page arrow click
	g_PageRequestCounter = 0;
}

function LoadMainPageImage()
{

	// Queue up a request for the corrisponsding page's LDLS web links.
	QueueCoalescedWebLinkRequest();

	var mainImage = $("bookPageImage");
	if (mainImage)
	{
		mainImage.onload = function()
		{
			if (Highlighter.PageHighlighters[g_imageOffset])
				Highlighter.PageHighlighters[g_imageOffset]();
		}
		mainImage.src = GetImageUrl(g_imageOffset);
	}

	// JS: This call to PreloadImages was moved here in order to only fetch the next big image after coalescing page requests has occured.
	PreloadImages();

	BookPageDetail.UpdateUserBookPageAccess(g_bookID, g_colorType, g_height, g_imageOffset, UpdateBookHistory_Callback);

	// set the page as viewed
	g_viewedPages[g_imageOffset] = true;

}

function LoadThumbnails()
{
	var startImage = GetStartImage();
	for (var i = 0; i < c_thumbnailCount; i++)
	{
		var offset = startImage + i;
		var imgThumb = document.getElementById('thumb' + i);

		imgThumb.src = GetThumbUrl(g_bookID, offset);
		imgThumb.parentNode.href = "javascript:void(LoadImages(" + offset + "))";

		if (offset == g_imageOffset)
		{
			imgThumb.style.border = "solid 2px #FFF";
			imgThumb.style.padding = "3px";
		}
		else
		{
			imgThumb.style.padding = "2px";

			if (g_viewedPages[offset])
				imgThumb.style.border = "solid 1px #5F656F";
			else
				imgThumb.style.border = "solid 1px #29313f";
		}
	}
}


function PreloadImages()
{
	var startImage = GetStartImage();
	// preload the next 10 thumbnails
	for (var i = 0; i < 10; ++i)
		document.getElementById('imgPreThumb' + i).src = GetThumbUrl(g_bookID, startImage + c_thumbnailCount + i);

	// preload the next big image (debatable whether it's better to do this or not)
	// kb - added the SuppressLogEntry querystring value here and to ScaledImage.ashx, so that we only log real page accesses and not the image preload for the next pages
	// document.getElementById('imgPreBig').src = 'ScaledImage.ashx?BookID=' + g_bookID + '&Color=' + g_colorType + '&Width=' + g_height + '&ImageOffset=' + (g_imageOffset + 1) + "&SuppressLogEntry=1";
	// kb - later removed SuppressLogEntry querystring, this results in a extra page view being logged for each book, but enables caching to work
	document.getElementById('imgPreBig').src = GetImageUrl(g_imageOffset + 1);
}



function LoadImagesIfEnterKey(e)
{
	// PCs use 13 for enter; Macs use 3 and 13
	if (e.keyCode == 3 || e.keyCode == 13)
	{
		LoadImages(parseInt(Util.UI.GetSrcElement(e).value, 10) - 1);
		return false;
	}
	return true;
}


// --------------------------------------------------------------------------------------------------
// Ajax.NET functions for retrieving Libronix WebLink requests
// --------------------------------------------------------------------------------------------------

// The AjaxRequestQueue is an array that should be treated as a queue, First in, First out
// Only push things into and, and shift things out of it.
var g_AjaxRequestQueue = new Array();
var g_AjaxRequestInProcess = false;
var g_RetrieveWebLinksRequestTimerID;
var g_CurrentPageNextTimeoutID = false;

function QueueCoalescedWebLinkRequest(AjaxRequestFunction, ParameterArray)
{

	// Push the current page globals on the AjaxRequestQueue
	var values = new Array(g_bookID, g_imageOffset, g_height);
	g_AjaxRequestQueue.push(values);

	// If there is no request in process, there is no interval set to submit
	// the current queued up request params.  Set up the interval
	if (g_AjaxRequestInProcess == false)
	{
		g_RetrieveWebLinksRequestTimerID = setInterval("GetImageMapForPage()", 50);
	}
}

function GetImageMapForPage()
{
	if (g_AjaxRequestQueue.length > 0)
	{
		if (g_AjaxRequestInProcess == false)
		{
			g_AjaxRequestInProcess = true;
			var params = g_AjaxRequestQueue.shift();
			g_CurrentPageNextTimeoutID = 0;
			RemoveCurrentAreas();
			BookPageDetail.GetImageMapForPage(params[0], params[1], params[2], GetImageMapForPage_Callback);
		}
		// else, do nothing.  Currently waiting for the last Ajax.net Request to complete
	}
}

function GetImageMapForPage_Callback(ImageMap)
{
	if (g_AjaxRequestQueue.length == 0)
	{
		clearInterval(g_RetrieveWebLinksRequestTimerID);
	}
	g_AjaxRequestInProcess = false;

	if (ImageMap.error != null)
		AjaxErrorHandler(ImageMap.error.Message);
	else
	{
		var map = $('WebLinkMap');
		var areas = ImageMap.value.Areas;
		for (var i = 0; i < areas.length; i++)
		{
			var area = document.createElement("AREA");
			area.shape = areas[i].Shape;
			area.href = areas[i].Href;
			area.coords = areas[i].Coords;
			area.title = areas[i].Title;
			area.alt = areas[i].Alt;
			map.appendChild(area);
		}
	}
}

function RemoveCurrentAreas()
{
	var map = $('WebLinkMap');
	while (map.hasChildNodes())
	{
		map.removeChild(map.lastChild);
	}
}

// END OF -------------------------------------------------------------------------------------------
// Ajax.NET functions for retrieving Libronix WebLink requests
// --------------------------------------------------------------------------------------------------

function UpdateBookHistory_Callback(bookHistory)
{
	if (bookHistory.error)
	{
		AjaxErrorHandler(bookHistory.error.Message);
	}
	else
	{
		// get the history ordered list 
		var ol = $("bookHistoryOL");

		// set up the new link
		var newListElement = document.createElement("LI");
		newListElement.id = bookHistory.value.BookID;
		var newAnchor = document.createElement("A");
		newAnchor.href = "BookPageDetail.aspx?BookID=" + bookHistory.value.BookID;
		newAnchor.appendChild(document.createTextNode(bookHistory.value.Title));
		newListElement.appendChild(newAnchor);

		// history only exists if !IpBasedLogin        
		if (ol && typeof (c_maxHistoryListLength) != "undefined")
		{
			var listChildren = ol.getElementsByTagName("LI");

			// if the list is not empty then insert element at top of list or reorder list                 
			// else add to list as first item                        
			if (listChildren && listChildren.length > 0)
			{
				// compare first list item to see if list is out of synch                                           
				if (listChildren[0].id != bookHistory.value.BookID)
				{
					// if existing item from list selected - move to top 
					// else new item selected - add to top and remove last element   
					var clickedElement = document.getElementById(bookHistory.value.BookID);
					if (clickedElement)
					{
						ol.insertBefore(ol.removeChild(clickedElement), listChildren[0]);
					}
					else
					{
						// only remove the last item if we need to
						if (listChildren.length > c_maxHistoryListLength - 1)
							ol.removeChild(listChildren[listChildren.length - 1]);

						ol.insertBefore(newListElement, listChildren[0]);
					}
				}
			}
			else
			{
				ol.appendChild(newListElement);
			}
		}
	}
}

var bookSearchXmlHttp = null;

function ResizeSearchPanel()
{
	// resize the search panel
	var searchResultsDiv = document.getElementById("SearchResultsDiv");
	if (searchResultsDiv)
		searchResultsDiv.style.height = searchResultsDiv.scrollHeight > 145 ? "145px" : "";
}

var m_searchInProgress = false;

function PostTextSearch()
{
	var query = document.getElementById("textSearchTextInput").value;
	if (!query)
		return false;

	Highlighter.ResetHighlighter();

	var ol = document.getElementById("SearchWithinBookResultsOL");

	// remove old results
	while (ol.firstChild)
		ol.removeChild(ol.firstChild);

	// add loading indication 
	ol.appendChild(Util.UI.CreateElementWithText("LI", "Loading results..."));
	ResizeSearchPanel();

	m_searchInProgress = true;

	setTimeout(function()
	{
		if (m_searchInProgress)
		{
			while (ol.firstChild)
				ol.removeChild(ol.firstChild);

			ol.appendChild(Util.UI.CreateElementWithText("LI", "No matches"));
			m_searchInProgress = false;
		}
	}, 10000);

	var elScript = document.createElement('script');
	elScript.setAttribute('type', 'text/javascript');
	elScript.setAttribute('charset', 'utf-8');
	elScript.setAttribute('src', 'http://books.logos.com/search/' + g_bookID + '?start=0&count=10000&callback=PostTextSearch_Callback&query=' + query);

	document.getElementsByTagName('head').item(0).appendChild(elScript);
	return false;
}

function PostTextSearch_Callback(response)
{
	m_searchInProgress = false;

	var viewData = response ? response.ViewData : null;

	if (!viewData || viewData.error)
		AjaxErrorHandler('');

	var ol = document.getElementById("SearchWithinBookResultsOL");

	// ensure all old results are removed
	while (ol.firstChild)
		ol.removeChild(ol.firstChild);

	// show results or no results found message
	if (viewData.SearchResults.length === 0)
	{
		ol.appendChild(Util.UI.CreateElementWithText("LI", "No matches"))
	}
	else
	{
		for (var i = 0; i < viewData.SearchResults.length; i++)
		{
			var result = viewData.SearchResults[i];
			var hitCount = result.SearchHits.length;
			var a = Util.UI.CreateElementWithText("A", "Page " + (result.PageOffset + 1) + (hitCount > 0 ? (" (" + hitCount + (hitCount == 1 ? " hit)" : " hits)")) : ''));
			a.onclick = CreateLoadImagesFunction(result.PageOffset);
			a.href = "javascript:void(0);";
			var li = document.createElement("LI");
			li.appendChild(a);
			ol.appendChild(li);
			(function()
			{
				var searchHit = result;
				var hitOffset = searchHit.PageOffset;
				Highlighter.PageHighlighters[hitOffset] = function()
				{
					Highlighter.Highlight($('bookPageImage').parentNode, searchHit.SearchHits);
				};
			})();
		}
	}

	ResizeSearchPanel();
}

function CreateLoadImagesFunction(num)
{
	return function() { LoadImages(num); };
}

function AttachTextboxClearing(inputId, initialValue)
{
	var objInput = document.getElementById(inputId);

	if (objInput != null)
	{
		// attach text box clearing
		objInput.onclick = function()
		{
			if (this.value == initialValue)
				this.value = "";
		};
	}
}

function GetThumbUrl(bookID, imageOffset)
{
	return 'ScaledImage.ashx?BookID=' + g_bookID + '&Color=C&Width=480&ImageOffset=' + imageOffset;
}

function GetImageUrl(imageOffset)
{
	var searchText = '';

	if ($("textSearchTextInput"))
		searchText = escape($("textSearchTextInput").value);

	return 'ScaledImage.ashx?BookID=' + g_bookID + '&Color=' + g_colorType + '&Width=' + g_height + '&ImageOffset=' + imageOffset + '&SearchText=' + searchText;
}

// Ajax.net Common Functions

function AjaxErrorHandler(Exception)
{
	if (Exception == "Session Timeout")
	{
		window.location.reload();
	}
}

