var storePage = 0;
var storePageSize = 5; // if using static comment page, this should match that page size
var currentFilter = null;

var fullStar = document.createElement("img");
fullStar.setAttribute("src", "newlayout/images/rstar.png");
fullStar.setAttribute("class", "mainstar");
fullStar.setAttribute("alt", "*");
var halfStar = document.createElement("img");
halfStar.setAttribute("src", "newlayout/images/rstar_half.png");
halfStar.setAttribute("class", "mainstar");
halfStar.setAttribute("alt", "1/2"); // proper way to get &frac12;?
var emptyStar = document.createElement("img");
emptyStar.setAttribute("src", "newlayout/images/rstar_off.png");
emptyStar.setAttribute("class", "mainstar");
emptyStar.setAttribute("alt", ".");


function pageStoreForward(ord) {
	pageStore(storePage+1, ord);
}

function pageStoreBackward(ord) {
	if (storePage > 0) {
		pageStore(storePage-1, ord);
	}
}

function pageStore(newpage, ord) {
		// do we need to do anything visually other than submit the request? (spinner, etc.)
	animateCommentMeter();
	var theFilterValue = filterValue();
	currentFilter = theFilterValue;
	requestStorePage(newpage, theFilterValue);
}

function requestStorePage(pg, ord) {
	requestChange("storepage.php", "page="+pg+"&size="+storePageSize+"&ord="+ord, respondStorePage);
}

function respondStorePage() {
	genericRespond(placeStorePage);
}

function placeStorePage() {
	try {
		var theContainer = document.getElementById("promoItemContainer");
		var revmain = req.responseXML.getElementsByTagName("items")[0];
		var revlist = revmain.getElementsByTagName("promo"); // this is just the (element) children of the <reviews> element gotten above...
		var revfeat = req.responseXML.getElementsByTagName("featured")[0];
		var featlist = revfeat.getElementsByTagName("promo");
		try {
			if (theContainer && featlist.length > 0) {
				// replace featured item
				var theOldFeature = document.getElementById("featured")
				var theFeatureParent = theOldFeature.parentNode;
				theFeatureParent.replaceChild(createFeaturedPromo(featlist[0]), theOldFeature);
				// replace secondary item(s) contingently
				if (featlist.length > 1) {
					var theSecondaryContainer = document.getElementById("secondaryContainer");
					var theSecondaryRow = theSecondaryContainer.rows[0];
						// clear out existing items
					while (theSecondaryRow.cells.length > 0) {
						theSecondaryRow.deleteCell(-1);
					}
					if (featlist.length > 2) {
						// make left and right cells
						var theNewLeftCell = theSecondaryRow.insertCell(-1);
						theNewLeftCell.className = "left";
						theNewLeftCell.appendChild(createSecondaryPromo(featlist[1]));
						var theNewRightCell = theSecondaryRow.insertCell(-1);
						theNewRightCell.className = "right";
						theNewRightCell.appendChild(createSecondaryPromo(featlist[2]));
					} else { // make only cell
						var theNewSecondaryCell = theSecondaryRow.insertCell(-1);
						theNewSecondaryCell.className = "only";
						theNewSecondaryCell.appendChild(createSecondaryPromo(featlist[1]));
					}
				}
			}
		} catch (m) {
			console.log("Caught exception while building new feature area: %o", m);
		}
			
		if (theContainer && revlist.length > 0) {
			var userCanBump = (revmain.hasAttribute("canmod") && revmain.getAttribute("canmod")=="yes");
			var newComments = document.createDocumentFragment();
			var newContainer = document.createElement("div");
			newContainer.id="promoItemContainer";
			newComments.appendChild(newContainer);
			
			for (var i=0; i<revlist.length; i++) {
				newContainer.appendChild(createStorePromo(revlist[i]));
			}
				/// swap old and new comment containers
			var containerParent = theContainer.parentNode;
			containerParent.replaceChild(newContainer, theContainer);
				/// update current page
			var main = req.responseXML.getElementsByTagName("items")[0];
			if (main.hasAttribute("currpage")) {
				storePage = parseInt(main.getAttribute("currpage"));
				if (storePage == 0) {
					disableItemsBackward();
				} else {
					enableItemsBackward();
				}
			}
			if (main.hasAttribute("more")) {
				if (main.getAttribute("more") == '0') {
					disableItemsForward();
				} else {
					enableItemsForward();
				}
			}
			
		} else if (revlist.length == 0) {
			alert("end of list");
			/// should disable forward paging
		}
		stopAnimateCommentMeter();
	} catch (m) {
// 		console.log(m);
	}
}

