/**
 * Actions to run when the DOM is ready with JQuery
 */
$(function() {

	// Set up page content
	$("form[0]").attr({
		"name" : "edContent",
		"id" : "edContent"
	});
	var pageContent = $("#edContent").formParams();
	$.each(pageContent, function(name, value) {
		pageContent[name] = unescape(value);
	});
	
	// Remove the initial undefined entries from viewResults array from 0 to &start=
	if (args['start']) {
		if (args['start'] > 1) {
			viewResults.remove(0, Number(args['start']) - 1);
		} else {
			viewResults.remove(0);
		};
		
	};
	

	// Get Shopping Cart Cookie values and assign to settings object to pass to page template

	var cartSettings = {
		items : thisArrayCookie,
		currentItemNumber : currentBookSequenceInCart,
		currentItemContent : currentBookCookieValue,
		currentBooks : currentBooksInCart
	};

	// Check if this is a book list page and if so get BIC groups and set title
	if(pageContent.PageType == 'library' && pageContent.Label == 'onix') {

		document.title = 'Palgrave - ' + getBICName(args['cat']);
		
		// Get a list of unique two char BIC codes in the result set
		pageContent.bicGroups = uniqueItems($.map(viewResults, function(viewObject) {
			return viewObject.viewCol12.substring(0, 2);
		}));
		// Get list of unique ISBN numbers
		pageContent.isbnList = uniqueItems($.map(viewResults, function(viewObject) {
			return viewObject.viewCol6;
		}));
		// Identify duplicate ISBNs if any
		$.each(viewResults, function(index, bookObject) {
			if(index >= 1 && bookObject.viewCol6 == viewResults[index - 1]['viewCol6']) {
				bookObject.dupe = 1;
			};
		});

		pageContent.filterCat = queryString.replace('start=' + args.start, 'start=1').replace('type=' + args.type, 'type=cat');
		pageContent.filterNew = queryString.replace('start=' + args.start, 'start=1').replace('type=' + args.type, 'type=new');
		pageContent.filterKey = queryString.replace('start=' + args.start, 'start=1').replace('type=' + args.type, 'type=key');

		// Set page nav variables for the loaded index
		pageContent.viewStart = Number(args['start']);
		pageContent.viewCount = Number(args['count']);
		pageContent.viewLast = pageContent.viewStart + pageContent.viewCount;
		pageContent.viewElements = viewResults.length - 1;
		if(pageContent.viewLast > (pageContent.viewStart + pageContent.viewElements)) {
			pageContent.viewLast = pageContent.viewStart + pageContent.viewElements
		};
		pageContent.viewNextStart = pageContent.viewStart + onixDesk.pageItems;
		pageContent.viewPrevStart = pageContent.viewStart - onixDesk.pageItems;
		if(indexElements % onixDesk.pageItems == 0) {
			pageContent.viewNumPages = (indexElements / onixDesk.pageItems);
		} else {
			pageContent.viewNumPages = (indexElements - (indexElements % onixDesk.pageItems)) / onixDesk.pageItems + 1;
		}
		pageContent.viewCurrentPage = (pageContent.viewStart + pageContent.viewCount - 1) / onixDesk.pageItems;
		
	} else
	// Check for Book product page
	if(pageContent.PageType == "onixProduct") {
		pageContent.isbnList = [pageContent.ISBN];
	} else
	// Check for Search results page
	if(pageContent.PageType == 'library' && pageContent.Label == 'searchResults') {

		// Search result items are returned in onixsearch.js
		// Remove the undefined first entry from view list array and set the number of elements or set as empty array if undefined
		
		searchOnixResults.shift();
		pageContent.searchElements = searchOnixResults.length;

		// Get list of unique ISBN numbers
		pageContent.isbnList = uniqueItems($.map(searchOnixResults, function(searchOnixObject) {
			return searchOnixObject.viewCol6;
		}));
		// Identify duplicate ISBNs if any
		var seen = {};
		$.each(searchOnixResults, function(index, bookObject) {
			var seenISBN = bookObject.viewCol6;
			if(seen[seenISBN]) {
				bookObject.dupe = 1;
			} else
				seen[seenISBN] = true
		});
	}
	;

	// Set common content arrays
	pageContent.InThisSectionArray = unescape(pageContent.InThisSection).split(';');

	// Render the page layout - asynchronously load the template definition file.
	$.get('/palgrave/templates/_palgrave_master.tmpl.html', null, function(templates) {

		var content = {
			page : pageContent,
			globals : siteSettings.globals,
			menus : siteSettings.menus,
			params : args,
			bics : siteSettings.bicCodes,
			cart : cartSettings
		};

		if(document.title == 'dombooks') {
			document.title = 'Palgrave - ' + unescape(pageContent.DistinctiveTitle);
		};

		// Inject all templates
		$('body').append(templates);

		// Render the template with article content
		pageTemplate = get_pageTemplate(pageContent.PageType, pageContent.Label, pageContent.Title);
		
		$(pageTemplate).tmpl(content).insertAfter('#edContent');

		$('#bodyContent').replaceWith($('#edDeskBody'));
		$('#edDeskBody').show();

		// Make updates to page content after initial rendering

		// Execute the quicksearch form using the query entered
		$('form#quicksearch').submit(function() {
			var searchQuery = $("#query").val().replace(/"/g, '');

			// Google style search if no operators
			// Add AND between words if there is no AND, OR, NOT, quotes, commas or pipes in the query string

			if(searchQuery.search(/ and | or |\[|\]|\=|\"|\||\,|\&| and not | or not |not /i) == -1) {
				searchQuery = searchQuery.replace(/\s/g, ' AND ');
			} else
				searchQuery = searchQuery.replace(/ not /g, ' ');

			var searchURL = siteSettings.edDesk.path + "libraries/Search+Results?open&query=" + searchQuery + "&start=1&count=200&SearchOrder=4&folder=pubdate&div=Palgrave&label=searchResults";
			window.location = searchURL;
			return false;
		});
		log('Changes made after rendering the template');


		// Replace any missing book covers
		if(pageContent.isbnList) {
			$.each(pageContent.isbnList, function(n, isbn) {
				$('#cover-' + isbn).load(function() {
					// ... loaded
					$(this).fadeIn();
				}).error(function() {
					// ... not loaded
					$(this).attr('src', '/palgrave/images/cover_not_available.gif');
				});
			});
		} else if(pageContent.PageType == "onixPromotions") {
			// Display covers for Monthly Releases
			$('.books-item-left img').error(function() {
				$(this).attr('src', '/palgrave/images/cover_not_available.gif');
			});
			$('.books-item-left img').show();
		}
		;


		// Check for cart information pages
		// Render content for cart pages
		if(pageContent.PageType == 'library' && pageContent.Title == 'Shopping Cart Summary') {
			//$.getScript('/palgrave/lib/site/cart_summary.js');
		};
		if(pageContent.PageType == 'library' && pageContent.Title == 'Checkout') {
			$(renderCartSummary()).appendTo('#cartSummary');
			if(isInspect) {
				$(collectInspectionDetails()).appendTo('#inspectionDetails');
			}
			$(renderCartConfirmation()).appendTo('#cartConfirmation');
			prefillForm('PalgraveDetails');
		};

		// Updates for onixProduct Book pages

		if(pageContent.PageType == 'onixProduct') {
			var priceAvailability = new PriceAvailability(pageContent.ISBN);
			if(priceAvailability && !priceAvailability.available) {
				$('#availability').replaceWith('<div id="availability" class="availability"><p class="notAvailable">' + priceAvailability.getShipDateString() + '</p></div>');
			}

		}

		//TODO: Implement post load updates for P&A service on list views

	});
	// Changes here happen before the page template is rendered
	log('Changes made before the page template is rendered');

});

