/*
*************************************************************************************
Cart GUI functions.. 
*************************************************************************************
*/

var tempX = 0;
var tempY = 0;

var IE = document.all ? true : false
var classArg = IE ? 'className' : 'class';

function BuildJSCart(JScart, tablePercentWidth) {
    try {
        if (JScart.length > 0) {
            //create JSON Table container
            var CartDiv = document.getElementById(JScart);
            if (!document.getElementById(JSON_TABLE)) {
                var CartTable = document.createElement("table");
                CartTable.setAttribute('id', JSON_TABLE);
                CartTable.setAttribute('width', tablePercentWidth + '%');
                //CartTable.setAttribute(classArg, 'TableWithBorder');
                CartTable.setAttribute('border', '0');
                CartTable.setAttribute('cellPadding', '0');
                CartTable.setAttribute('cellSpacing', '0');
                if (IE) {
                    TablecellTBody = document.createElement('TBODY');
                    CartTable.appendChild(TablecellTBody);
                }
            }
            else {
                CartTable = document.getElementById(JSON_TABLE);
            }


            //parse the JSON structure and form the array	
            for (i = 0; i <= oCart.Items.length - 1; i++) {
                var strError = '';

                var itemObj = oCart.Items[i];
                var itemErrorObj = itemObj.Error;

                var strdescription = '';
                var strMaterial = '';
                var strprices = '';
                var x;
                var otime0 = 0;
                var otime1 = 0;
                var modot = '';
                var modprice;
                var qty = itemObj.Quantity;
                var baseprice = itemObj.Price;

                if (IE) {
                    //this check bellow should be deleted once a Modifiers[] empty collection is added from VLCartMgr
                    if (oCart.Items[i].Modifiers) {
                        for (x = 0; x < oCart.Items[i].Modifiers.length; x++) {
                            modprice = oCart.Items[i].Modifiers[x].Price;
                            //Check One time
                            if (oCart.Items[i].Modifiers[x].OneTime) {
                                //sum price//get modifier one time state//concat price								
                                otime1 = otime1 + modprice;
                                modot = oCart.Items[i].Modifiers[x].OneTime;
                                strprices = strprices + ' onetime=' + modot + ' ->>' + modprice + ",";
                                modPriceDescription = modprice != 0 ? ' $' + modprice.toFixed(2) + ' x 1' : '';
                                //concat description
                                if (!isSingularModType(oCart.Items[i].Modifiers[x].ID))
                                    strdescription = strdescription + oCart.Items[i].Modifiers[x].Name + modPriceDescription + ","
                                else
                                    strMaterial = oCart.Items[i].Modifiers[x].Name;
                            }
                            else {
                                //sum price//get modifier one time state//concat price
                                otime0 = otime0 + modprice;
                                modot = oCart.Items[i].Modifiers[x].OneTime;
                                strprices = strprices + ' onetime=' + modot + ' ->>' + modprice + ",";
                                modPriceDescription = modprice != 0 ? ' $' + modprice.toFixed(2) : '';
                                //concat description
                                if (!isSingularModType(oCart.Items[i].Modifiers[x].ID))
                                    strdescription = strdescription + oCart.Items[i].Modifiers[x].Name + modPriceDescription + ","
                                else
                                    strMaterial = oCart.Items[i].Modifiers[x].Name;

                            }
                        }
                    }
                }
                else {
                    for (x = 0; x < oCart.Items[i].Modifiers.length; x++) {
                        //avoid remove function included in collection prototype.. 
                        if (x != "remove") {
                            //Check One time							
                            modprice = oCart.Items[i].Modifiers[x].Price;
                            if (oCart.Items[i].Modifiers[x].OneTime) {
                                //sum price//get modifier one time state//concat price								
                                otime1 = otime1 + modprice;
                                modot = oCart.Items[i].Modifiers[x].OneTime;
                                strprices = strprices + ' onetime=' + modot + ' ->>' + oCart.Items[i].Modifiers[x].Price + ",";
                                modPriceDescription = modprice != 0 ? ' $' + modprice.toFixed(2) + ' x 1' : '';
                                //concat description
                                if (!isSingularModType(oCart.Items[i].Modifiers[x].ID))
                                    strdescription = strdescription + oCart.Items[i].Modifiers[x].Name + modPriceDescription + ","
                                else
                                    strMaterial = oCart.Items[i].Modifiers[x].Name;
                            }
                            else {
                                //sum price//get modifier one time state//concat price								
                                otime0 = otime0 + modprice;
                                modot = oCart.Items[i].Modifiers[x].OneTime;
                                strprices = strprices + ' onetime=' + modot + ' ->>' + oCart.Items[i].Modifiers[x].Price + ",";
                                modPriceDescription = modprice != 0 ? ' $' + modprice.toFixed(2) : '';
                                //concat description
                                if (!isSingularModType(oCart.Items[i].Modifiers[x].ID))
                                    strdescription = strdescription + oCart.Items[i].Modifiers[x].Name + modPriceDescription + ","
                                else
                                    strMaterial = oCart.Items[i].Modifiers[x].Name;
                            }
                        }
                    }
                }
                //formulas
                var basemodprice = baseprice + otime0;
                var totalitem = otime1 + (basemodprice * qty);

                // cart validation
                var bitwise = 0;
                var newQty;
                var newPrice;
                var newOTPrice;
                var newCandidateQty;

                if (itemErrorObj) {
                    var validItem = itemErrorObj.validItem;

                    bitwise = itemErrorObj.bitWise;
                    newOTPrice = 0;

                    if (validItem) {
                        newQty = validItem.qty;
                        newPrice = validItem.basePrice;
                        newCandidateQty = validItem.candidateQty;
                        var q = 0;

                        for (q in validItem.modifiers) {
                            if (validItem.modifiers[q].oneTime) {
                                newOTPrice += validItem.modifiers[q].priceOffset;
                            }
                            else {
                                newPrice += validItem.modifiers[q].priceOffset;
                            }
                        }
                    }
                }

                var newQtyText = newQty == -1 ? "" : ". Quantity should be adjusted to " + newQty + "<br><br>";
                var newQtyStockText = newQty == -1 ? "" : ". Quantity should be adjusted, at most, to " + newQty + " (the maximum available).<br><br>";


                var extMsg = "";
                var err = new Array();

                if (bitwise & BW_ERR_INACTIVE)
                    err.push("* Product is Unavailable.");

                if (bitwise & BW_ERR_NOTPURCHASABLE)
                    err.push("* Product cannot be purchased at this time.");

                if (bitwise & BW_ERR_PRICE_CHANGED)
                    err.push("* Price has changed from " + formatCurrency(basemodprice + otime1) + " to " + formatCurrency(newPrice + newOTPrice) + ".");

                if (bitwise & BW_ERR_STOCK_CHANGED)
                    err.push("* There are not enough items in stock to meet your request.");

                if (bitwise & BW_ERR_INCQTY)
                    err.push("* The quantity level does not satisfy the specified incremental amount of " + oCart.Items[i].IncAmt + ".");

                if (bitwise & BW_ERR_SKU_MIN) {
                    err.push('* The quantity level for this SKU(' + oCart.Items[i].ItemCode + ') is lower than the minimum specified amount of ' + oCart.Items[i].Config.MinQuantity);
                }
                if (bitwise & BW_ERR_SKU_MAX) {
                    err.push('* The quantity level for this SKU(' + oCart.Items[i].ItemCode + ') is greater than the maximum specified amount of ' + oCart.Items[i].Config.MaxQuantity);
                }
                if (bitwise & BW_ERR_PARTNO_MIN) {
                    err.push('* The quantity level for this PartNo(' + oCart.Items[i].ItemCode + ') is lower than the minimum specified amount of ' + oCart.Items[i].Config.MinQuantity);
                }
                if (bitwise & BW_ERR_PARTNO_MAX) {
                    err.push('* The quantity level for this PartNo(' + oCart.Items[i].ItemCode + ') is greater than the maximum specified amount of ' + oCart.Items[i].Config.MaxQuantity);
                }

                if (err.length > 0) {
                    strError = err.join('<br><br>');
                    strError += ((isQtyRelated(bitwise)) && ((oCart.Items[i].Error.bitWise
					    & (BW_ERR_INACTIVE + BW_ERR_NOTPURCHASABLE)) == 0)) ? newQtyText : "";
                }

                //remove last comma
                strdescription = strdescription.slice(0, strdescription.length - 1);
                strprices = strprices.slice(0, strprices.length - 1);
                //add cart line
                AddJSCartLine(CartTable, oCart.Items[i], i, strdescription, strprices, basemodprice, totalitem, strError, strMaterial);
                strMaterial = '';
            }
            if (cartFirstDisplay) {
                CartDiv.appendChild(CartTable);
                cartFirstDisplay = false;
            }
            addTableFooter(CartTable);
            consolidateCart();
            AdjustGUI();

        } else {
            throw ("NoCartExc");
        }
    } catch (er) {
    }
}