function createStorePromo(promo) {
	try {
		var promoLinkText = "/deal/"+promo.getAttribute("id")+"/"+linktitle(storePromoTitle(promo));
		var thePromo = document.createElement("table");
		thePromo.className = "promoitem";
		var thePromoRow  = thePromo.insertRow(-1);
			// build icon col
		var theIconCell = document.createElement("td");
		theIconCell.className = "pi_icon";
		var theIconLink = document.createElement("a");
		theIconLink.setAttribute("href", promoLinkText);
		var theIcon = document.createElement("img");
		theIcon.setAttribute("src", storePromoIcon(promo));
		theIcon.setAttribute("class", "iconbig");
		theIcon.setAttribute("alt", "icon");
		theIconLink.appendChild(theIcon);
		theIconCell.appendChild(theIconLink);
			// build title/descr col
		var theTitleCell = document.createElement("td");
		theTitleCell.className = "pi_titleInfo";
		var theTitle = document.createElement("a");
		theTitle.className = "titleTOP";
		theTitle.setAttribute("href", promoLinkText);
		theTitle.appendChild(document.createTextNode(storePromoTitle(promo)));
		var theDescr = document.createElement("div");
		theDescr.className = "descr";
		theDescr.appendChild(document.createTextNode(storePromoDescr(promo)));
		var theRating = document.createElement("div");
		theRating.className = "rating";
		theRating.appendChild(storePromoRating(promo.getAttribute("rating")));
		theTitleCell.appendChild(theTitle);
		theTitleCell.appendChild(theDescr);
		theTitleCell.appendChild(theRating);
			// build purchase info cols
		var thePriceCell = document.createElement("td");
		thePriceCell.className = "pi_price";
		thePriceCell.appendChild(document.createTextNode("$"+ promo.getAttribute("price")));
		var theDiscountCell = document.createElement("td");
		theDiscountCell.className = "pi_discount";
		theDiscountCell.appendChild(document.createTextNode(promo.getAttribute("discount") + "% off"));
		var thePurchCell = document.createElement("td");
		thePurchCell.className = "pi_buy";
		var thePurchLink = document.createElement("a");
		thePurchLink.setAttribute("href", promoLinkText);
		thePurchButton = document.createElement("img");
		thePurchButton.setAttribute("src", "newlayout/images/buynow_dark.png");
		thePurchButton.setAttribute("class", "buynow_dark");
		thePurchButton.setAttribute("alt", "[buy now]");
		thePurchLink.appendChild(thePurchButton);
		thePurchCell.appendChild(thePurchLink);
			// put everything together
		thePromoRow.appendChild(theIconCell);
		thePromoRow.appendChild(theTitleCell);
		thePromoRow.appendChild(thePriceCell);
		thePromoRow.appendChild(theDiscountCell);
		thePromoRow.appendChild(thePurchCell);
		return thePromo;
	} catch (m) {
// 		console.log("err: %o promo: %o", m, promo);
	}
	return null;
}

function createFeaturedPromo(promo) {
	var promoLinkText = "/deal/"+promo.getAttribute("id")+"/"+linktitle(storePromoTitle(promo));
	var thePromo = document.createElement("table");
	thePromo.id = "featured";
	var theContentRow = thePromo.insertRow(-1);
		/// icon
	var theIconCell = theContentRow.insertCell(-1);
	theIconCell.className = "col_icon";
	var theIconLink = document.createElement("a");
	theIconLink.setAttribute("href", promoLinkText);
	var theIcon = document.createElement("img");
	theIcon.setAttribute("src", storePromoIcon(promo));
	theIcon.setAttribute("class", "iconbig");
	theIcon.setAttribute("alt", "icon");
	theIconLink.appendChild(theIcon);
	theIconCell.appendChild(theIconLink);
		/// main data
	var theTitleCell = theContentRow.insertCell(-1);
	theTitleCell.className = "pi_titleInfo";
		// title link
	var theTitle = document.createElement("a");
	theTitle.className = "titleTOP";
	theTitle.setAttribute("href", promoLinkText);
	theTitle.appendChild(document.createTextNode(storePromoTitle(promo)));
		// short descr
	var theShortDescr = document.createElement("div");
	theShortDescr.className = "shortdescr";
	theShortDescr.appendChild(document.createTextNode(storePromoDescr(promo)));
		// rating
	var theRating = document.createElement("div");
	theRating.className = "rating";
	theRating.appendChild(storePromoRating(promo.getAttribute("rating")));
		// main descr (how to handle truncation?)
	var theDescr = document.createElement("div");
	theDescr.className = "fulldescr";
	theDescr.appendChild(document.createTextNode(storePromoFullDescr(promo)));
		// purchase button, discount, etc.
	var theBuyTable = document.createElement("table");
	theBuyTable.className = "buy";
	var theBuyTableRow = theBuyTable.insertRow(-1);
	var theBuyButtonCell = theBuyTableRow.insertCell(-1);
	theBuyButtonCell.appendChild(createFeaturedBuyButton(promoLinkText));
	var theBuyPriceCell = theBuyTableRow.insertCell(-1);
	theBuyPriceCell.className = "price";
	theBuyPriceCell.appendChild(document.createTextNode("$"+ promo.getAttribute("price")));
	var theBuyDiscountCell = theBuyTableRow.insertCell(-1);
	theBuyDiscountCell.className="discount";
	theBuyDiscountCell.appendChild(document.createTextNode(promo.getAttribute("discount") + "% off"));
	
	theTitleCell.appendChild(theTitle);
	theTitleCell.appendChild(theShortDescr);
	theTitleCell.appendChild(theRating);
	theTitleCell.appendChild(theDescr);
	theTitleCell.appendChild(theBuyTable);
		/// screenshot
	var theScreenCell = theContentRow.insertCell(-1);
	theScreenCell.className = "col_screen";
	theScreenCell.appendChild(storePromoScreen(promo));	
	return thePromo;
}

