// ******************************************************************
// cdsProductDetails.js
//
// Copyright (c) 2007 Catalog Data Solutions. All Rights Reserved.
//
// Displays information about a given product as well as cad and
// eCommerce controls
// ******************************************************************
if (typeof fixUrl != "function") document.write('<script type="text/javascript" src="scripts/cdsUtilities.js"></script>');
if (typeof attributeDisplayOrder != "object") document.write('<script type="text/javascript" src="scripts/productDetailsAttributeOrder.js"></script>');

function cdsProductDetails() {
	this.controlsElementId = properties["showProduct.controlsElement"];
	this.attributesElementId = properties["showProduct.attributesElement"];
    this.openAttachmentTab = (properties["showProduct.openAttachmentTab"].toUpperCase().indexOf("Y") == 0) ? true : false;
	this.imagePosition = properties["showProduct.imagePosition"];
	this.showProductNumber = (properties["showProduct.displayProductNumber"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.showCategory = (properties["showProduct.displayCategory"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.showPrintPage = (properties["showProduct.displayPrintPage"].toUpperCase().indexOf("Y") == 0) ? true : false;
	this.showCartQuantity = (properties["showProduct.displayCartQuantity"].toUpperCase().indexOf("Y") == 0) ? true : false;
	this.showAllAttributesInCart = (properties["cart.displayAllAttributes"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.isPrintPDF = (properties["showProduct.printPDF"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.seperateDynamicAttributes = (properties["showProduct.seperateAttributes"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.addTopSpotLinks = (properties["global.addTopSpotLinks"].toUpperCase().indexOf("Y") == 0);
	this.hasRFQCart = (properties["cart.enableCart"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.cartButtonLabel = properties["cart.buttonLabel"];
    this.hasNSCart = (properties["cart.enableNSCart"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.hasNSDetails = (properties["cart.enableNSProductLink"].toUpperCase().indexOf("Y") == 0) ? true : false;
    this.NSCartDomain = properties["cart.NSCartDomain"];
    this.genericAddCartUrl = properties["cart.genericAddCartUrl"];
    if (this.genericAddCartUrl && this.genericAddCartUrl.length === 0) {
        this.genericAddCartUrl = null;
    }
	this.productNumber = entities.ProductDetailsEntity.productNumber;
	this.displayProductNumber = entities.ProductDetailsEntity.displayProductNumber;
    if (this.displayProductNumber == null || this.displayProductNumber.length == 0) {
        this.displayProductNumber = this.productNumber;
    }
	this.categoryLabel = entities.ProductDetailsEntity.categoryLabel;
	this.productFlag = entities.ProductDetailsEntity.productFlag;
	this.eCommerceId = entities.ProductDetailsEntity.eCommerceId;
	this.attributes = entities.ProductDetailsEntity.attributes;
	this.cadAttributes = entities.CADEntity.attributes;
	this.imageUrl = fixUrl(entities.ProductDetailsEntity.imageUrl);
	this.image = null;
	if (this.imageUrl != null) {
		this.image = new Image();
		this.image.src = this.imageUrl;
		this.image.className = "cdsShowProductImage";
	}
    this.thumbnailColumn = properties["global.thumbnailColumn"];
	this.cadAttributeElements = null;
    this.precisionMap = [];

	// check for NO DOMAIN TEMPLATE argument
	parsePageArguments();
	this.printFriendly = false;
	if (pageArguments["nodt"] != null && pageArguments["nodt"].toLowerCase() == "true") this.printFriendly = true;

	// initialize the service manual widget
	this.init = function() {
		this.display();
	};

    // initialize after unit change
    this.initCallback = function(context) {
        var e = document.getElementById(context.attributesElementId);
        while (e.hasChildNodes()) {
            e.removeChild(e.lastChild);
        }
        e = document.getElementById(context.controlsElementId);
        while (e.hasChildNodes()) {
            e.removeChild(e.lastChild);
        }
        context.display();
    };
    this.numberFormatter = new cdslib.NumberFormatter(properties["global.defaultUnit"], this.initCallback, this);
    if (properties["global.defaultUnit"] === "english") {
        this.numberFormatter.renderMetricFirst = false;
    }

	// get attributes for custom pn/pricing
    this.getCustomAttributes = function() {
        var e, i, o = {"pn":this.productNumber};

        if (this.cadAttributes != null && this.cadAttributes.length > 0 && this.cadAttributeElements != null &&
                    this.cadAttributeElements.length > 0) {
            for (i = 0; i < this.cadAttributeElements.length; i++) {
                e = this.cadAttributeElements[i];

                if (e.tagName != null && e.tagName.toUpperCase() == "SELECT") {
                    o[e.attributeLabel] = e.options[e.selectedIndex].value;
                } else if (e.tagName != null && e.tagName.toUpperCase() == "INPUT" && e.type == "checkbox" && e.checked == true) {
                    o[e.attributeLabel] = e.valueLabel;
                } else {
                    o[e.attributeLabel] = e.value;
                }
            }
        }

        return o;
    };

    // get all attributes for printing
    this.getAllAttributes = function() {
        var e, i, v, o = {};

        if (this.cadAttributes != null && this.cadAttributes.length > 0 && this.cadAttributeElements != null &&
                    this.cadAttributeElements.length > 0) {
            for (i = 0; i < this.cadAttributeElements.length; i++) {
                e = this.cadAttributeElements[i];
                l = e.attributeLabel.trim();

                if (e.tagName != null && e.tagName.toUpperCase() == "SELECT") {
                    o[l] = e.options[e.selectedIndex].value;
                } else if (e.tagName != null && e.tagName.toUpperCase() == "INPUT" && e.type == "checkbox") {
                    if (e.checked == true) {
                        v = o[l];
                        if (!v) {
                            v = "";
                        } else {
                            v += "<br />";
                        }
                        v += e.valueLabel.entityify();
                        o[l] = v;
                    }
                } else {
                    o[l] = e.value;
                }
            }
        }

        for (i = 0; i < this.attributes.length; i++) {
            if (this.attributes[i].type != "attachment") {
                var v = this.attributes[i].value;
                if (this.attributes[i].type === "decimal" || this.attributes[i].type === "fraction") {
                    v = this.numberFormatter.formatForDisplay(v, this.precisionMap[i], this.attributes[i].unit,
                            this.attributes[i].unitMetric, this.attributes[i].unitEnglish,
                            (this.attributes[i].type === "fraction"));
                } else {
                    v = this.numberFormatter.formatForDisplay(v, null, null, null, null, false);
                }
                o[this.attributes[i].label.trim()] = v.entityify();
            }
        }

        return o;
    };

    // set custom pricing and part numbering
    this.setCustomPNandPrice = function() {
        var pn = null, price = null, e = null;

        if (typeof getCustomPN === "function") {
            pn = getCustomPN(this.getCustomAttributes());
            if (pn !== null) {
                e = document.getElementById("cdsShowProductProductNumber");
                if (e !== null) {
                    document.getElementById("cdsShowProductProductNumber").innerHTML = pn;
                }
                e = document.getElementById("cdsCategoryBreadcrumbCurrent");
                if (e !== null) {
                    document.getElementById("cdsCategoryBreadcrumbCurrent").innerHTML = pn;
                }
            }
        }
        if (typeof getCustomPrice === "function") {
            price = getCustomPrice(this.getCustomAttributes());
            if (price !== null) {
                e = document.getElementById("cdsShowProductPriceCell");
                if (e !== null) {
                    document.getElementById("cdsShowProductPriceCell").innerHTML = "Price: " + price;
                }
            }
        }
    };

    // add product to cart
    this.onClickGenericAddtoCart = function(pn, eid) {
        var qstr = document.getElementById("cdsShowProductCartQuantityInput");
        var qval = parseInt(qstr.value);
        if (isNaN(qval) || qval < 0) {
            alert("Please enter a valid quantity.");
            return;
        }
        var action = this.genericAddCartUrl.replace(/%ID%/g, encodeURIComponent(this.productNumber)).replace(/%EID%/g, this.eCommerceId).replace(/%QUANTITY%/g, qval);
        location.href = action;
    };

    this.onClickPrintPDF = function() {
        var i, k, o, url = 'print?domain=' + domain +
                '&product=' + encodeURIComponent(this.displayProductNumber.entityify()) +
                '&category=' + encodeURIComponent(this.categoryLabel.entityify()) +
                '&image=' + encodeURIComponent(this.imageUrl);

        o = this.getAllAttributes();
        i = 1;
        for (k in o) {
            url += '&a' + i + '=' + encodeURIComponent(k.entityify());
            // we're not going to entityify here becuase we do it in getAllAttributes()
            url += '&v' + i + '=' + encodeURIComponent(o[k]);
            i++;
        }

        location.href = url;
    };

	this.onClickAddtoCart = function() {
		var qstr = document.getElementById("cdsShowProductCartQuantityInput");
		var qval = parseInt(qstr.value);
		if (isNaN(qval) || qval < 0) {
			alert("Please enter a valid quantity.");
			return;
		}

		// if cds rfq cart, add to that
		if (this.hasRFQCart) {
			var s = "service?domain=" + domain + "&command=cart&product=" + this.productNumber + "&quantity=" + qval;
			// gather cad attributes if available
			var cadString = "";
			if (this.cadAttributes != null && this.cadAttributes.length > 0 && this.cadAttributeElements != null && this.cadAttributeElements.length > 0) {
				for (var i = 0; i < this.cadAttributeElements.length; i++) {
					// var e = document.getElementById("cdsShowProductCADAttribute" + i);
					var e = this.cadAttributeElements[i];

					// check for select
					if (e.tagName != null && e.tagName.toUpperCase() == "SELECT") {
						if (cadString.length > 0) cadString += "|";
						cadString += e.attributeLabel + ":" + e.options[e.selectedIndex].value;

					// check for checkbox
					} else if (e.tagName != null && e.tagName.toUpperCase() == "INPUT" && e.type == "checkbox") {
						if (e.checked == true) {
							if (cadString.length > 0) cadString += "|";
							cadString += e.attributeLabel + ":" + e.valueLabel;
						}

					// must be text box
					} else {
						if (cadString.length > 0) cadString += "|";
						cadString += e.attributeLabel + ":" + e.value;
					}
				}
				s += "&attributes=" + encodeURIComponent(cadString);
			}
			if (this.showAllAttributesInCart) {
				var stdattr = "";
				for (var i = 0; i < this.attributes.length; i++) {
					if (this.attributes[i].type != "attachment") {
						if (stdattr.length > 0) stdattr += "|";
						stdattr += encodeURIComponent(this.attributes[i].label) + ":" + encodeURIComponent(this.attributes[i].value);
					}
				}
				if (stdattr.length > 0) s += "&stdattributes=" + encodeURIComponent(stdattr);
			}

			// document.getElementById("cdsShowProductCartFormQuantity").value = qval;
			// document.getElementById("cdsShowProductCartFormAttributes").value = cadString;
			location.href = s;
		} else {
			document.getElementById("cdsShowProductCartQuantityForm").value = qval;
			var form = document.getElementById("cdsShowProductCartForm");
			form.submit();
		}
	}

	// draw ourself
	this.display = function() {
		// create controls elements
		// title
		var controls = document.createElement("table");
		tbody = document.createElement("tbody");
		controls.appendChild(tbody);
		var tr = document.createElement("tr");
		tbody.appendChild(tr);
		var td = document.createElement("td");
		tr.appendChild(td);
		td.className = "cdsShowProductTitleCell";
        td.setAttribute("id", "cdsShowProductProductNumber");
		var s = "Product Details";
        if (this.showProductNumber) s += " for " + this.displayProductNumber;
		td.appendChild(document.createTextNode(s));

		// category
        if (this.showCategory) {
            tr = document.createElement("tr");
            tbody.appendChild(tr);
            td = document.createElement("td");
            tr.appendChild(td);
            td.className = "cdsShowProductCategoryCell";
            td.innerHTML = "Category: " + this.categoryLabel;
        }

        // price
        if (typeof getCustomPrice === "function") {
            tr = document.createElement("tr");
            tbody.appendChild(tr);
            td = document.createElement("td");
            tr.appendChild(td);
            td.setAttribute("id", "cdsShowProductPriceCell");
            td.appendChild(document.createTextNode("Price: "));
        }

		// print me controls
		if (this.printFriendly) {
			tr = document.createElement("tr");
			tbody.appendChild(tr);
			td = document.createElement("td");
			td.className = "cdsShowProductPrintMeCell";
			tr.appendChild(td);
			var anchor = document.createElement("a");
			td.appendChild(anchor);
			anchor.setAttribute("href", "javascript:window.print()");
			anchor.appendChild(document.createTextNode("Print this page"));
        } else if (this.showPrintPage) {
			tr = document.createElement("tr");
			tbody.appendChild(tr);
			td = document.createElement("td");
			td.className = "cdsShowProductPrintMeCell";
			tr.appendChild(td);
			var anchor = document.createElement("a");
			td.appendChild(anchor);
            if (this.isPrintPDF) {
                anchor.controller = this;
                anchor.onclick = function() { this.controller.onClickPrintPDF(); return false; }
                anchor.setAttribute("href", "#");
            } else {
			    var url = location.href + "&nodt=true";
                anchor.setAttribute("href", url);
                anchor.setAttribute("target", "_blank");
            }
			anchor.appendChild(document.createTextNode("Printer friendly view"));
		}

		// cad model controls
		if (entities.CADEntity.hasCAD && !this.printFriendly) {
			tr = document.createElement("tr");
			tbody.appendChild(tr);
			td = document.createElement("td");
			tr.appendChild(td);
			td.className = "cdsShowProductCADCell";
			td.appendChild(widgets.cdsCADService.display());
		}

		// cart controls
        if (this.genericAddCartUrl && !this.printFriendly) {
            tr = document.createElement("tr");
            tbody.appendChild(tr);
            td = document.createElement("td");
            tr.appendChild(td);
            td.className = "cdsShowProductShoppingCartCell";
            var inp = document.createElement("input");
            inp.setAttribute("type", "button");
            td.appendChild(inp);
            inp.setAttribute("value", this.cartButtonLabel);
            inp.controller = this;
            inp.onclick = function() { this.controller.onClickGenericAddtoCart(); }
            inp = document.createElement("input");
            inp.setAttribute("type", "text");
            inp.setAttribute("id", "cdsShowProductCartQuantityInput");
            inp.setAttribute("size", "4");
            inp.setAttribute("value", "1");
            if (!this.showCartQuantity) inp.style.display = "none";
            td.appendChild(inp);
        }
        if (this.hasNSCart && !this.printFriendly) {
            tr = document.createElement("tr");
            tbody.appendChild(tr);
            td = document.createElement("td");
            tr.appendChild(td);
            td.className = "cdsShowProductNSShoppingCartCell";
            td.innerHTML = '<form method="post" action="http://' + this.NSCartDomain + '/' + this.productNumber + '.aspx">\n' +
                           '  <label>Quantity: <input name="quantity" type="text" value="1" maxlength="10" size="3" /></label>\n' +
                           '  <input type="image" name="addtocart" id="addtocartImage" src="http://' + this.NSCartDomain + '/themes/default/images/buttons/cart_btn_add.gif" />\n' +
                           '</form>';
        }
        if (this.hasNSDetails && !this.printFriendly) {
            tr = document.createElement("tr");
            tbody.appendChild(tr);
            td = document.createElement("td");
            tr.appendChild(td);
            td.className = "cdsShowProductNSShoppingCartCell";


            td.innerHTML = '<a href="http://' + this.NSCartDomain + '/' + this.productNumber.replace("/","") + '.aspx"' + ((this.addTopSpotLinks && typeof pageTracker != "undefined") ? ' onclick="pageTracker._link(this.href); return false;"' : '') + '>Buy Online</a>';
        }
        if ((this.hasRFQCart || this.eCommerceId != null) && !this.genericAddCartUrl && !this.printFriendly) {
			tr = document.createElement("tr");
			tbody.appendChild(tr);
			td = document.createElement("td");
			tr.appendChild(td);
			td.className = "cdsShowProductShoppingCartCell";
			var inp = document.createElement("input");
			inp.setAttribute("type", "button");
			td.appendChild(inp);
            inp.setAttribute("value", this.cartButtonLabel);
			inp.controller = this;
			inp.onclick = function() { this.controller.onClickAddtoCart(); }
			inp = document.createElement("input");
			inp.setAttribute("type", "text");
			inp.setAttribute("id", "cdsShowProductCartQuantityInput");
			inp.setAttribute("size", "4");
			inp.setAttribute("value", "1");
			if (!this.showCartQuantity) inp.style.display = "none";
			td.appendChild(inp);
			tr = document.createElement("tr");
			tbody.appendChild(tr);
			td = document.createElement("td");
			tr.appendChild(td);
			if (this.eCommerceId != null) {
				td.innerHTML = '<form id="cdsShowProductCartForm" name="cart_quantity" action="' + properties["global.zcAddProductUrl"] + '" method="post" enctype="application/x-www-form-urlencoded"><input id="cdsShowProductCartQuantityForm" type="hidden" name="cart_quantity" value="10" /><input type="hidden" name="products_id" value="' + this.eCommerceId + '" /></form>';
			} else {
				var s = '<form id="cdsShowProductCartForm" name="cdsShowProductCartForm" action="service" method="post" enctype="application/x-www-form-urlencoded">';
				s += '<input type="hidden" name="domain" value="' + domain + '" />';
				s += '<input type="hidden" name="command" value="cart" />';
				s += '<input type="hidden" name="product" value="' + this.productNumber + '" />';
				s += '<input id="cdsShowProductCartFormAttributes" type="hidden" name="attributes" value="" />';
				s += '<input id="cdsShowProductCartFormQuantity" type="hidden" name="quantity" value="0" />';
				if (this.showAllAttributesInCart) {
					s += '<input id="cdsShowProductCartFormStdAttributes" type="hidden" name="stdattributes" value="'
					var firstAttribute = true;
					for (var i = 0; i < this.attributes.length; i++) {
						if (this.attributes[i].type != "attachment") {
							if (firstAttribute) {
								firstAttribute = false;
							} else {
								s += "|";
							}
							s += encodeURIComponent(this.attributes[i].label) + ":" + encodeURIComponent(this.attributes[i].value);
						}
					}
					s += '" />';
				}
				s += '</form>';
				td.innerHTML = s;
			}
		}

		// position image and controls
		var e = document.getElementById(this.controlsElementId);
		var table = document.createElement("table");
		e.appendChild(table);
		table.className = "cdsShowProductControlsTable";
		tbody = document.createElement("tbody");
		table.appendChild(tbody);

		if (this.image == null) {
			tr = document.createElement("tr");
			tbody.appendChild(tr);
			td = document.createElement("td");
			tr.appendChild(td);
			td.appendChild(controls);
		} else {
			if (this.imagePosition == "top") {
				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductImageCell";
				td.appendChild(this.image);

				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductControlsCell";
				td.appendChild(controls);
			} else 	if (this.imagePosition == "bottom") {
				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductControlsCell";
				td.appendChild(controls);

				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductImageCell";
				td.appendChild(this.image);
			} else 	if (this.imagePosition == "right") {
				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductControlsCell";
				td.appendChild(controls);

				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductImageCell";
				td.appendChild(this.image);
			} else {
				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductImageCell";
				td.appendChild(this.image);

				td = document.createElement("td");
				tr.appendChild(td);
				td.className = "cdsShowProductControlsCell";
				td.appendChild(controls);
			}
		}

        // get precision for all columns
        for (var i = 0; i < this.attributes.length; i++) {
            if (this.attributes[i].type === 'decimal' || this.attributes[i].type === 'fraction') {
                var precision = 0;
                var pos = this.attributes[i].value.indexOf('.');
                if (pos != -1) {
                    precision = this.attributes[i].value.toString().length - pos - 1;
                }
                this.precisionMap[i] = precision;
            }
        }

        // measurement system toggle
        var hasMeasurementSystemToggle = false;
        for (var i = 0; i < this.attributes.length; i++) {
            if (this.attributes[i].unitMetric && this.attributes[i].unitEnglish) {
                hasMeasurementSystemToggle = true;
                break;
            }
        }
        if (hasMeasurementSystemToggle) {
            var e = document.getElementById(this.attributesElementId);
            var div = document.createElement("div");
            div.className = "cdsShowProductControlUnitContainer";
            e.appendChild(div);
            this.numberFormatter.renderMeasurementSystemToggle(div);
        }

		// show tables

		// create rows into an array for later sorting
		// NOTE: this is a bit of a hack to mix dynamic and standard attribute display orders
		//       save original order in attlabels for domains without special order
		var dattrows = new Array();
        var attrows = new Array();
		var attlabels = new Array();

        var count = 0;

		// if we have CAD attributes, display them first
		if (this.cadAttributes != null && this.cadAttributes.length > 0) {
			for (var i = 0; i < this.cadAttributes.length; i++) {
				tr = document.createElement("tr");

				// save our rows so we can sort them later
				attlabels[attlabels.length] = this.cadAttributes[i].label.trim();

                // save them to seperate array if we're going to separate them
                if (this.seperateDynamicAttributes) {
                    dattrows[dattrows.length] = tr;
                } else {
                    attrows[attrows.length] = tr;
                }

				tr.className = (count++ % 2 == 0) ? "cdsShowProductTableEvenRow" : "cdsShowProductTableOddRow";

				// string attributes
				if (this.cadAttributes[i].type.toUpperCase() == "STRING") {
					var td = document.createElement("td");
					tr.appendChild(td);
					td.appendChild(document.createTextNode(this.cadAttributes[i].label));
                    td.setAttribute("id", "dvl_" + this.cadAttributes[i].parameter);
					td = document.createElement("td");
					tr.appendChild(td);
                    td.setAttribute("id", "dvv_" + this.cadAttributes[i].parameter);
					var vals = this.cadAttributes[i].values.split(",");
					var dflt = this.cadAttributes[i]["default"].replace(/^\s+|\s+$/g, '');
					if (vals != null && vals.length > 0 && vals[0].length > 0) {
						var sel = document.createElement("select");
						sel.setAttribute("id", "cdsShowProductCADAttribute" + i);
						td.appendChild(sel);
						for (var j = 0; j < vals.length; j++) {
							var v = vals[j].replace(/^\s+|\s+$/g, '');
							var opt = document.createElement("option");
							opt.setAttribute("value", v);
							if (dflt == v) opt.setAttribute("selected", "selected");
							opt.appendChild(document.createTextNode(v));
							sel.appendChild(opt);
						}
						sel.attributeLabel = this.cadAttributes[i].label;
                        sel.onchange = function() { widgets.cdsProductDetails.setCustomPNandPrice(); };
						if (this.cadAttributeElements == null) this.cadAttributeElements = new Array();
						this.cadAttributeElements[this.cadAttributeElements.length] = sel;
					} else {
						var inp = document.createElement("input");
						inp.setAttribute("type", "text");
						inp.setAttribute("id", "cdsShowProductCADAttribute" + i);
						inp.setAttribute("size", "10");
						inp.value = (this.cadAttributes[i]["default"] != null && this.cadAttributes[i]["default"] != "null") ? this.cadAttributes[i]["default"] : "";
						inp.onfocus = function() { this.select(); };
						inp.idx = i;
                        inp.onblur = function() { widgets.cdsProductDetails.setCustomPNandPrice(); widgets.cdsCADService.doOnBlurAttribute(this.idx); };
						td.appendChild(inp);
						btn = document.createElement("input");
						btn.setAttribute("type", "button");
						btn.setAttribute("value", "Set");
						td.appendChild(btn);
						inp.attributeLabel = this.cadAttributes[i].label;
						if (this.cadAttributeElements == null) this.cadAttributeElements = new Array();
						this.cadAttributeElements[this.cadAttributeElements.length] = inp;
					}

				// set attributes
				} else if (this.cadAttributes[i].type.toUpperCase() == "SET") {
					var td = document.createElement("td");
					tr.appendChild(td);
					td.appendChild(document.createTextNode(this.cadAttributes[i].label));
                    td.setAttribute("id", "dvl_" + this.cadAttributes[i].parameter);
					td = document.createElement("td");
					tr.appendChild(td);
                    td.setAttribute("id", "dvv_" + this.cadAttributes[i].parameter);
					var vals = this.cadAttributes[i].values.split(",");
					var dflt = this.cadAttributes[i]["default"].replace(/^\s+|\s+$/g, '');
					for (var j = 0; j < vals.length; j++) {
						var inp = document.createElement("input");
						inp.setAttribute("type", "checkbox");
						inp.setAttribute("name", "cdsShowProductCADAttribute" + i);
						inp.setAttribute("id", "cdsShowProductCADAttribute" + i + "_" + j);
						inp.setAttribute("value", "cdsShowProductCADAttribute" + i + "_" + j);
                        inp.onchange = function() { widgets.cdsProductDetails.setCustomPNandPrice(); };
						td.appendChild(inp);
						td.appendChild(document.createTextNode(vals[j]));
						td.appendChild(document.createElement("br"));
						inp.valueLabel = vals[j];
						inp.attributeLabel = this.cadAttributes[i].label;
						if (this.cadAttributeElements == null) this.cadAttributeElements = new Array();
						this.cadAttributeElements[this.cadAttributeElements.length] = inp;
					}

				// numeric attributes
				} else {
					var td = document.createElement("td");
					tr.appendChild(td);
                    td.setAttribute("id", "dvl_" + this.cadAttributes[i].parameter);
					var vals = this.cadAttributes[i].values.split(",");
					var s = this.cadAttributes[i].label + " (" + vals[0] + " to " + vals[1] + ")";
					td.appendChild(document.createTextNode(s));
					td = document.createElement("td");
					tr.appendChild(td);
                    td.setAttribute("id", "dvv_" + this.cadAttributes[i].parameter);
					var inp = document.createElement("input");
					inp.setAttribute("type", "text");
					inp.setAttribute("id", "cdsShowProductCADAttribute" + i);
					inp.setAttribute("size", "10");

					// I would love for someone to explain to me why the commented
					// out line below doesn't work in IE7 but the line below it does.
					// inp.setAttribute("value", this.cadAttributes[i].default);
					inp.value = this.cadAttributes[i]["default"];

					inp.onfocus = function() { this.select(); };
					inp.idx = i;
                    inp.onblur = function() { widgets.cdsProductDetails.setCustomPNandPrice(); widgets.cdsCADService.doOnBlurAttribute(this.idx); };
					td.appendChild(inp);
					btn = document.createElement("input");
					btn.setAttribute("type", "button");
					btn.setAttribute("value", "Set");
					td.appendChild(btn);
					inp.attributeLabel = this.cadAttributes[i].label;
					if (this.cadAttributeElements == null) this.cadAttributeElements = new Array();
					this.cadAttributeElements[this.cadAttributeElements.length] = inp;
				}
			}
		}

        // reset count if we're seperating the attributes
        if (this.seperateDynamicAttributes) {
            count = 0;
        }

        // standard attributes
		for (var i = 0; i < this.attributes.length; i++) {
            if (this.attributes[i].type != "attachment" && this.attributes[i].id !== this.thumbnailColumn) {
				tr = document.createElement("tr");

				// save our rows so we can sort them later
				attlabels[attlabels.length] = this.attributes[i].label.trim();
				attrows[attrows.length] = tr;

				tr.className = (count++ % 2 == 0) ? "cdsShowProductTableEvenRow" : "cdsShowProductTableOddRow";
				var td = document.createElement("td");
                td.setAttribute("id", "avl_" + this.attributes[i].id);
				tr.appendChild(td);
				var s = this.attributes[i].label;
                var du = this.numberFormatter.getDisplayUnit(this.attributes[i].unit, this.attributes[i].unitMetric, this.attributes[i].unitEnglish);
				if (du) s += " (" + du + ")";
				td.appendChild(document.createTextNode(s));
				td = document.createElement("td");
                td.setAttribute("id", "avv_" + this.attributes[i].id);
				tr.appendChild(td);
                var v = this.attributes[i].value;
                if (this.attributes[i].type === "decimal" || this.attributes[i].type === "fraction") {
                    v = this.numberFormatter.formatForDisplay(v, this.precisionMap[i], this.attributes[i].unit,
                            this.attributes[i].unitMetric, this.attributes[i].unitEnglish,
                            (this.attributes[i].type === "fraction"));
                } else {
                    v = this.numberFormatter.formatForDisplay(v, null, null, null, null, false);
                }
                td.innerHTML = v;
			}
		}

        // display attribute tables
        var e = document.getElementById(this.attributesElementId);
        var table = document.createElement("table");
        e.appendChild(table);
        table.className = "cdsShowProductAttributeOuterTable";
        var outtbody = document.createElement("tbody");
        table.appendChild(outtbody);
        var outtr = document.createElement("tr");
        outtbody.appendChild(outtr);

        // if we have seperate tables, create them
        if (this.seperateDynamicAttributes) {
            // render dynamic attribute table
            var maptd = document.createElement("td");
            outtr.appendChild(maptd);
            maptd.className = "cdsShowProductAttributeCell";
            table = document.createElement("table");
            maptd.appendChild(table);
            table.className = "cdsShowProductAttributeTable configurable";
            tbody = document.createElement("tbody");
            table.appendChild(tbody);
            var tr = document.createElement("tr");
            tbody.appendChild(tr);
            tr.className = "cdsShowProductTableHeadRow";
            var td = document.createElement("td");
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Configurable Attributes"));
            td.colSpan = "2";
            for (var i = 0; i < dattrows.length; i++) {
                tbody.appendChild(dattrows[i]);
            }

            // render standard attribute table
            var outtr2 = document.createElement("tr");
            outtbody.appendChild(outtr2);
            maptd = document.createElement("td");
            outtr2.appendChild(maptd);
            maptd.className = "cdsShowProductAttributeCell";
            table = document.createElement("table");
            maptd.appendChild(table);
            table.className = "cdsShowProductAttributeTable";
            tbody = document.createElement("tbody");
            table.appendChild(tbody);
            var tr = document.createElement("tr");
            tbody.appendChild(tr);
            tr.className = "cdsShowProductTableHeadRow";
            var td = document.createElement("td");
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Attributes"));
            var td = document.createElement("td");
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Values"));
            for (var i = 0; i < attrows.length; i++) {
                tbody.appendChild(attrows[i]);
            }

        // if not seperate, render attribute tables
        } else {
            var maptd = document.createElement("td");
            outtr.appendChild(maptd);
            maptd.className = "cdsShowProductAttributeCell";
            table = document.createElement("table");
            maptd.appendChild(table);
            table.className = "cdsShowProductAttributeTable";
            tbody = document.createElement("tbody");
            table.appendChild(tbody);
            var tr = document.createElement("tr");
            tbody.appendChild(tr);
            tr.className = "cdsShowProductTableHeadRow";
            var td = document.createElement("td");
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Attributes"));
            var td = document.createElement("td");
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Values"));

            // if we have a special order for this domain, sort them
            var attorder = attributeDisplayOrder[domain];
            if (attorder != null) {
                for (var i = 0; i < attorder.length; i++) {
                    for (var j = 0; j < attlabels.length; j++) {
                        if (attorder[i] == attlabels[j]) {
                            tbody.appendChild(attrows[j]);
                        }
                    }
                }
            // otherwise just list them
            } else {
                for (var i = 0; i < attrows.length; i++) {
                    tbody.appendChild(attrows[i]);
                }

            }
        }

		// check to see if we have any attachments
		var foundAttachment = false;
		for (var i = 0; i < this.attributes.length; i++) {
			if (this.attributes[i].type == "attachment") {
				foundAttachment = true;
				break;
			}
		}

		// show attachment table
		if (!this.printFriendly) {
			var linktd = document.createElement("td");
			outtr.appendChild(linktd);
			linktd.className = "cdsShowProductAttachmentCell";

            if (this.seperateDynamicAttributes) {
                linktd.setAttribute("rowspan", "2");
            }

			if (foundAttachment) {
				table = document.createElement("table");
				linktd.appendChild(table);
				table.className = "cdsShowProductAttachmentTable";
				tbody = document.createElement("tbody");
				table.appendChild(tbody);
				var tr = document.createElement("tr");
				tbody.appendChild(tr);
				tr.className = "cdsShowProductTableHeadRow";
				var td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(document.createTextNode("Attachments"));
				var div = document.createElement("div");
				td.appendChild(div);
				div.className = "cdsShowProductTableHeadInstructions";
				div.appendChild(document.createTextNode("To save an attachment, right click on a link and select \"Save Link As\" in Firefox or \"Save Target As\" in Internet Explorer."));

				count = 0;
				var count = 0;
				for (var i = 0; i < this.attributes.length; i++) {
					if (this.attributes[i].type == "attachment") {
						tr = document.createElement("tr");
						tbody.appendChild(tr);
						tr.className = (count++ % 2 == 0) ? "cdsShowProductTableEvenRow" : "cdsShowProductTableOddRow";
						var td = document.createElement("td");
						tr.appendChild(td);
						var a = document.createElement("a");
						a.setAttribute("href", fixUrl(this.attributes[i].value));
						if (this.openAttachmentTab) {
                            a.setAttribute("target", "cdsCatalogAttachment");
                        }
						a.appendChild(document.createTextNode(this.attributes[i].label));
                        if (this.addTopSpotLinks && typeof pageTracker != "undefined") {
                            a.onclick = function() {
                                pageTracker._link(this.href);
                                return false;
                            };
                        }
						td.appendChild(a);
					}
				}
			}
		}

        // update pn and price with custom values
        this.setCustomPNandPrice();

	}
}