function addTableFooter(oTable) {
    var tempTable;
    var oGeneralRow, oRow, oCell, oGeneralCell;
    var oTBody;
    var xdiv, oText;

    //Add separator...	
    oGeneralRow = document.createElement('TR');
    //oGeneralRow.setAttribute(classArg, 'Secondary');
    oGeneralCell = document.createElement('TD');
    oGeneralCell.colSpan = 9;

    tempTable = document.createElement('TABLE');
    tempTable.setAttribute('width', '100%');
    tempTable.setAttribute('height', '12');
    tempTable.setAttribute('border', '0');
    tempTable.setAttribute('cellspacing', '0');
    tempTable.setAttribute('cellpadding', '0');

    if (IE) {
        oTBody = document.createElement('TBODY');
        tempTable.appendChild(oTBody);
    }

    oRow = document.createElement('TR');

    oCell = document.createElement('TD');
    oCell.setAttribute('width', '100%');
    //oCell.setAttribute(classArg, 'SecondaryBoldText');
    oRow.appendChild(oCell);

    if (IE) {
        tempTable.tBodies[0].appendChild(oRow);
    }
    else {
        tempTable.appendChild(oRow);
    }

    oGeneralCell.appendChild(tempTable);
    oGeneralRow.appendChild(oGeneralCell);

    if (IE) {
        oTable.tBodies[0].appendChild(oGeneralRow);
    }
    else {
        oTable.appendChild(oGeneralRow);
    }


    //Add Subtotal...

    oGeneralRow = document.createElement('TR');
    oGeneralRow.setAttribute('height', '30');



    // Begin Subtotal Cell
    oGeneralCell = document.createElement('TD');
    oGeneralCell.setAttribute('align', 'right');
    oGeneralCell.colSpan = 8;

    tempTable = document.createElement('TABLE');
    tempTable.setAttribute('height', '30');
    tempTable.setAttribute('border', '0');
    tempTable.setAttribute('cellspacing', '0');
    tempTable.setAttribute('cellpadding', '0');

    if (IE) {
        oTBody = document.createElement('TBODY');
        tempTable.appendChild(oTBody);
    }

    oRow = document.createElement('TR');

    oCell = document.createElement('TD');
    oCell.setAttribute(classArg, 'OrangeBold');
    //oCell.setAttribute('style','font-weight:bold');
    oCell.setAttribute('width', '70');
    oCell.setAttribute('align', 'left');
    oText = document.createTextNode('Subtotal:');
    oBold = document.createElement('b');
    oBold.appendChild(oText);
    oCell.appendChild(oBold);
    oRow.appendChild(oCell);

    oCell = document.createElement('TD');
    oCell.setAttribute(classArg, 'OrangeBold2');
    oCell.setAttribute('width', '85');

    divx = document.createElement('DIV');
    divx.setAttribute('id', 'subTotal');
    divx.setAttribute('Style', 'margin-right:10px; font-weight:bold');

    oBold = document.createElement('b');
    oBold.appendChild(divx);
    oCell.appendChild(oBold);
    oRow.appendChild(oCell);

    if (IE) {
        tempTable.tBodies[0].appendChild(oRow);
    }
    else {
        tempTable.appendChild(oRow);
    }

    oGeneralCell.appendChild(tempTable);
    oGeneralRow.appendChild(oGeneralCell);

    if (IE) {
        oTable.tBodies[0].appendChild(oGeneralRow);
    }
    else {
        oTable.appendChild(oGeneralRow);
    }
    // End Subtotal

    // Begin Update Button
    //oGeneralCell = document.createElement('TD');
    //oGeneralCell.setAttribute('align', 'left');
    //oGeneralCell.colSpan = 2;
    //oGeneralRow.appendChild(oGeneralCell);

    oGeneralCell = document.createElement('TD');
    oGeneralCell.setAttribute('align', 'left');
    oGeneralCell.setAttribute(classArg, 'updateCell');
    var updateBtn = document.createElement('input');

    updateBtn.setAttribute('id', 'QtyUpdBtn');
    updateBtn.setAttribute('value', 'Update');
    updateBtn.setAttribute('type', 'button');
    updateBtn.style.fontSize = CSSRule['FrmBtnFontSize'];
    updateBtn.onclick = updateCartQty;
    updateBtn.disabled = true;

    if (oCart.Items.length == 0)
        updateBtn.style.visibility = 'hidden';

    oGeneralCell.appendChild(updateBtn);
    oGeneralRow.appendChild(oGeneralCell);
    // End Update Button
}