function createSecondaryPromo(promo) {
	var promoLinkText = "/deal/"+promo.getAttribute("id")+"/"+linktitle(storePromoTitle(promo));
	var thePromo = document.createElement("table");
	thePromo.className = "secondary";
	var theContentRow = thePromo.insertRow(-1);
		/// icon
	var theIconCell = theContentRow.insertCell(-1);
	theIconCell.className = "pi_icon";
	var theIconLink = document.createElement("a");
	theIconLink.setAttribute("href", promoLinkText);
	var theIcon = document.createElement("img");
	theIcon.setAttribute("src", storePromoIcon(promo));
	theIcon.setAttribute("class", "iconbig");
	theIcon.setAttribute("alt", "icon");
	theIconLink.appendChild(theIcon);
	theIconCell.appendChild(theIconLink);
		/// remaining content
	var theContentCell = theContentRow.insertCell(-1);
		// title link
	var theTitle = document.createElement("a");
	theTitle.className = "titleTOP";
	theTitle.setAttribute("href", promoLinkText);
	theTitle.appendChild(document.createTextNode(storePromoTitle(promo)));
		// short descr
	var theShortDescr = document.createElement("div");
	theShortDescr.className = "descr";
	theShortDescr.appendChild(document.createTextNode(storePromoDescr(promo)));
		// buy button, pricing
	var theBuyTable = document.createElement("table");
	theBuyTable.className = "buy";
	var theBuyTableRow = theBuyTable.insertRow(-1);
	var theBuyButtonCell = theBuyTableRow.insertCell(-1);
	theBuyButtonCell.appendChild(createSecondaryBuyButton(promoLinkText));
	var theBuyPriceCell = theBuyTableRow.insertCell(-1);
	theBuyPriceCell.className = "price";
	theBuyPriceCell.appendChild(document.createTextNode("$"+ promo.getAttribute("price")));
	var theBuyDiscountCell = theBuyTableRow.insertCell(-1);
	theBuyDiscountCell.className = "discount";
	theBuyDiscountCell.appendChild(document.createTextNode(promo.getAttribute("discount") + "% off"));

	theContentCell.appendChild(theTitle);
	theContentCell.appendChild(theShortDescr);
	theContentCell.appendChild(theBuyTable);
	
	return thePromo;
}


	/// if getElementsByTagName() doesn't work on arbitrary Elements, we can more-painfully
	/// crawl the structure to look for matching nodes
function storePromoIcon(promo) {
	var iconElt = promo.getElementsByTagName("icon")[0];
	if (iconElt && iconElt.hasAttribute("src")) {
		return iconElt.getAttribute("src");
	} else {
		return "http://www.macupdate.com/images/icons/app.png";
	}
}

function storePromoTitle(promo) {
	return nodeChildText(promo, "title");
}

function storePromoDescr(promo) {
	return nodeChildText(promo, "descr");
}

function storePromoFullDescr(promo) {
	return nodeChildText(promo, "fulldescr");
}

