
// Contains utility functions used by multiple scripts.

var booksXMLDoc;
var booksXMLFile = "bookcatalog.xml";
var xmlHttp;

// Load an XML file and call onResponse when it's done.
function LoadXMLDoc(URL, onResponse)
{
	if (window.XMLHttpRequest)	{	// code for IE7, Firefox, Mozilla, etc.
		xmlHttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)  	{	// code for IE5, IE6
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlHttp!=null){
		xmlHttp.onreadystatechange=onResponse;
		xmlHttp.open("GET",booksXMLFile,true);
		xmlHttp.send(null);
	}
	else{
	  alert("Your browser does not support XMLHTTP.");
	  throw "Your browser does not support XMLHTTP.";
	}
	return xmlHttp;
}

// Returns a DIV tag containing all of the information we want to display to the user about a given book
function CreateBookDiv(curBook){
	var result = document.createElement('div');
	var bookDiv = document.createElement('div');
	bookDiv.className = 'bookDiv';

	if (valueOfTag(curBook, 'picture') !== ''){
		var pictureContainer = document.createElement('div');
		pictureContainer.className = 'photoleft';
		var picture = document.createElement('img');
		picture.setAttribute('src', valueOfTag(curBook, 'picture'));
		picture.setAttribute('alt', valueOfTag(curBook, 'title'));
	
		pictureContainer.appendChild(picture);
		bookDiv.appendChild(pictureContainer);
	}
	
				
	var title = document.createElement('h3');
	title.innerHTML = "<strong>" + valueOfTag(curBook, 'title');
	if (valueOfTag(curBook, 'subtitle') !== "") 
	{ title.innerHTML += ":<br />" + valueOfTag(curBook, 'subtitle'); }
	title.innerHTML += "</strong>";
	bookDiv.appendChild(title);
	
	var authorData = document.createElement('p');
	if (valueOfTag(curBook, 'editor') !== ''){
		authorData.innerHTML += "Edited ";
		authorData.innerHTML += "by " + valueOfTag(curBook, 'editor');
	}
	else if (valueOfTag(curBook, 'author') !== '')
		authorData.innerHTML += "by " + valueOfTag(curBook, 'author'); 
	if (valueOfTag(curBook, 'translator') !== '')
		authorData.innerHTML += ", translated by " + valueOfTag(curBook, 'translator');
	bookDiv.appendChild(authorData);
	
	var varData = document.createElement('p');
	if (valueOfTag(curBook, 'published') !== '')
		varData.innerHTML += valueOfTag(curBook, 'published') + ", ";
	if (valueOfTag(curBook, 'pages') !== '')
		varData.innerHTML += valueOfTag(curBook, 'pages') + " pages, ";
	if (valueOfTag(curBook, 'type') !== '')
		varData.innerHTML += valueOfTag(curBook, 'type') + ", ";
	if (valueOfTag(curBook, 'volume') !== '')
		varData.innerHTML += "Volume " + valueOfTag(curBook, 'volume') + ", ";
	varData.innerHTML = varData.innerHTML.substring(0, varData.innerHTML.length - 2);
	bookDiv.appendChild(varData);
	
	var pricing = document.createElement('p');
	if (!isNaN(parseFloat(valueOfTag(curBook, 'price'))))
		pricing.innerHTML += "$";
	pricing.innerHTML += valueOfTag(curBook, 'price');
	bookDiv.appendChild(pricing);

	bookDiv.appendChild(makePaypalAddToCart(curBook));
	
	if (valueOfTag(curBook, 'description.shortdescription') !== ""){
		var descriptionHeading = document.createElement('h4');
		descriptionHeading.innerHTML = "Description";
		bookDiv.appendChild(descriptionHeading);
		
		var description = document.createElement('p');
		description.innerHTML = valueOfTag(curBook, 'description.shortdescription');
		bookDiv.appendChild(description);
	}
	
	if (valueOfTag(curBook, 'description.review') !== ""){
		var reviewsHeading = document.createElement('h4');
		reviewsHeading.innerHTML = "Reviews:";
		bookDiv.appendChild(reviewsHeading);
		
		var reviews = document.createElement('p');
		reviews.innerHTML = valueOfTag(curBook, 'description.review');
		bookDiv.appendChild(reviews);
	}
	
	// Add a link back to the top of the page.
	var backToTop = document.createElement('div');
	backToTop.innerHTML += "<a href='#top'>Back to top</a>";
	bookDiv.appendChild(backToTop);
	
	// Add an invisible element at the end, whose only purpose is to expand the div to include any floating pictures.
	var expander = document.createElement('div');
	expander.style.cssText = 'clear:both;';
	bookDiv.appendChild(expander);
	
	// Attach the book div to the result list.
	result.appendChild(bookDiv);
	return result;  
}