function getCartSubTotal() {
    var subTotal = 0;
    for (i = 0; i < oCart.Items.length; i++) {
        //div = document.getElementById('subTotal'+ oCart.Items[i].ItemCode);
        div = document.getElementById('subTotal' + i);
        subTotal += parseFloat((div.innerHTML.replace(/,/g, '')).slice(1));
    }
    return subTotal.toFixed(2);
}


function consolidateCart() {
    //subtotal was changed so clear up applied discounts and alert
    var cartSubTotal = getCartSubTotal();
    /*var appliedDiscounts = getSessionDiscountsString();
    appliedDiscounts = appliedDiscounts.split(String.fromCharCode(30));    

    //if cart was already rendered
    if (appliedDiscounts[2].length > 0)
    {   //if last subtotal is different from the current one
    if (parseFloat(appliedDiscounts[2]) != parseFloat(cartSubTotal))
    {   //if discounts were already commited
    if (appliedDiscounts[1].length > 0)
    {
    alert('All previously applied discounts will be removed due to changes to your cart. Please re-enter you code during checkout.');
    }
    clearDiscounts();
    }
    }*/

    document.getElementById("subTotal").innerHTML = formatCurrency(cartSubTotal);
}


function AddJSCartLine(oTable, item, Cindex, strModif, strprices, basemodprice, totalitem, strError, strMaterial) {
    //var oTable = document.getElementById(tableID);
    var builtRow, oRow;

    builtRow = BuildJSONCartItem(item, Cindex, strModif, strprices, basemodprice, totalitem, strError, strMaterial);

    if (IE) {
        oTable.tBodies[0].appendChild(builtRow);
    }
    else {
        oTable.appendChild(builtRow);
    }

    oRow = document.createElement('TR');
    oRow.setAttribute('height', '1px');
    //oRow.setAttribute(classArg, 'Secondary');

    oCell = document.createElement('TD');
    oCell.colSpan = 9;

    oRow.appendChild(oCell);

    if (IE) {
        oTable.tBodies[0].appendChild(oRow);
    }
    else {
        oTable.appendChild(oRow);
    }

}