function storePromoScreen(promo) {
	var screenElt = promo.getElementsByTagName("screen")[0];
	var theScreen = document.createElement("div");
	theScreen.className = "featuredScreenshot";
	var theImage = document.createElement("img");
	theImage.setAttribute("border", "0");
	if (screenElt && screenElt.hasAttribute("src")) {
		theImage.setAttribute("src", screenElt.getAttribute("src"));
		if (screenElt.hasAttribute("href")) {
			var theLink = document.createElement("a");
			theLink.setAttribute("href", screenElt.getAttribute("href"));
			theLink.appendChild(theImage);
			theScreen.appendChild(theLink);
		} else { // do not link screenshot
			theScreen.appendChild(theImage);
		}
	} else {
		theImage.setAttribute("src", "newlayout/images/screenshot.jpg");
		theScreen.appendChild(theImage);
	}
	return theScreen;
}
	

function nodeChildText(nd, child) {
	var theElt = nd.getElementsByTagName(child)[0]; // nb: explicitly assumes there is only a single matching child node
	if (theElt && theElt.hasChildNodes) {
		theElt.normalize();
		return (theElt.firstChild) ? theElt.firstChild.nodeValue : ""; // get inner text
	} else {
		return "";
	}
}

function storePromoRating(rat) {
	return createRating(parseFloat(rat));
}

	/// based on PHP showrating()
function createRating(rating, mx) {
	if (!mx) {
		mx = 5; // default to 5 stars
	}
	var theRating = document.createDocumentFragment();
	try {
		if (rating) {
			if (rating > mx) {
				for (var i=0; i<mx; i++) {
					theRating.appendChild(fullStar.cloneNode(true));
				}
			} else {
				var entire = Math.floor(rating);
				var nonempty = Math.ceil(rating);
				for (var i=0; i<entire; i++) {
					theRating.appendChild(fullStar.cloneNode(true));
				}
				if (entire < nonempty) {
					var remain = rating - entire;
					if (remain < 0.25) {
						theRating.appendChild(emptyStar.cloneNode(true)); // no star for < 1/4
					} else if (remain < 0.75) {
						theRating.appendChild(halfStar.cloneNode(true));
					} else {
						theRating.appendChild(fullStar.cloneNode(true));
					}
				}
				for (var i=0; i<(mx-nonempty); i++) {
					theRating.appendChild(emptyStar.cloneNode(true));
				}
			}
		} else {
			for (var i=0; i<mx; i++) {
				theRating.appendChild(emptyStar.cloneNode(true));
			}
		}
	} catch (m) {
// 		console.log(m);
	}
	return theRating;
}

function createBuyButtonImg(src, cls) {
	var theBuyButton = document.createElement("img");
	theBuyButton.className = cls;
	theBuyButton.setAttribute("src", src);
	theBuyButton.setAttribute("alt", "[buy now]");
	return theBuyButton;
}

function createFeaturedBuyButton(link) {
	return createBuyButton(link, createBuyButtonImg("newlayout/images/buynow_small.png", "buynow_small"));
}

function createSecondaryBuyButton(link) {
	return createBuyButton(link, createBuyButtonImg("newlayout/images/buynow_dark.png", "buynow_dark"));
}

function createBuyButton(link, img) {
	var theBuyButtonLink = document.createElement("a");
	theBuyButtonLink.setAttribute("href", link);
	theBuyButtonLink.appendChild(img);
	return theBuyButtonLink;
}	


function linktitle(tstring) {
	var despace = /[\s\/]+/g;
	return encodeURIComponent(tstring.replace(despace, "-")).toLowerCase();
}

function filterStoreList() {
	pageStore(0, filterValue());
}

function filterValue() {
	var theFilter = document.getElementById("itemListFilter");
	return (theFilter && theFilter.value) ? theFilter.value : null;
}

function enableItemsControl(ctlid, action) {
	try {
		var theControl = document.getElementById(ctlid);
		if (!theControl.hasAttribute("href")) {
			theControl.setAttribute("href", action);
			theControl.className = "enabled";
		}
	} catch (m) {
		console.log("Problem enabling control (%o): %o", ctlid, m);
	}
}

function enableItemsForward() {
	enableItemsControl("itemsForwardButton", "javascript:pageStoreForward()");
}

function enableItemsBackward() {
	enableItemsControl("itemsBackButton", "javascript:pageStoreBackward()");
}

function disableItemsForward() {
	try {
		disableItemsControl(document.getElementById("itemsForwardButton"));
	} catch (m) {
		console.log("Problem disabling forward control: " + m.toString());
	}
}

function disableItemsBackward() {
	try {
		disablePPControl(document.getElementById("itemsBackButton"));
	} catch (m) {
		console.log("Problem disabling backward control: " + m.toString());
	}
}

function disableItemsControl(ctl) {
	if (ctl && ctl.hasAttribute("href")) {
		ctl.removeAttribute("href");
		ctl.className = "disabled";
	}
}


