// JavaScript Document
/// <reference path="global.js">
/// <reference path="classes/jquery-vsdoc.js">

// Load required classes
AppGlobal.loadClass("Ajax");

var BlainCat;
if (!BlainCat) BlainCat = {};

// Declare properties
BlainCat.timer = null;
BlainCat.cartPopup = null;
BlainCat.storeAjaxURL = "/ajax/stores.aspx";
BlainCat.ajaxURL = "/ajax/catalog.aspx";
BlainCat.productDetailURL = "/catalog/product.aspx";

// Clears the field on focus if it is filled with the default "Search by Keyword" value
BlainCat.clearEmptyFindForm = function(textfield) {
	if (textfield.value == "Find a Product") textfield.value = '';
}

// Changes the sort order of the find product page
BlainCat.changeFindProductSortResultsPerPage = function(field) {
	location.href = field.value;
}

// Changes the ecom only flag of the find product page
BlainCat.changeFindProductEcomStatus = function(field) {
	// Remove the ecom flag from the url
	var qs = (location.search.charAt(0) == '?') ? location.search.substring(1) : location.search,
		tmp = new Array(),
		pair = qs.split("&"),
		newqs = "";
	for (var i = 0; i < pair.length; i++) {
		if (pair[i].indexOf("eco=") == -1) tmp.push(pair[i]);
	}
	if (field.checked) tmp.push("eco=1");
	if (tmp.length > 0) newqs = "?" + tmp.join("&");
	location.href = location.pathname + newqs;
}

// Switches to another child product
BlainCat.changeChild = function () {
	var c = $id("c");
	if(c) {
		// Hide existing child information
		var pnPrice = $id("pnPrice"),
			pnAvailability = $id("pnAvailability"),
			frmProduct = $id("frmProduct"),
			imgProgress = $id("imgChildProgress");
		if(pnPrice && imgProgress) {
			pnPrice.style.visibility = 'hidden';
			if(pnAvailability) pnAvailability.style.visibility = 'hidden';
			if(frmProduct) frmProduct.style.visibility = 'hidden';
			imgProgress.style.visibility = 'visible';
		}
		// Parse URL string and separate the query string into individual parts;
		var base = location.pathname,
			qs = location.search.substring(1, location.search.length).replace(/\+/g, ' ');
		// Formulate new URL string
		var args = qs.split('&'),
			url = location.pathname + '?i=' + c.value;
		for(var i = 0; i < args.length; i++) {
			// Split name/value pair to get the variable name
			var pair = args[i].split('=');
			var name = unescape(pair[0]);
			if(name != 'i') url = url + '&' + args[i];
		}
		alert(url);
		location.href = url;
	}
}

// Switches to another child product (new way)
BlainCat.getOtherChild = function() {
	var c = $id("c");
	if (c) {
		var url = location.pathname.replace(/^(\/products\/)([A-Za-z0-9]+)(-[a-z0-9-_]+)?(.html)?/, "$1" + c.value + "$3$4") + location.search.replace(/(i=)([A-Za-z0-9]+)/, "$1" + c.value);
		// Hide existing child information
		var pnPrice = $id("pnPrice"),
			pnAvailability = $id("pnAvailability"),
			frmProduct = $id("frmProduct"),
			imgProgress = $id("imgChildProgress");
		if (pnPrice && imgProgress) {
			pnPrice.style.visibility = 'hidden';
			if (pnAvailability) pnAvailability.style.visibility = 'hidden';
			if (frmProduct) frmProduct.style.visibility = 'hidden';
			imgProgress.style.visibility = 'visible';
		}
		//window.onunload = BlainCat.resetDisplay;
		location.href = url;
	}
}

// Switches the child product display back to the default condition
BlainCat.resetDisplay = function() {
	var pnPrice = $id("pnPrice"),
		pnAvailability = $id("pnAvailability"),
		imgProgress = $id("imgChildProgress"),
		frmProduct = $id("frmProduct");
	if (pnPrice && imgProgress) {
		pnPrice.style.visibility = 'visible';
		if (pnAvailability) pnAvailability.style.visibility = 'visible';
		if (frmProduct) frmProduct.style.visibility = 'visible';
		imgProgress.style.visibility = 'hidden';
	}
}