function BuildJSONCartItem(item, Cindex, strModif, strprices, basemodprice, totalitem, strError, strMaterial) {
    var mainDiv, oRow, oCel, oTBody;
    var tmpPrice, divx, boton, texto, image, Trcell, Tdcell;
    var alterCartQty;

    switch (alterItemQty) {
        case C_eShopCnfgNo:
            alterCartQty = false;
            break;
        case C_eShopCnfgYes:
            alterCartQty = true;
            break;
        case C_eShopCnfgCheckProduct:
            alterCartQty = item.AlterQty;
            break;
    }

    oRow = document.createElement('TR');
    oRow.setAttribute('height', '50px');
    //oRow.setAttribute('id', 'row'+item.ItemCode);
    oRow.setAttribute('id', 'row' + Cindex);

    //set space
    oCell = document.createElement('TD');
    oCell.setAttribute('width', '10');

    if (strError != '') {
        image = document.createElement('IMG');
        image.setAttribute('src', '/vlImages/icons/cart_error.gif');
        image.setAttribute('border', '0');
        image.style.cursor = (ie) ? 'hand' : 'pointer';
        image.onclick = function() { showInfoBox(Cindex); }
        image.onerror = function() { this.src = '/vlImages/icons/cart_error.gif'; }
        oCell.appendChild(image);

        Tablecell = document.createElement('TABLE');
        Tablecell.setAttribute('width', '300');
        //Tablecell.setAttribute(classArg, 'TableWithBorder');

        if (IE) {
            TablecellTBody = document.createElement('TBODY');
            Tablecell.appendChild(TablecellTBody);
        }

        for (p = 0; p < 3; p++) {
            content = "";
            switch (p) {
                case 0:
                    {
                        rHeight = '2';
                        hAlign = 'right';
                        content += "<a href='javascript:hideInfoBox(" + Cindex + ");'>X</a>";
                        break;
                    }
                case 1:
                    {
                        rHeight = '10';
                        content = strError;
                        hAlign = 'left';
                        break;
                    }
                case 2:
                    {
                        rHeight = '2';
                        //determine where to include modify and not...
                        var cantBeModified = (item.Error.bitWise & (BW_ERR_INACTIVE + BW_ERR_NOTPURCHASABLE)) != 0;
                        cantBeModified = cantBeModified || (isQtyRelated(item.Error.bitWise) && (item.Error.validItem.qty == -1));
                        var Cqty = getCandidateQty(item);
                        if (!cantBeModified) { content += "<a href='javascript:updtItem(" + Cindex + ");'>Modify</a>" + "&nbsp;&nbsp;&nbsp;"; }
                        content += "<a href='javascript:delItem(" + Cindex + ");'>Delete</a>";
                        hAlign = 'right';
                        break;
                    }
                    /*default: {rHeight = '2';
                    content = '';
                    break;
                    }*/
            }

            Trcell = document.createElement('TR');
            Trcell.setAttribute('height', rHeight);

            Tdcell = document.createElement('TD');
            Tdcell.setAttribute('width', '5%');
            Trcell.appendChild(Tdcell);

            Tdcell = document.createElement('TD');
            Tdcell.setAttribute('width', '90%');
            Tdcell.setAttribute('valign', 'top');
            Tdcell.setAttribute('align', hAlign);
            Tdcell.innerHTML = content;
            Trcell.appendChild(Tdcell);

            Tdcell = document.createElement('TD');
            Tdcell.setAttribute('width', '5%');
            Trcell.appendChild(Tdcell);

            if (IE) {
                Tablecell.tBodies[0].appendChild(Trcell);
            }
            else {
                Tablecell.appendChild(Trcell);
            }
        }

        divx = document.createElement('DIV');
        divx.setAttribute('id', 'infoBox' + Cindex);
	divx.className = 'infoBox';
        divx.setAttribute('style', 'display:none;opacity:0.00; -mozopacity:0.00; filter:alpha(opacity=0)');
        divx.appendChild(Tablecell);

        oCell.appendChild(divx);
    }
    oRow.appendChild(oCell);
    //Product Image Source
    if (CART_ELEMENTS & BW_CART_IMAGE) {
        //set image source
        oCell = document.createElement('TD');
        oCell.setAttribute(classArg, 'CartImage');
        //oCell.setAttribute('width', '80');
        oCell.setAttribute('align', 'center');
        image = document.createElement('IMG');
        var imagePath, itemId = "000000" + item.ID;
        if ((String(tmbPrefix).length > 0) && (String(crtPrefix).length > 0))
			item.Image = String(item.Image).replace('/' + crtPrefix, '/' + tmbPrefix);		
        imagePath = "/DSN/" + DSN + "/Commerce/" + item.Image;
        image.setAttribute('src', imagePath);
        image.setAttribute('alt', item.Name);
        image.setAttribute('title', item.Name);
        image.setAttribute('border', '0');
        image.setAttribute(classArg, 'COMCartProdIMG');
        image.onerror = function() { swapImages(this); }
        oCell.appendChild(image);
        oRow.appendChild(oCell);
    }
    //end Product Image Source

    //set item.Name, item.PartNo and item.Description
    oCell = document.createElement('TD');
    oCell.colSpan = 3;
    oCell.setAttribute(classArg, 'CartDetails cartItem');

    var Tablecell;
    Tablecell = document.createElement('TABLE');
    Tablecell.setAttribute('width', '100%');
    var TablecellTBody;

    if (IE) {
        TablecellTBody = document.createElement('TBODY');
        Tablecell.appendChild(TablecellTBody);
    }

    Trcell = document.createElement('TR');
    Tdcell = document.createElement('TD');

    var catString = item.CategoryID ? "-" + item.CategoryID : "";
    var productPageInfoPath = "/Prod-" + ((item.ProductPageID == 0) ? PRODUCT_PAGE_ID : item.ProductPageID) + "-" + oCart.ShopID.toString() + "-" + item.ID + catString + "/" + makeLinkSafe(item.Name) + ".htm";

    if (CART_ELEMENTS & BW_CART_NAME) {
        var aLink = document.createElement('A');
        aLink.setAttribute(classArg, 'COMCartProdName');

        if (CART_ELEMENTS & BW_CART_LINKPRODUCT) {
            aLink.setAttribute('title', "View product information for " + item.Name);
            aLink.setAttribute('href', productPageInfoPath);
        }
        //var aText = document.createTextNode(item.Name);
        //aLink.appendChild(aText);
        aLink.innerHTML = item.Name;
        Tdcell.appendChild(aLink);
    }

    texto = document.createElement('div');
    texto.setAttribute('id', 'stock' + Cindex);
    texto.style.color = CSSRule['ErrorColor'];
    texto.style.marginTop = '5px';
    texto.className = 'ReducedText';

    if ((CART_ELEMENTS & BW_CART_BACKORDER) && item.allowBackOrder && item.availableStock < item.Quantity) {
        var tmpInt = (item.availableStock < 0) ? 0 : item.availableStock;
        var tmpStr = tmpInt + ' in stock, ' + (item.Quantity - tmpInt) + ' on backorder'
        texto.innerHTML = tmpStr;
    } else {
        texto.style.display = 'none';
    }

    Tdcell.appendChild(texto);
    
    
    //create and add Description
    if (item.Description.length > 0 && (CART_ELEMENTS & BW_CART_DESCRIPTION)) {
        divx = document.createElement("DIV");
        divx.setAttribute(classArg, 'COMCartProdDesc');

        if (item.Description.length > 100)
            divx.innerHTML = item.Description.slice(0, 100) + " ... [<a href='" + productPageInfoPath + "'>more</a>]";
        else
            divx.innerHTML = item.Description;

        Tdcell.innerHTML += "<br>";
        Tdcell.appendChild(divx);
    }

    Trcell.appendChild(Tdcell);

    if (IE) {
        Tablecell.tBodies[0].appendChild(Trcell);
    }
    else {
        Tablecell.appendChild(Trcell);
    }
    // Begin Product Attributes
    if (trim(strModif) != "") {
        var arytmp = strModif.split(",");
        for (var i = 0; i < arytmp.length; i++) {
            Trcell = document.createElement('TR');
            Tdcell = document.createElement('TD');
            Tdcell.setAttribute('align', 'left');
            Tdcell.innerHTML = arytmp[i];
            Trcell.appendChild(Tdcell);

            if (IE) {
                Tablecell.tBodies[0].appendChild(Trcell);
            }
            else {
                Tablecell.appendChild(Trcell);
            }
        }
    }
    oCell.appendChild(Tablecell);
    // End Product Attributes


    if (CART_ELEMENTS & BW_CART_PARTNO) {
        var aContent = (item.ItemCode != "") ? item.ItemCode : item.PartNo;
        divx = document.createElement("DIV");
        divx.setAttribute(classArg, 'COMCartProdPartNo');
        divx.innerHTML = aContent;
        oCell.appendChild(divx);
    }

    oRow.appendChild(oCell);
    // End Part Number

    // Begin SKU Cell
    //oCell = document.createElement('TD');
    //oCell.setAttribute(classArg, 'CartDetails cartSku');
    //oCell.setAttribute('width', '100');
    //if (CART_ELEMENTS & BW_CART_PARTNO) {
    //    var aContent = (item.ItemCode != "") ? item.ItemCode : item.PartNo;
    //    divx = document.createElement("DIV");
    //    divx.setAttribute(classArg, 'COMCartProdPartNo');
    //    divx.innerHTML = aContent;
    //    oCell.appendChild(divx);
    //}
    oRow.appendChild(oCell);
    // End SKU Cell

    if (CART_ELEMENTS & BW_CART_ATTRIBUTES) {
        var TablecellTBody;
        // Begin Material Cell
        //oCell = document.createElement('TD');
        //oCell.setAttribute(classArg, 'CartDetails cartMaterial');
        //oCell.setAttribute('width', '110');
        //oCell.setAttribute('align', 'left');
        //oCell.innerHTML = strMaterial + '&nbsp;';
        //oRow.appendChild(oCell);
        // End Material Cell

        // Begin Price Cell
        oCell = document.createElement('TD');
        oCell.setAttribute(classArg, 'CartDetails cartPrice');
        //oCell.setAttribute('width', '69');
        oCell.setAttribute('align', 'left');
        oText = document.createTextNode(formatCurrency(item.Price));
        oCell.appendChild(oText);
        oRow.appendChild(oCell);
        // End Price Cell
    }

    //set text changeqty
    oCell = document.createElement('TD');
    oCell.setAttribute(classArg, 'CartDetails cartQty');
    //oCell.setAttribute('width', '80');
    oCell.setAttribute('align', 'left');
    if (item.LocationName.length > 0) {
        var loc = document.createElement('FONT');
        loc.setAttribute('color', 'red');
        loc.setAttribute('size', '2');
        //if (item.ItemCode.indexOf('SPST') == 0)
        //{		        
        loc.innerHTML = String(item.LocationName + '<br>');
        //}else{
        //   loc.innerHTML = String('HPI<br>');
        // }
        oCell.appendChild(loc);
    }
    texto = document.createElement('INPUT');
    texto.setAttribute('type', 'text');
    texto.setAttribute('value', item.Quantity);
    texto.setAttribute('id', 'qty' + Cindex);
    texto.setAttribute('maxlength', '7');
    texto.setAttribute('size', '2');
    texto.style.textAlign = 'center';
    //texto.onchange=function(){changeItemQty(Cindex);}
    texto.onkeypress = texto.onkeyup = function() {
        if (QtyTimeout['I' + Cindex] != null)
            clearTimeout(QtyTimeout['I' + Cindex])

        QtyTimeout['I' + Cindex] = setTimeout('changeItemQty(' + Cindex + ');', 500);
    }

    if (navigator.appName == 'Microsoft Internet Explorer') {
        texto.onkeypress = function() { if (noNumbers(event) == 13) { changeItemQty(Cindex); } }
    }

    if (!alterCartQty) {
        texto.readOnly = true;
        texto.style.border = 'none';
    }

    oCell.appendChild(texto);
    oRow.appendChild(oCell);
    //end set text changeqty

    // set total price
    oCell = document.createElement('TD');
    oCell.setAttribute(classArg, 'CartDetails cartSubtotal');
    //oCell.setAttribute('width', '95');
    oCell.setAttribute('align', 'left');
    //oCell.setAttribute('style', 'margin-right:10px');

    divx = document.createElement('DIV');
    divx.setAttribute('id', 'subTotal' + Cindex);

    oText = document.createTextNode(formatCurrency(totalitem));
    divx.appendChild(oText);

    oCell.appendChild(divx);
    oRow.appendChild(oCell);

    //set button delete
    oCell = document.createElement('TD');
    oCell.setAttribute(classArg, 'CartDetails cartSummary');
    //oCell.setAttribute('width', '85');
    oCell.setAttribute('align', 'left');
    boton = document.createElement('INPUT');
    boton.setAttribute('id', 'btn' + Cindex);
    boton.setAttribute('type', 'button');
    boton.setAttribute('value', 'Delete');
    boton.setAttribute(classArg, 'FormButtons');
    boton.onclick = function() { delItem(Cindex); };
    oCell.appendChild(boton);
    oRow.appendChild(oCell);
    //end set button delete

    // set last space
    //oCell = document.createElement('TD');
    //oCell.setAttribute('width', '1%');
    //oCell.setAttribute(classArg, 'CartDetails');
    //oRow.appendChild(oCell);

    return oRow;
}