function makePaypalAddToCart(curBook){
	var paypalDiv = document.createElement('div');
	
	var fullTitle = valueOfTag(curBook, 'title') + ": " + valueOfTag(curBook, 'subtitle');
	var isbn = valueOfTag(curBook, 'isbn');
	var price = parseFloat(valueOfTag(curBook, 'price'));
	
	if (fullTitle !== "" && isbn !== "" && !isNaN(price) && price > 0.0 && price < 1000.0){
		paypalDiv.innerHTML = "<form target='paypal' action='https://www.paypal.com/cgi-bin/webscr' method='post'> \
			<input type='image' src='https://www.paypal.com/en_US/i/btn/x-click-but22.gif' name='submit' \
			alt='PayPal - The safer, easier way to pay online!'> \
			<img alt='' border='0' src='https://www.paypal.com/en_US/i/scr/pixel.gif' width='1' height='1'> \
			<input type='hidden' name='add' value='1'> \
			<input type='hidden' name='cmd' value='_cart'> \
			<input type='hidden' name='business' value='scott.pearce@wwu.edu'> \
			<input type='hidden' name='item_name' value='" + fullTitle + "'> \
			<input type='hidden' name='item_number' value='" + isbn + "'> \
			<input type='hidden' name='amount' value='" + price + "'> \
			<input type='hidden' name='no_shipping' value='0'> \
			<input type='hidden' name='no_note' value='1'> \
			<input type='hidden' name='currency_code' value='USD'> \
			<input type='hidden' name='lc' value='US'> \
			<input type='hidden' name='bn' value='PP-ShopCartBF'> \
			</form>";
	}
	return paypalDiv;
}

function makePaypalCheckoutBtn(){
	var paypalCheckoutDiv = document.createElement('div');
	
	paypalCheckoutDiv.innerHTML = "<form target='paypal' action='https://www.paypal.com/cgi-bin/webscr' method='post'> \
		<input type='hidden' name='cmd' value='_cart'> \
		<input type='hidden' name='business' value='scott.pearce@wwu.edu'> \
		<input type='image' src='https://www.paypal.com/en_US/i/btn/view_cart.gif' name='submit' \
			alt='PayPal - The safer, easier way to pay online!'> \
		<input type='hidden' name='display' value='1'> \
		</form>";
		
	return paypalCheckoutDiv;
}

// Takes a list of books and a title and returns the book with the given title.  No surprise there
function GetBookByTitle(books, title){	
	for (curBook = 0; curBook < books.length; curBook++){
		if (valueOfTag(books[curBook], 'title') == title){
			return books[curBook];
		}
	}
	return null;
}

// Returns the value of the xml tag xmlTag in curBook.  If xmlTag is of the form "Something.SomethingElse" this will return
// the value of the tag "SomethingElse" nested inside of the tag "Something"
function valueOfTag(curBook, xmlTag){
	var levelArray = new Array();
	levelArray = xmlTag.split('.');
	
	var curLevel = curBook;
	while (levelArray.length !== 0){
		curLevel = getFirstMatchingElementByName(curLevel, levelArray.shift());
		if (curLevel !== null){
			if (levelArray.length == 0){ 	
				if (curLevel.firstChild == null)
					return "";
				if (curLevel.firstChild.nodeValue == null)
					return "";
				curLevel = curLevel.firstChild.nodeValue; 
			}
		}
		else
			return "";
	}
	
	return makeHTMLFriendly(trimString(curLevel));
}

function getFirstMatchingElementByName(curNode, xmlTagName){
	for (var curIndex = 0; curIndex < curNode.childNodes.length; curIndex++){
		if (curNode.childNodes[curIndex].tagName == xmlTagName){
			return curNode.childNodes[curIndex];
		}
	}
	return null;
}

// Adds a new option to a given list box.
function addOption(selectbox, text, value ){
  var optn = document.createElement("OPTION");
  optn.text = text;
  optn.value = value;
  selectbox.options.add(optn);
}

// Removes leading and trailing white-space from a string.
function trimString (str) {
	return str.replace(/^\s+|\s+$/g,"");
}

// Replace Window's line breaks with HTML line breaks.
function makeHTMLFriendly(str) {
	return str.replace(/\n/g, "<br />");
}

// BOOK TYPE
function BookType(){
	this.m_Title;
	this.m_Published;
	this.m_Category;
}

// Just a basic sort routine applied to books.  Sorts based on a given criterion, in a given direction
// (criterion must either be "title", "published", or "category" and direction must either be "asc" or "desc").
function SortBookData(bookSortData, criterion, direction){
	for (i = 0; i < bookSortData.length; i++){
		for (j = i +1; j < bookSortData.length; j++){
			// If the book in the top spot was published earlier than the guy we're comparing,
			// Swap them.
			var curCriterion
			var nextCriterion
			if ("published" == criterion.toLowerCase()){
				curCriterion = bookSortData[i].m_Published
				nextCriterion = bookSortData[j].m_Published
			}
			else if ("title" == criterion.toLowerCase()){
				curCriterion = bookSortData[i].m_Title
				nextCriterion = bookSortData[j].m_Title
			}
			else if ("category" == criterion.toLowerCase()){
				curCriterion = bookSortData[i].m_Category
				nextCriterion = bookSortData[j].m_Category
			}
			if (("desc" == direction && curCriterion < nextCriterion) || ("asc" == direction && curCriterion > nextCriterion)){
				var temp = bookSortData[i];
				bookSortData[i] = bookSortData[j];
				bookSortData[j] = temp;
			}
		}
	}
}