// Reset the child selection on the current item to the current child
BlainCat.resetChildSelection = function() {
	var c = document.frmItemSelect.c;
	if (c) {
		var blain = location.pathname.replace(/^(\/products\/)([0-9]{6,7})(-[a-z0-9-_]+)?(.html)?/, "$2");
		for (var x = 0; x < c.options.length; x++) {
			if (c.options[x].value == blain) {
				c.selectedIndex = x;
				break;
			}
		}
		BlainCat.resetDisplay();
	}
}

// Opens a window with a full-size image view
BlainCat.viewFullImage = function(id) {
	var popup = $id("image-popupobj"),
		img = $id(id),
		div = $id("FullImage");
	if (popup && img && div) {
		AppGlobal.overlay = new Overlay("image-popupobj");
		var lgimg = $elem("img");
		lgimg.width = 450;
		lgimg.height = 450;
		lgimg.src = img.src.replace(/\/(smthumb|thumb|detail|lgdetail)\//i, "/full/").replace(/\/product_(smthumb|thumb|detail|lgdetail)\//i, "/product_full/");
		if (lgimg.complete) div.appendChild(lgimg);
		lgimg.onload = function() { div.appendChild(this); }
		if (document.frmItemSelect) {
			if (document.frmItemSelect.c) document.frmItemSelect.c.style.visibility = 'hidden';
		}
		// Track event in Google Analytics
		try { pageTracker._trackEvent('Product Details', 'View Full Image'); } catch(err) {}
		return false;
	} else return true;
}

// Closes the full image popup
BlainCat.closeFullImage = function() {
	AppGlobal.overlay.remove();
	AppGlobal.overlay = null;
	var div = $id("FullImage");
	while (div.firstChild) div.removeChild(div.firstChild);
	if (document.frmItemSelect) {
		if (document.frmItemSelect.c) document.frmItemSelect.c.style.visibility = 'visible';
	}
}

// Opens the store selector popup
BlainCat.openStoreSelector = function() {
	var popup = $id("store-popupobj");
	if (popup) {
		if (AppGlobal.overlay == null) AppGlobal.overlay = new Overlay("store-popupobj");
		var selector = $id("store-select"),
			set = $id("store-set"),
			notfound = $id("store-notfound");
		selector.style.display = '';
		set.style.display = 'none';
		notfound.style.display = 'none';
		if (document.frmItemSelect) {
			if (document.frmItemSelect.c) document.frmItemSelect.c.style.visibility = 'hidden';
		}
		// Track event in Google Analytics
		try { pageTracker._trackEvent('Product Details', 'Open Store Selector'); } catch(err) {}
		return false;
	} else return true;
}

// Closes the store selector popup
BlainCat.closeStoreSelector = function() {
	AppGlobal.overlay.remove();
	AppGlobal.overlay = null;
	if (document.frmItemSelect) {
		if (document.frmItemSelect.c) document.frmItemSelect.c.style.visibility = 'visible';
	}
}

// Changes the local store to the selected store
BlainCat.changeStore = function () {
	var s = $("#ddlStoreNum").val(), b = $("#lblBlainNum").text(), v = $("#hdnVK").val(), p = $.sha1(v + $.sha1(s.toString())), imgProgress = $("#imgStoreProgress");
	$.ajax({
		async: true,
		cache: false,
		url: BlainCat.storeAjaxURL,
		dataType: "xml",
		data: { a: "s", n: s, i: b, h: p },
		beforeSend: function(xhr, settings) { imgProgress.css('visibility', ''); },
		complete: function(xhr, settings) { imgProgress.css('visibility', 'hidden'); },
		success: function(xml) {
			var vLocationName = $("LocationName", xml).text(),
				vPhone = $("Phone", xml).text(),
				vLocatorURL = $("LocatorURL", xml).text(),
				vStatus = $("Status", xml).text(),
				vDomain = $("Domain", xml).text(),
				vExpireDate = new Date(new Date().getTime() + (60 * 1000 * 60 * 60 * 24)),
				cls;
			if (vStatus == "Available for Special Order") cls = "avail-asterisk";
			else cls = (vStatus == "Available" || vStatus == "Limited Availability") ? "avail-yes" : "avail-no";
			$("#lblLocationName").text(vLocationName);
			$("#lblStoreName").text(vLocationName);
			$("#lblLocationPhone").text(vPhone);
			$("#lblStatusStore").text(vStatus);
			$("#hlLocationURL").attr("href", "/stores/" + vLocatorURL);
			$("#pnStoreSelect").hide();
			$("#pnAvailStore").show().attr('class', cls);
			Cookie.set("Local", s, vExpireDate, "/", vDomain);
			// Set panel display
			$("#store-select, #store-notfound").hide();
			$("#store-set").show();
			// Track event in Google Analytics
			try { pageTracker._trackEvent('Product Details', 'Set Local Store', vLocationName); } catch(err) { }
		},
		error: function(xhr, status, err) {
			// Display failed message
			$("#store-select, #store-set").hide();
			$("#store-notfound").show();
		}
	});
}


// Opens a popup window to send product to a friend
BlainCat.sendToFriend = function(id) {
	popup = window.open('/catalog/product_email.aspx?i=' + encodeURIComponent(id), 'SetStore','width=530,height=570,resizable=yes,scrollbars=yes');
	if (window.focus) popup.focus();
}

// Returns the main browser window to the newsletter signup
BlainCat.goToNewsletterSignup = function() {
	window.opener.location.href = '/promotions/newsletter.aspx';
	window.close();
}

// Changes the tab display
BlainCat.displayTab = function(val) {
	BlainCat.toggleTab(false, "Promo");
	BlainCat.toggleTab(false, "Features");
	BlainCat.toggleTab(false, "Swatches");
	BlainCat.toggleTab(false, "Technical");
	BlainCat.toggleTab(false, "Reviews");
	BlainCat.toggleTab(false, "Warranty");
	BlainCat.toggleTab(false, "Diagrams");
	BlainCat.toggleTab(false, "Projects");
	BlainCat.toggleTab(false, "Video");
	if (val == 'P') BlainCat.toggleTab(true, "Promo");
	else if (val == 'F') BlainCat.toggleTab(true, "Features");
	else if (val == "S") BlainCat.toggleTab(true, "Swatches");
	else if (val == "T") BlainCat.toggleTab(true, "Technical");
	else if (val == "V") BlainCat.toggleTab(true, "Reviews");
	else if (val == "W") BlainCat.toggleTab(true, "Warranty");
	else if (val == "D") BlainCat.toggleTab(true, "Diagrams");
	else if (val == "R") BlainCat.toggleTab(true, "Projects");
	else if (val == "M") BlainCat.toggleTab(true, "Video");
}

BlainCat.toggleTab = function(val, id) {
	var pn = $id('pn' + id),
		hl = $id('hl' + id),
		img = $id('img' + id);
	if (pn) pn.className = (val) ? "product-tabshow" : "product-tabhide";
	if (hl && img) img.src = (val) ? img.src.replace("_off.gif", "_on.gif") : img.src.replace("_on.gif", "_off.gif");
	if (val) {
		// Set the height of the customer reviews iframe
		if (id == "Reviews" && typeof jQuery != 'undefined') $("#ifReviews").attr('height', function() { return $(this).contents().height() });
		// Track event in Google Analytics
		try { pageTracker._trackEvent('Product Details', 'Change Tab', id); } catch(err) {}
	}
}

// Toggles the display/non-display of the filter list
BlainCat.toggleFilterList = function(link_elem, divname) {
	var div = $id(divname);
	if (div) {
		if (div.style.display == "none") {
			div.style.display = ""
			link_elem.className = "open";
		} else {
			div.style.display = "none"
			link_elem.className = "closed";
		}
	}
}

// Adds an item to the cart
BlainCat.addToCart = function(blain, parent) {
	if (parent.length > 0) BlainCat.openChildSelector(blain);
	else {
		self.location = BlainCat.productDetailURL + '?a=A&i=' + encodeURIComponent(blain);
		if (BlainCat.cartPopup != null) BlainCat.closeChildSelector();
	}
	return false;
}

// Goes to a product detail page
BlainCat.viewDetail = function(blain) {
	location.href = BlainCat.productDetailURL + '?i=' + encodeURIComponent(blain);
	BlainCat.closeChildSelector();
}

// Opens a popup window to select a child item
BlainCat.openChildSelector = function(blain) {
	var mainload = $id("cartselect-mainload"),
		error = $id("cartselect-error"),
		content = $id("cartselect-content"),
		image = $id("cartselect-image");
	if (mainload) mainload.style.display = '';
	if (error) error.style.display = 'none';
	if (content) content.style.display = 'none';
	if (image) image.style.visibility = 'hidden';
	BlainCat.cartPopup = new Overlay("cartselect-popupobj");
	BlainCat.getChildList(blain);
}

// Changes the information regarding the current product
BlainCat.changeProductInfo = function(blain) {
	var subload = $id("cartselect-subload"),
		childinfo = $id("cartselect-child"),
		image = $id("cartselect-image");
	if (subload) subload.style.display = '';
	if (childinfo) childinfo.style.display = 'none';
	if (image) image.style.visibility = 'hidden';
	BlainCat.getProductInfo(blain);
}

// Gets information regarding the current product
BlainCat.getProductInfo = function (blain) {
	$.ajax({ cache: false, url: BlainCat.ajaxURL, data: { a: "pd", i: encodeURIComponent(blain) }, dataType: "xml", success: function(data, status, xhr) {
		var xml = $(data),
			imgProduct = $id("cartselect-image"),
			imgCartButton = $id("cartselect-cartbutton"),
			vVendorBrand = xml.find("VendorBrand").text(),
			vProductName = xml.find("ProductName").text(),
			vWebAttributeDescription = xml.find("WebAttributeDescription").text(),
			vBlainNumber = xml.find("BlainNumber").text(),
			vMFGItemNumber = xml.find("MFGItemNumber").text(),
			vImageURL = xml.find("ImageDetailURL").text(),
			vCurrentPrice = xml.find("CurrentPrice").text(),
			vRegularPrice = xml.find("RegularPrice").text(),
			vPriceModifier = xml.find("PriceModifier").text(),
			vPromoPrice = xml.find("PromoPrice").text(),
			vPromoExpiration = xml.find("PromoExpiration").text(),
			vDisplayMode = xml.find("DisplayMode").text();

		// Insert product text
		$("#hVendorBrand").text(vVendorBrand);
		$("#hProductName").text(vProductName);
		$("#hWebAttributeDescription").text("Select " + vWebAttributeDescription + ":");
		$("#lblMfrNum").text(vMFGItemNumber);
		$("#lblBlainNumber").text(vBlainNumber);

		// Pricing information
		if(vCurrentPrice == (vPromoPrice - vPriceModifier) && vCurrentPrice >= (vRegularPrice - vPriceModifier)) {
			$("#lblPrice").html("Price: <b>" + (vPromoPrice - vPriceModifier).toString().toCurrency() + "</b><br />\r\n");
			if(vPriceModifier > 0) $("#lblPriceSuffix").html("Find Value, after $" + vPriceModifier.toString().toCurrency() + " exchange").show();
			else $("#lblPriceSuffix").html("Find Value").show();
		} else if(vCurrentPrice == (vPromoPrice - vPriceModifier)) {
			$("#lblPrice").attr("class", "strikethru").html("Price: <b>$" + (vRegularPrice - vPriceModifier).toString().toCurrency() + "</b><br />\r\n");
			$("#lblPromoPrice").html("Sale Price: <b>$" + vCurrentPrice.toString().toCurrency() + "</b><br />\r\n").show();
			if(vPriceModifier > 0) $("#lblPriceSuffix").html("After $" + vPriceModifier.toString().toCurrency() + " exchange, through " + BlainCat.promoExpirationString(new Date(vPromoExpiration))).show();
			else $("#lblPriceSuffix").html("Through " + BlainCat.promoExpirationString(new Date(vPromoExpiration))).show();
		} else {
			$("#lblPrice").html("Price: <b>$" + vCurrentPrice.toString().toCurrency() + "</b><br />\r\n");
			$("#lblPromoPrice").hide();
			if(vPriceModifier > 0) $("#lblPriceSuffix").html("After $" + vPriceModifier.toString().toCurrency() + " exchange").show();
			else $("#lblPriceSuffix").hide();
		}
		// Determine if this is an exchange price
		if(vDisplayMode.endsWith("f")) $("#lblPriceComment").html("per ft.<br />\r\n").show();
		else $("#lblPriceComment").hide();

		// Insert image
		imgProduct.src = vImageURL;
		imgProduct.onload = function () { }
		if(imgProduct.complete) imgProduct.style.visibility = '';
		else imgProduct.onload = function () { imgProduct.style.visibility = ''; }
		// Assign cart button target
		imgCartButton.onclick = function () { BlainCat.addToCart(blain, ""); };
		// Display product information
		$("#cartselect-mainload, #cartselect-subload, #cartselect-error").hide();
		$("#cartselect-content, #cartselect-child").show();
	}, error: function(xhr, status, error) {
		// Get failed status error message
		var message = "";
		message = xhr.statusText;
		if(message.length == 0) message = "Unspecified error " + xhr.status;
		// Display error message
		if(message != "No Data Available" || message != "OK") {
			$("#cartselect-errormsg").text("We're sorry for the confusion, but an it seems that an error may have occurred on this end.  Please click on the button below to view details about this product.");
		}
		// Display error information
		$("#cartselect-mainload, #cartselect-subload, #cartselect-content, #cartselect-child").hide();
		$("#cartselect-error").show();
		$id("cartselect-detailbutton").onclick = function () { BlainCat.viewDetail(blain, ""); };
	}});
	/*
	var request = Ajax.newRequest();
	request.open("POST", BlainCat.ajaxURL, true);
	var params = "a=pd&i=" + encodeURIComponent(blain);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.onreadystatechange = function () {
		if(request.readyState == 4) {
			if(request.status == 200) {
				var xmlDoc = request.responseXML;
				var imgProduct = $id("cartselect-image"),
					imgCartButton = $id("cartselect-cartbutton"),
					vVendorBrand = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("VendorBrand")[0]),
					vProductName = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("ProductName")[0]),
					vWebAttributeDescription = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("WebAttributeDescription")[0]),
					vBlainNumber = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("BlainNumber")[0]),
					vMFGItemNumber = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("MFGItemNumber")[0]),
					vImageURL = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("ImageDetailURL")[0]),
					vCurrentPrice = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("CurrentPrice")[0]),
					vRegularPrice = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("RegularPrice")[0]),
					vPriceModifier = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("PriceModifier")[0]),
					vPromoPrice = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("PromoPrice")[0]),
					vPromoExpiration = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("PromoExpiration")[0]).toDate(),
					vDisplayMode = AppGlobal.getXMLValue(xmlDoc.getElementsByTagName("DisplayMode")[0]);

				// Insert product text
				$("#hVendorBrand").text(vVendorBrand);
				$("#hProductName").text(vProductName);
				$("#hWebAttributeDescription").text("Select " + vWebAttributeDescription + ":");
				$("#lblMfrNum").text(vMFGItemNumber);
				$("#lblBlainNumber").text(vBlainNumber);

				// Pricing information
				if(vCurrentPrice == (vPromoPrice - vPriceModifier) && vCurrentPrice >= (vRegularPrice - vPriceModifier)) {
					$("#lblPrice").html("Price: <b>" + (vPromoPrice - vPriceModifier).toString().toCurrency() + "</b><br />\r\n");
					if(vPriceModifier > 0) $("#lblPriceSuffix").html("Find Value, after $" + vPriceModifier.toString().toCurrency() + " exchange").show();
					else $("#lblPriceSuffix").html("Find Value").show();
				} else if(vCurrentPrice == (vPromoPrice - vPriceModifier)) {
					$("#lblPrice").attr("class", "strikethru").html("Price: <b>$" + (vRegularPrice - vPriceModifier).toString().toCurrency() + "</b><br />\r\n");
					$("#lblPromoPrice").html("Sale Price: <b>$" + vCurrentPrice.toString().toCurrency() + "</b><br />\r\n").show();
					if(vPriceModifier > 0) $("#lblPriceSuffix").html("After $" + vPriceModifier.toString().toCurrency() + " exchange, through " + vPromoExpiration).show();
					else $("#lblPriceSuffix").html("Through " + vPromoExpiration).show();
				} else {
					$("#lblPrice").html("Price: <b>$" + vCurrentPrice.toString().toCurrency() + "</b><br />\r\n");
					$("#lblPromoPrice").hide();
					if(vPriceModifier > 0) $("#lblPriceSuffix").html("After $" + vPriceModifier.toString().toCurrency() + " exchange").show();
					else $("#lblPriceSuffix").hide();
				}
				// Determine if this is an exchange price
				if(vDisplayMode.endsWith("f")) $("#lblPriceComment").html("per ft.<br />\r\n").show();
				else $("#lblPriceComment").hide();

				// Insert image
				imgProduct.src = vImageURL;
				imgProduct.onload = function () { }
				if(imgProduct.complete) imgProduct.style.visibility = '';
				else imgProduct.onload = function () { imgProduct.style.visibility = ''; }
				// Assign cart button target
				imgCartButton.onclick = function () { BlainCat.addToCart(blain, ""); };
				// Display product information
				$("#cartselect-mainload, #cartselect-subload, #cartselect-error").hide();
				$("#cartselect-content, #cartselect-child").show();
			} else {
				// Get failed status error message
				var message = "";
				message = request.statusText;
				if(message.length == 0) message = "Unspecified error " + request.status;
				// Display error message
				if(message != "No Data Available" || message != "OK") {
					$("#cartselect-errormsg").text("We're sorry for the confusion, but an it seems that an error may have occurred on this end.  Please click on the button below to view details about this product.");
				}
				// Display error information
				$("#cartselect-mainload, #cartselect-subload, #cartselect-content, #cartselect-child").hide();
				$("#cartselect-error").show();
				$id("cartselect-detailbutton").onclick = function () { BlainCat.viewDetail(blain, ""); };
			}
		}
	}
	request.send(params);
	*/
}

// Formats the expiration date of a promo
BlainCat.promoExpirationString = function(dt) {
	if (dt.getHours() == 0 && dt.getMinutes() == 0) return dt.Add(-1, "D").toFormattedString("n/j/Y");
	else if (dt.toFormattedString("n/j/Y") == (new Date).toFormattedString("n/j/Y") && dt.getHours() != 23 && dt.getMinutes() != 59) {
		if (dt.getMinutes() == 59) dt.setHours(dt.getHours()+1);
		return dt.toFormattedString("g A") + " today (CT)";
	} else if (dt.getHours() != 23 || dt.getMinutes() != 59) {
		if (dt.getMinutes() == 59) dt.setHours(dt.getHours()+1);
		return dt.toFormattedString("g A") + " (CT) on " + dt.toFormattedString("n/j/Y");
	} else return dt.toFormattedString("n/j/Y");
}

// Gets the list of child products
BlainCat.getChildList = function(blain) {
	$.ajax({ cache: false, url: BlainCat.ajaxURL, data: { a: "pcl", ecom: "1", i: encodeURIComponent(blain) }, dataType: "xml", success: function(data, status, xhr) {
		// Add child products to the drop-down list
		var ddlBlainNumber = $id("ch"), vBlainNumber, vWebAttributeValue, node;
		ddlBlainNumber.options.length = 0;
		$(data).find("Product").each(function() {
			node = $(this);
			vBlainNumber = node.find("BlainNumber").text();
			vWebAttributeValue = node.find("WebAttributeValue").text();
			ddlBlainNumber.options.add(new Option(vWebAttributeValue, vBlainNumber));
		});
		// Select the current blain number in the list
		for(x = 0; x < ddlBlainNumber.options.length; x++) if(ddlBlainNumber.options[x].value == blain) { ddlBlainNumber.selectedIndex = x; break; }
		// Now get the product info
		BlainCat.getProductInfo(blain);
	}, error: function(xhr, status, error) {
		// Get failed status error message
		var message = "";
		message = xhr.statusText;
		if (message.length == 0) message = "Unspecified error " + xhr.status;
		// Display error message
		if (message != "No Data Available" || message != "OK") {
			$("#cartselect-errormsg").text("We're sorry for the confusion, but an it seems that an error may have occurred on this end.  Please click on the button below to view details about this product.");
		}
		// Display error information
		$("#cartselect-mainload, #cartselect-subload, #cartselect-content, #cartselect-child").hide();
		$("#cartselect-error").show();
		$id("cartselect-detailbutton").onclick = function () { BlainCat.viewDetail(blain, ""); };
	}});
	/*
	var request = Ajax.newRequest(),
		params = "a=pcl&ecom=1&i=" + encodeURIComponent(blain),
		x;
	request.open("POST", BlainCat.ajaxURL, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.onreadystatechange = function () {
		if(request.readyState == 4) {
			if(request.status == 200) {
				var xmlDoc = request.responseXML;
				var vProducts = xmlDoc.getElementsByTagName("Product");
				var ddlBlainNumber = $id("ch");
				// Add child products to the drop-down list
				var vBlainNumber, vWebAttributeValue;
				ddlBlainNumber.options.length = 0;
				for(x = 0; x < vProducts.length; x++) {
					vBlainNumber = AppGlobal.getXMLValue(vProducts[x].getElementsByTagName("BlainNumber")[0]);
					vWebAttributeValue = AppGlobal.getXMLValue(vProducts[x].getElementsByTagName("WebAttributeValue")[0]);
					ddlBlainNumber.options.add(new Option(vWebAttributeValue, vBlainNumber));
				}
				// Select the current blain number in the list
				for(x = 0; x < ddlBlainNumber.options.length; x++) if(ddlBlainNumber.options[x].value == blain) { ddlBlainNumber.selectedIndex = x; break; }
				// Now get the product info
				BlainCat.getProductInfo(blain);
			} else {
				// Get failed status error message
				var message = "";
				message = request.statusText;
				if(message.length == 0) message = "Unspecified error " + request.status;
				// Display error message
				if(message != "No Data Available" || message != "OK") {
					$("#cartselect-errormsg").text("We're sorry for the confusion, but an it seems that an error may have occurred on this end.  Please click on the button below to view details about this product.");
				}
				// Display error information
				$("#cartselect-mainload, #cartselect-subload, #cartselect-content, #cartselect-child").hide();
				$("#cartselect-error").show();
				$id("cartselect-detailbutton").onclick = function () { BlainCat.viewDetail(blain, ""); };
			}
		}
	}
	request.send(params);
	*/
}

// Closes the popup window
BlainCat.closeChildSelector = function() {
	BlainCat.cartPopup.remove();
	BlainCat.cartPopup = null;
}

// Gets the volume pricing
BlainCat.getVolumePricing = function (blain, store, obj) {
	var content = $("#volprice-popup").hide(),
		progress = $("#volprice-popupprogress").show(),
		popup = $id("volprice-popupobj");
	if(popup) {
		// Determine position of popup
		var framepos = $("#siteframe").offset(),
			objpos = $(obj).offset();
		var x = parseInt(objpos.left + (obj.offsetWidth / 2) - 150 - framepos.left) + 'px',
			y = parseInt(objpos.top + obj.offsetHeight - 5 - framepos.top) + 'px',
			node;
		$(popup).css({ "left": x, "top": y }).show();
		$.ajax({ cache: false, url: BlainCat.ajaxURL, data: { a: "vp", i: blain, snum: store }, dataType: "xml", success: function(xml) {
			content.empty();
			var table = '<table cellspacing="0" cellpadding="0" border="0">';
			$(xml).find("VolumePriceItem").each(function () {
				node = $(this);
				table += '<tr><th>' + node.find("QtyRange").text() + '</th>'
						+ '<td>' + node.find("CurrentPriceHTML").text() + '</td></tr>';
			});
			progress.hide();
			content.html(table).show();
		}});
	}
}

// Closes the volume pricing popup
BlainCat.closeVolumePricing = function() {
	$("#volprice-popupobj").hide();
}

// OnLoad directive for this class
BlainCat.onLoad = function () {
	var cssprefix = AppGlobal.cssPrefix(),
		imgprefix = AppGlobal.imagePrefix();
	// Conditionally preload product navigation images
	if($id("ucProductList_divProductNavTop")) {
		(new Image()).src = cssprefix + '/images/productnav/gridview_over.png';
		(new Image()).src = cssprefix + '/images/productnav/listview_over.png';
		(new Image()).src = cssprefix + '/images/productnav/nextprev_over.png';
		(new Image()).src = cssprefix + '/images/productnav/pagenum_over.png';
	}
	// Conditionally preload popup background images
	if($id("cartselect-popupobj")) (new Image()).src = cssprefix + '/images/interface/cart_selector_bkg.png';
	if($id("store-popupobj")) (new Image()).src = cssprefix + '/images/interface/storeselect_bkg.png';
	if($id("image-popupobj")) (new Image()).src = cssprefix + '/images/interface/image_bkg.png';
	if($id("volprice-popupobj")) {
		(new Image()).src = cssprefix + '/images/interface/volprice_popup.png';
		(new Image()).src = cssprefix + '/images/interface/volprice_popup_bkg.png';
	}
	// Conditionally preload tab images
	if($id("imgPromo")) {
		(new Image()).src = imgprefix + '/images/headers/promo_off.gif';
		(new Image()).src = imgprefix + '/images/headers/features_on.gif';
	}
	if($id("imgFeatures")) (new Image()).src = imgprefix + '/images/headers/features_off.gif';
	if($id("imgSwatches")) (new Image()).src = imgprefix + '/images/headers/colors_styles_on.gif';
	if($id("imgTechnical")) (new Image()).src = imgprefix + '/images/headers/technical_description_on.gif';
	if($id("imgWarranty")) (new Image()).src = imgprefix + '/images/headers/warranty_on.gif';
	if($id("imgDiagrams")) (new Image()).src = imgprefix + '/images/headers/product_diagrams_on.gif';
	if($id("imgProjects")) (new Image()).src = imgprefix + '/images/headers/related_projects_on.gif';
	if($id("imgReviews")) (new Image()).src = imgprefix + '/images/headers/reviews_on.gif';
	if($id("imgVideo")) (new Image()).src = imgprefix + '/images/headers/video_clips_on.gif';
	// On product detail pages, reset the child selection
	if($id("c")) BlainCat.resetChildSelection();
	// On US Auto tires, look up external quantity available
	if($id("frmUSAutoTire")) {
		var pnAvailOnlineWait = $id("pnAvailOnlineWait"),
			pnAvailOnline = $id("pnAvailOnline"),
			pnAvailOnlineUnknown = $id("pnAvailOnlineUnknown"),
			lblStatusOnline = $("#lblStatusOnline"),
			txtQty = $("#txtQty"),
			bc = $id("hdnBrandCode").value,
			b = $("#lblBlainNum").text(),
			v = $id("hdnVK").value,
			p = $.sha1(v + $.sha1(bc.toString())),
			vOnHand;
		$.ajax({ cache: false, url: BlainCat.ajaxURL, data: { a: "usats", i: b, h: p }, success: function(data, status, xhr) {
			vOnHand = parseInt($("OnHand", data).text());
			pnAvailOnlineWait.style.display = 'none';
			pnAvailOnlineUnknown.style.display = 'none';
			pnAvailOnline.style.display = '';
			pnAvailOnline.className = (vOnHand > 0) ? "avail-yes" : "avail-no";
			if (vOnHand > 4) lblStatusOnline.text("Available");
			else if (vOnHand > 0) {
				lblStatusOnline.text("Limited Availability");
				try { pageTracker._trackEvent('US Auto Tire', 'Limited Stock', b); } catch(err) {}
			} else {
				lblStatusOnline.text("Temporarily Unavailable");
				try { pageTracker._trackEvent('US Auto Tire', 'Out Of Stock', b); } catch(err) {}
			}
			if (vOnHand >= 4) txtQty.val("4");
			else if (vOnHand > 0) txtQty.val(vOnHand.toString());
		}, error: function(xhr, status, error) {
			pnAvailOnlineWait.style.display = 'none';
			pnAvailOnlineUnknown.style.display = '';
			pnAvailOnline.style.display = 'none';
		}, dataType: "xml", timeout: 15000 });
	}
	// Format read-review link, if present
	$("div.pr-snippet-read-reviews > a").click(function() {
		BlainCat.displayTab("V");
		location.href = "#ReviewHeader";
		return false;
	});
}

if (window.addEventListener) window.addEventListener("load", BlainCat.onLoad, false);
else if (window.attachEvent) window.attachEvent("onload", BlainCat.onLoad);