function noNumbers(e) {
    var keynum;
    var keychar;
    var numcheck; if (window.event) // IE
    {
        keynum = event.keyCode;
    }
    return keynum;
}

function swapImages(anImage) {
    anImage.src = "/DSN/" + DSN + "/Commerce/ProductImages/Cart_NoImage.jpg";
    anImage.alt = "No image available";
    anImage.title = "No image available";
}


function updateJSONCart(anItem) {
    var i = 0, avail = 0, erBitwise;
    done = false;
    while (!done && i < oCart.Items.length) {
        done = (anItem.ItemCode == oCart.Items[i].ItemCode) && (anItem.ID == oCart.Items[i].ID) && (compareItemModifiers(anItem.Modifiers, oCart.Items[i].Modifiers));
        if (!done) { i++; }
    }
    if (done) {
	    //different error handling
	    erBitwise = oCart.Items[i].Error.bitWise;	    
	    if ((erBitwise & BW_ERR_SKU_MIN) || (erBitwise & BW_ERR_PARTNO_MIN))
	        avail = oCart.Items[i].Config.MinQuantity;
	    if (erBitwise & BW_ERR_STOCK_CHANGED)
	        avail = oCart.Items[i].availableStock;
        if ((erBitwise & BW_ERR_SKU_MAX) || (erBitwise & BW_ERR_PARTNO_MAX) || (erBitwise & BW_ERR_INCQTY))
	        avail = calculateItemUpdateQty(oCart.Items[i]);
        //proceed
        anItem.Quantity = parseInt(avail, 10);
        anItem.availableStock = oCart.Items[i].availableStock;
        anItem.allowBackOrder = oCart.Items[i].allowBackOrder;
        anItem.outStockMsg = oCart.Items[i].outStockMsg;
        anItem.inStockMsg = oCart.Items[i].inStockMsg;
        oCart.Items[i] = null;
        oCart.Items[i] = anItem;
        reBuildCart();
    }
    hideLoadingBox(LOADING_DIV);
}

function compareItemModifiers(oModList, oModTargetList) {
    var totalMatches = 0;
    var retVal = false;
    if (oModList.length == oModTargetList.length) {
        for (i = 0; i <= oModList.length - 1; i++) {
            for (j = 0; j <= oModTargetList.length - 1; j++) {
                if (oModList[i].ID == oModTargetList[j].ID) {
                    totalMatches++;
                }
            }
        }
        if (totalMatches == oModList.length)
            retVal = true;
    }

    return retVal;
}

function reBuildCart() {
    var oTable = document.getElementById(JSON_TABLE);
    if (IE) {
        while (oTable.rows.length) {
            oTable.deleteRow(-1);
        }
    }
    else {
        while (oTable.childNodes.length) {
            oTable.removeChild(oTable.childNodes[length]);
        }
    }
    BuildJSCart(JSON_DIV, "100");
}


function clearJSONCart() {
    oCart.Items = [];
    reBuildCart();
    hideLoadingBox(LOADING_DIV);
}

function errorOut(msg) {
    document.getElementById(ERROR_DIV).style.display = "inline";
    document.getElementById(ERROR_DIV_CONTENT).innerHTML = msg;
}

function deleteJSONItem(anIndex) {
    var i = 0;
    /*done = false;	
    while ((i<oCart.Items.length) && (!done)){
    done = (oCart.Items[i].ItemCode == anItemCode);
    if (!done){i++;}		
    }
	
	if (done){oCart.Items.splice(i,1);}	*/
    oCart.Items.splice(anIndex, 1);
    reBuildCart();
    hideLoadingBox(LOADING_DIV);
}

function showInfoBox(id) {
    infoBox = GetTag("infoBox" + id);
    infoBox.style.position = "absolute";
    infoBox.style.zIndex = 10;
    infoBox.style.top = (tempY - 50) + "px";
    infoBox.style.left = (tempX + 10) + "px";
    changeOpac(0, "infoBox" + id);
    infoBox.style.display = "block";
    opacity("infoBox" + id, 0, 90, 200);
}

function hideInfoBox(id) {
    var currInfoBox = document.getElementById("infoBox" + id);
    if (currInfoBox) {
        currInfoBox.style.display = "none";
    }
}


function showLoadingBox(id)
{
	spinBox = document.getElementById(id);	
	spinBox.style.position = "absolute";	
	spinBox.style.zIndex = 10;			
	spinBox.style.top = document.body.scrollTop + 250 + "px";
	spinBox.style.left = 45 + "%";	
	changeOpac(0, id);
	spinBox.style.display = "block";
	opacity(id, 0, 95, 800); 	
}

function hideLoadingBox(id) {
    var spinBox = document.getElementById(id);
    if (spinBox) {
        spinBox.style.display = "none";
    }
}


function showBox(id) {
    spinBox = document.getElementById(id);
    spinBox.style.position = "absolute";
    spinBox.style.zIndex = 10;
    spinBox.style.top = (screen.height / 2) - 70 + "px";
    spinBox.style.left = (screen.width / 2) - 300 + "px";
    changeOpac(0, id);
    spinBox.style.display = "block";
    opacity(id, 0, 95, 200);
}

function hideBox(id) {
    var spinBox = document.getElementById(id);
    if (spinBox) {
        spinBox.style.display = "none";
    }
}


function getMouseXY(e) {
    if (IE) {
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
    } else {
        tempX = e.pageX
        tempY = e.pageY
    }
    if (tempX < 0) { tempX = 0 }
    if (tempY < 0) { tempY = 0 }
    return true
}

/*
function AdjustGUI(){
var errors = 0;
for (i=0; i <= oCart.Items.length - 1; i++){
itemCode = oCart.Items[i].ItemCode;
tempDiv = document.getElementById("infoBox"+itemCode);	
if (tempDiv){
targetBtn = eval('document.frmCart.btn'+itemCode);
targetTxt = eval('document.frmCart.qty'+itemCode);				
targetBtn.disabled = true;
targetTxt.disabled = true;
if (IE){
alert("hideInfoBox(itemCode)");
hideInfoBox(itemCode);
}
}
if (oCart.Items[i].Error){
errors += oCart.Items[i].Error.bitWise;	
}
}	
document.frmCart.btnSaveCart.disabled = (errors != 0);
}
*/


function AdjustGUI() {
    var errors = 0;
    for (i = 0; i <= oCart.Items.length - 1; i++) {
        //itemCode = oCart.Items[i].ItemCode;	
        if (oCart.Items[i].Error) {
            if (oCart.Items[i].Error.bitWise != 0) {
                targetBtn = eval('document.frmCart.btn' + i);
                targetTxt = eval('document.frmCart.qty' + i);
                targetBtn.disabled = true;
                targetTxt.disabled = true;
                if (IE) { hideInfoBox(i); }
            }
            errors += oCart.Items[i].Error.bitWise;
        }
    }
    //document.frmCart.btnSaveCart.disabled = ((errors != 0) || (oCart.Items.length == 0));
}



function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;
    var completionTime = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if (opacStart > opacEnd) {
        for (i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')", (timer * speed));
            timer++;
        }
    } else if (opacStart < opacEnd) {
        for (i = opacStart; i <= opacEnd; i++) {
            completionTime += (timer * speed);
            setTimeout("changeOpac(" + i + ",'" + id + "')", (timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


//coming from CommerceCartMaanage.asp
function getChecked() {
    var currentForm = document.frmCart;
    if (currentForm.Save.length) {
        for (I_cwb = 0; I_cwb < currentForm.Save.length; I_cwb++) {
            if (currentForm.Save[I_cwb].checked) {
                return currentForm.Save[I_cwb];
            }
        }
    }
    else {
        if (currentForm.Save) {
            return currentForm.Save;
        }
    }
    return null;
}

function validateSave() {
    var currentForm = document.frmCart;
    var selectedRadio = getChecked();
    if (selectedRadio) {
        switch (selectedRadio.value) {
            case "saved": concurrencyField = eval('document.frmCart.tempConcurrencyID' + document.frmCart.SelectCartID.value);
                currentForm.ActionCartConcurrencyID.value = concurrencyField.value;
                currentForm.ActionCartID.value = currentForm.SelectCartID.value;
                var sIndex = currentForm.SelectCartID.selectedIndex;
                currentForm.ActionCartLabel.value = currentForm.SelectCartID.options[sIndex].text;
                currentForm.ActionToDo.value = "SAVE";
                currentForm.submit();
                break;

            case "new": if (checkRequiredTextField(currentForm.cartName, "Cart Name")) {
                    //then check for name conflicts				
                    actionCartId = 0;
                    actionCartConcurrencyId = 0;
                    actionCartNewName = currentForm.cartName.value;
                    showLoadingBox(LOADING_DIV);
                    doAjax("/Commerce/CommerceManageCartAJAX.asp", "act=RENAMECART&cartID=0&NewName=" + urlEncode(actionCartNewName), "GET", saveCartHnd);
                }
                else {
                    return false;
                }
                break;
        }
    }
}

function cancelSave() {
    var currentForm = document.frmCart;
    currentForm.DisplayBlock.value = "LIST";
    currentForm.submit();
}

function cancelLoad(cartId) {
    hideBox("ask" + cartId.toString());
}

function discardCurrent(savedCartID, savedCartConcurrencyID) {
    //alert("cartID : " + savedCartID + "  &  concurrencyID : " + savedCartConcurrencyID );
    loadCart(savedCartID, savedCartConcurrencyID);
}

function saveCurrent(savedCartID) {
    var currentForm = document.frmCart;
    currentForm.ActionLoadThisCartFinally.value = savedCartID;
    currentForm.DisplayBlock.value = "SAVE";
    hideBox("ask" + savedCartID.toString());
    currentForm.submit();
}

function loadCart(cartId, concurrencyID) {
    var currentForm = document.frmCart;
    currentForm.CurrentCartID.value = cartId;
    currentForm.CurrentCartConcurrencyID.value = concurrencyID;
    currentForm.ActionCartID.value = cartId;
    currentForm.ActionCartConcurrencyID.value = concurrencyID;
    currentForm.ActionToDo.value = "LOAD";
    currentForm.DisplayBlock.value = "LIST";
    hideBox("ask" + cartId.toString());
    currentForm.submit();
}

function doSubmitCarts(cartId, action, concurrencyID) {
    if (action == "LOAD") {
        if (oCart.Items.length != 0) {
            //ask for choices...
            showBox("ask" + cartId.toString());
            return;
        }
        loadCart(cartId, concurrencyID);
        return;
    }

    var currentForm = document.frmCart;
    currentForm.ActionCartID.value = cartId;
    currentForm.ActionCartConcurrencyID.value = concurrencyID;
    currentForm.ActionToDo.value = "DELETE";
    currentForm.DisplayBlock.value = "LIST";
    currentForm.submit();
}

function SaveCart() {
    var currentForm = document.frmCart;
    //currentForm.ActionCartID.value = currentForm.CurrentCartID.value;
    //currentForm.ActionCartConcurrencyID.value = currentForm.CurrentCartConcurrencyID.value;
    if (oCart.Items.length == 0) {
        alert("There are no items in the cart");
        return false;
    }
    currentForm.DisplayBlock.value = "SAVE";
    currentForm.action = '';
    currentForm.submit();
}

function checkOut() {
    var errors = 0;
    var zero = false;
    for (i = 0; i <= oCart.Items.length - 1; i++) {
        if (oCart.Items[i].Error) {
            errors += oCart.Items[i].Error.bitWise;
            if (oCart.Items[i].Quantity == 0) {
                zero = true;
            }
        }
    }
    if (oCart.Items.length == 0) {
        alert("Your cart is empty.");
        return false;
    }
    if (errors != 0) {
        alert("Please fix the errors in the cart before checking out.");
        return false;
    }
    if (zero == true) {
        alert('Quantity must be greater than zero');
        return false;
    }
    if (validateClientSide() == false)
    {
        return false;
    }
    if (isCartDirty()) {
        var confirmed = confirm("You have changed the quantity of an item in your cart.\n\nClick OK to apply the change.");
        if (confirmed) {
            updateCartQty();
        }
        return false;
    }

    var currentForm = document.frmCart;
    //var subTotal = getCartSubTotal();
    //currentForm.action = '/Content/'+TRANSACTION_PAGE_ID.toString()+'.htm?Sub='+subTotal.toString();
    //currentForm.action = '/Content/'+TRANSACTION_PAGE_ID.toString()+'.htm';
    currentForm.ActionToDo.value = "CHECKOUT";
    currentForm.DisplayBlock.value = "LIST";
    currentForm.action = '';
    currentForm.submit();
}

function getCandidateQty(oItem) {
    var retQty = oItem.Quantity;
    if (typeof (oItem.Config) != 'undefined') {
        if (oItem.Quantity < oItem.Config.MinQuantity)
            retQty = oItem.Config.MinQuantity;
        if (oItem.Quantity > oItem.Config.MaxQuantity)
            retQty = oItem.Config.MaxQuantity;
    }
    return retQty;
}

function continueShopping() {
    var errors = 0;
    for (i = 0; i <= oCart.Items.length - 1; i++) {
        if (oCart.Items[i].Error) {
            errors += oCart.Items[i].Error.bitWise;
        }
    }

    if (errors != 0) {
        var confirmed = confirm("Are you sure you want to continue shopping before correcting the errors?");
        if (!confirmed) return false;
    }

    if (isCartDirty()) {
        confirmed = confirm("You have changed the quantity of an item in your cart, continue shopping anyway?\n\n(changes will not be saved)");
        if (!confirmed) return false;
    }
	var locURL = String(document.getElementById('StartCommercePageID').value)+'.htm';
	/*var currentForm = document.frmCart;
    currentForm.action = locURL;
	currentForm.submit();*/
	location.replace('../Content/' + locURL);

}
//this happens after page load.
/*
if (oCart.Items.length > 0 || COMMERCE_START_PAGE_ID > 0) {
    document.getElementById('COMConShopLink').href = "javascript:continueShopping();";
    document.getElementById('COMConShopIMG').src = "/DSN/" + DSN + "/Commerce/Icons/continueshopping.gif";
    document.getElementById('COMConShopSpan').style.display = "inline";
}

if (!IE) {
    document.captureEvents(Event.MOUSEMOVE)
}*/

document.onmousemove = getMouseXY;

