﻿var ViewCart = (function() {
    var tableCornered = false;
    var cartRowCount = 0;
    var pricingOverrideElem = null;
    var pricingOverrideRow = null;
    var _user = null;
    var _updatingLeadTimes = false;
    
    // information from crystal currently showing for this part number
    var crystalPart = '';

    var addCartBinds = function(selector) {
        var parent = (typeof(selector) == "String" ? $(selector) : selector);
        
        // bind the update quantity and pricing links
        $("a", parent).each(function(idx) {
            if (this.id == "viewCartUpdateQuantityLink") {
                $(this).click(function() {
                    updateQuantity(this);
                });
            }
            
            if (this.id == "viewCartUpdateUnitPriceLink") {
                $(this).click(function() {
                    capturePricingReason(this);
                });
            }

            if (this.id == "viewCartRemoveLink") {
                $(this).click(function() {
                    removeLine(this);
                });
            }
            
            if (this.id == "viewCartMoreInfoLink") {
                $(this).click(function() {
                    var that = $(this);
                    var showing = that.attr("moreInfoShowing");
                    
                    if (showing == "yes") {
                        that.parents("tr:first").next().hide();
                        that.attr("moreInfoShowing", "no");
                    } else {
                        that.parents("tr:first").next().show();
                        that.attr("moreInfoShowing", "yes");

                        if (that.attr("moreInfoPopulated") == "no") {
                            loadMoreInfo(this, "Part", false);
                            that.attr("moreInfoPopulated", "yes");
                        }
                    }
                });
            }

            if (this.id == "viewCartATPErrorLink") {
                $(this).click(function() {
                    var moreInfoLink = $(this).parents("tr[cartrow='3']").prev().find("#viewCartMoreInfoLink");
                    loadMoreInfo(moreInfoLink, "ATP", true);
                });
            }
        });
        
        if (!_user.internalUser) {
            $(".date-picker", parent).datePicker({"createButton":false, "showYearNavigation":false})
                .bind("dateSelected", function(event, date) {
                    updateShipDate(this, Ubiquitous.ConvertDatePickerDate(date));
                });
            $(".date-picker-link", parent).click(function() { 
                var dateDiv = $(this).parents("tr:first").prev().find("div.date-picker");
                var startDate = new Date(dateDiv.attr("expectedShipDate"));
                dateDiv.dpSetStartDate(startDate.asString());
                dateDiv.dpDisplay(); 
            });
        };
                        
        // bind the keydown in the quantity and price inputs
        $("input", parent).each(function(idx) {
            if (this.id == "viewCartUpdateQuantity") {
                $(this).keydown(function(e) {
                    if (e.which == "13") {
                        e.preventDefault();
                        updateQuantity(this);
                    }
                });
            }
            if (this.id == "viewCartUpdateUnitPrice") {
                $(this).keydown(function(e) {
                    if (e.which == "13") {
                        e.preventDefault();
                        capturePricingReason(this);
                    }
                });

                $(this).attr("href", "#columnBreakWrapper").attr("rel", "#columnBreakWrapper");
                var that = $(this);
                var onActivateFn = function(e) {
                    var topRow = that.parents("tr:first");
                    var moreInfoRow = topRow.next().next();
                    var moreInfoLink = moreInfoRow.prev().find("#viewCartMoreInfoLink");
                    if (moreInfoRow.attr("moreInfoPricingPopulated") == "yes") {
                        var colBreaks = moreInfoRow.find("#columnBreakTable").clone();
                        if (typeof(colBreaks[0]) == "undefined")
                            $("#columnBreakWrapper").html("No column break information.");
                        else
                            $("#columnBreakWrapper").html(colBreaks[0]);
                        $("#columnBreakWrapper").find("#columnBreakTable").css("display", "block");
                        $("#columnBreakWrapper").find("#columnBreakTable").css("width", "125px");
                    } else {
                        $("#columnBreakWrapper").html("Still populating.  Try again in a few seconds.");
                    }
                    return true;
                }
                $(this).cluetip({local : true, cluetipClass:'jtip', arrows:true, showTitle:false, onActivate:onActivateFn});
            }            
        });
    };

    var addQuickEntryLine = function(section, itemStatusChecked) {
        var partNumber = $.trim($("#" + section + "PartNumberInput").val());
        var quantity = $.trim($("#" + section + "QuantityInput").val());

        if (partNumber == "" || quantity == "")
            return;
            
        if (!itemStatusChecked) {
            // check item status
            var partNumber = $.trim($("#" + section + "PartNumberInput").val());
            JSC.ServerPost({'action':'checkItemStatus', 'partNumber':partNumber }, function(data) {
                if (data.length > 0) {
                    displayMessageWithClose(data, function() {
                        addQuickEntryLine(section, true);
                    });
                } else {
                    addQuickEntryLine(section, true);
                }
            }, ignoreError, null);
            
            return;
        }
        
        var postData = {};
        postData["action"] = "addNonCSItemToCart";
        postData["quickEntryPartNumber"] = encodeURIComponent($.trim($("#" + section + "PartNumberInput").val()));
        postData["quickEntryQuantity"] = $.trim($("#" + section + "QuantityInput").val());
        var addedPart = decodeURIComponent(postData["quickEntryPartNumber"]);

        if (section == "quickEntry") {
            displayMessage("Adding line ...");
        } else {
            var newTr = $(createEmptyCartRow(addedPart));
            addCartBinds(newTr);
            $("#viewCartTable").append(newTr);
            cartRowCount++;
        }            
        
        // clear and reset the form before sending the data to the server
        $("#" + section + "PartNumberInput").val("");
        $("#" + section + "QuantityInput").val("");
        
        JSC.ServerPost(postData, function(data, textStatus) {
            var result = JSC.ConvertServerDataToLocal(data);
    
            if (result.serverDataOk && !result.error && result.lines.length > 0) {
                // if we only have one line, then let's let the main update cart routine handle this
                if (result.lines.length == 1) {
                    updateCartSuccess(data, textStatus, null);
                } else {                
                    // after adding a row we just need to add it to the table
                    var addedLine = null;
                    for (var i = 0; i < result.lines.length; i++) {
                        if (result.lines[i].partNumber.toLowerCase() == addedPart.toLowerCase() || 
                                result.lines[i].customerPartNumber.toLowerCase() == addedPart.toLowerCase()) {
                            addedLine = result.lines[i];
                            break;
                        }
                    }
                    
                    // first, let's see if there's a row out there already
                    var rowFound = false;
                    $("#viewCartTable tr").each(function() {
                        var thisRow = $(this);
                        if (thisRow.attr("cartrow") == "1" && 
                            (thisRow.attr("partnumber").toLowerCase() == addedLine.partNumber.toLowerCase() || 
                                thisRow.attr("partnumber").toLowerCase() == addedLine.customerPartNumber.toLowerCase())) {

                            // first one we hit we fill in, next one we hit we get rid of
                            if (!rowFound) {
                                rowFound = true;
                                var nextRow = thisRow.next();

                                thisRow.attr("priceListId", result.priceListId);
                                thisRow.attr("partNumber", addedLine.partNumber);
                                thisRow.attr("productId", addedLine.productId);
                                thisRow.attr("lineId", addedLine.lineId);
                                thisRow.attr("originalQuantity", addedLine.quantity);
                                thisRow.attr("originalPrice", addedLine.unitPrice);
                                nextRow.attr("priceListId", result.priceListId);
                                nextRow.attr("partNumber", addedLine.partNumber);
                                nextRow.attr("productId", addedLine.productId);
                                nextRow.attr("lineId", addedLine.lineId);
                                nextRow.attr("originalQuantity", addedLine.quantity);
                                nextRow.attr("originalPrice", addedLine.unitPrice);
                                
                                if (addedLine.csProductUrl != "") {
                                    var html = "<a href='" + addedLine.csProductUrl + "'>" + addedLine.description + "</a>";
                                    thisRow.find("#viewCartLineDescription").html(html);
                                } else {
                                    thisRow.find("#viewCartLineDescription").text(addedLine.description);
                                }
                                
                                nextRow.find("#viewCartLinePartNumber").html(addedLine.partNumber +
                                    (addedLine.customerPartNumber == '' ? '' : ' (' + addedLine.customerPartNumber + ')') + 
                                    (addedLine.packageQuantity > 1 ? ('&nbsp;&nbsp; - Available in quantity multiples of ' + addedLine.packageQuantity + ' only.') : ''));
                                    
                                if (addedLine.leadTimeExpired)
                                    thisRow.find("#viewCartLineShipDate").text("Updating").attr("expectedShipDate", addedLine.expectedShipDate);
                                else
                                    thisRow.find("#viewCartLineShipDate").text(addedLine.customerRequestDate).attr("expectedShipDate", addedLine.expectedShipDate);
                                thisRow.find("#viewCartUpdateQuantity").val(addedLine.quantity);
                                if (_user.quotePricing) {
                                    thisRow.find("#viewCartUpdateUnitPrice").val(addedLine.unitPrice);
                                    if (addedLine.unitPrice != addedLine.customerPrice)
                                        thisRow.find("#viewCartUpdateUnitPrice").css({backgroundColor:'#FF5050', border:'solid 1px #A88863'});
                                    else
                                        thisRow.find("#viewCartUpdateUnitPrice").css({backgroundColor:'#FFF', border:'solid 1px #A88863'});
                                } else {
                                    thisRow.find("#viewCartViewUnitPrice").text(addedLine.unitPrice);
                                }
                                thisRow.find("#viewCartExtPrice").text(addedLine.extPrice);
                                nextRow.next().find("#moreInfoARO").text(addedLine.aroDays);
                                nextRow.next().find("#moreInfoListPrice").text(addedLine.listPrice);
                            } else {
                                // we already have it ...
                                thisRow.next().find("#viewCartRemoveLink").click();
                            }
                        }
                    });
                    
                    if (!rowFound) {
                        var newTr = $(createCartRow(result.lines[result.lines.length - 1], result.priceListId, (result.lines.length - 1)));
                        addCartBinds(newTr);
                        $("#viewCartTable").append(newTr);
                        cartRowCount++;
                    }

                    loadMoreInfoPricing();
                    updateCartSummary(result);
                    updateLeadTimes();
                    
                    JSCE.Fire("CartItemAdded", null, "ViewCart.addQuickEntryLine");
                }

                if (section == "quickEntry")
                    $("#viewCartPartNumberInput").focus();

                displayStatusMessage(result);
            }
            
            if (result.error) {
                displayMessage(result.errorMessage);
                displayMessage(2000);
                
                // find the offending part number and remove the row
                if (result.partNumber) {
                    $("#viewCartTable tr").each(function() {
                        var thisRow = $(this);
                        if (thisRow.attr("partnumber") == result.partNumber) {
                            thisRow.remove();
                        }
                    });
                }                    
            }
                
        }, ignoreError, null);
    };

    var capturePricingReason = function(updateElem) {
        // get a reference to the cart row that contains the update pricing input box
        var curRow = $(updateElem).parents("tr:first");
        if (curRow.attr("cartRow") == "2")
            curRow = curRow.prev();
            
        pricingOverrideRow = curRow;
        
        // unbind the action elements on the popup
        var form = $(pricingOverrideElem);
        form.find("#pricingOverrideSubmit").unbind();
        form.find("#pricingOverrideCancel").unbind();

        // rebind them        
        form.find("#pricingOverrideSubmit").click(function() {
            $.unblockUI({fadeOut:'0'});
            var wrapper = pricingOverrideRow.next().next().find("#moreInfoPricingOverrideReasonWrapper");
            wrapper.show();
            wrapper.find("#moreInfoPricingOverrideReason").text($(this).parent().find("#viewCartPricingReason").val());
            updatePrice();
        });
        
        form.find("#pricingOverrideCancel").click(function() {
            var origPrice = pricingOverrideRow.attr("originalPrice");
            pricingOverrideRow.find("#viewCartUpdateUnitPrice").val(origPrice);
            $.unblockUI({fadeOut:'0'});
        });

        var curPricingReason = pricingOverrideRow.next().next().find("#moreInfoPricingOverrideReason");
        if (curPricingReason.size() == 0)
            form.find("#viewCartPricingReason").val("");
        else
            form.find("#viewCartPricingReason").val(curPricingReason.text());

        $.blockUI(form[0], { width:'500px' });
    };
    
    var changePromoCode = function() {
        displayMessage("Updating promo code ...");
        
        var promoCode = $("#viewCartPromoCodeInput").val();
        
        var postData = {};
        postData["action"] = "setPromoCode";
        postData["promoCode"] = promoCode;
        JSC.ServerPost(postData,  function(data, textStatus) { 
            var result = JSC.ConvertServerDataToLocal(data);
            if (result.serverDataOk && !result.error) {
                if (result.statusMessage != '' && result.statusMessage != null) {
                    displayMessageWithClose(result.statusMessage);
                    $("#viewCartPromoCodeInput").val("");
                } else {
                    updateCartSummary(result);
                    displayMessage(false);
                }
            }
        }, ignoreError, null);
    };
    
    var changeZipCode = function() {
        displayMessage("Updating postal code ...");
        
        // get what they entered
        var zipCode = $("#viewCartZipInput").val();
        
        var postData = {};
        postData["action"] = "viewCartSetZip";
        postData["zipCode"] = zipCode;
        JSC.ServerPost(postData,  function(data, textStatus) { 
            var result = JSC.ConvertServerDataToLocal(data);
            if (result.serverDataOk && !result.error) {
                updateCartSummary(result);
            }
            displayMessage(false);
        }, ignoreError, null);
    };
    
    var clearCartBinds = function() {
        $("#viewCartBasketLines a").unbind("click");
        $("#viewCartBasketLines input").unbind("keydown");
        $("#viewCartBasketLines div").unbind("dateSelected");
    };

    var createCartRow = function(curLine, priceListId) {
        var priceCSS;
        // FIRST ROW
        var lineHtml = '<tr valign="top" partNumber="' + curLine.partNumber + '" priceListId="' + priceListId + 
            '" productId="' + curLine.productId + 
            '" lineId="' + curLine.lineId + '" originalQuantity="' + curLine.quantity +
            '" originalPrice="' + curLine.unitPrice + '" class="' + (cartRowCount % 2 == 0 ? 'cart-line-even' : 'cart-line-odd') +
            '" cartRow="1"><td style="padding-left:15px;" class="cart-line cart-line-right">' +
            '<span style="font-size:small;" id="viewCartLineDescription">' + 
            (curLine.csProductUrl != '' ? ('<a href="' + curLine.csProductUrl + '">') : '') +
            curLine.description + (curLine.csProductUrl != '' ? '</a>' : '') +
            '</span></td><td align="center" class="cart-line cart-line-right">' +
            '<div class="date-picker" id="viewCartLineShipDate" expectedShipDate="' + curLine.expectedShipDate + '">';
        
        if (curLine.leadTimeExpired)
            lineHtml += "Updating";
        else
            lineHtml += curLine.customerRequestDate;
        
        lineHtml += '</div></td>' +
            '<td align="center" class="cart-line cart-line-right">' + 
            '<input type="text" id="viewCartUpdateQuantity" size="3" style="text-align:right" value="' + curLine.quantity + 
            '"></td><td align="right" class="cart-line cart-line-right" id="viewCartViewUnitPrice">';
        if (_user.quotePricing) {
            priceCSS = " background-color:#FFFFFF; border:solid 1px #A88863;";
            if (curLine.unitPrice != curLine.customerPrice)
                priceCSS = " background-color:#FF5050; border:solid 1px #A88863;";
            lineHtml += '<input type="text" id="viewCartUpdateUnitPrice" size="7" style="text-align:right;' +
                priceCSS + '" value="' + curLine.unitPrice + '">';
        } else {
            lineHtml += curLine.unitPrice;
        }
        lineHtml += '</td><td align="right" style="padding-right:15px;" class="cart-line" id="viewCartExtPrice">' + 
            curLine.extPrice + '</td></tr>';
            
        // SECOND ROW ... add on the second row with the part number and action links
        lineHtml += '<tr valign="bottom" partNumber="' + curLine.partNumber + '" priceListId="' + priceListId + 
            '" productId="' + curLine.productId + 
            '" lineId="' + curLine.lineId + '" originalQuantity="' + curLine.quantity +
            '" originalPrice="' + curLine.unitPrice + '" class="' + (cartRowCount % 2 == 0 ? 'cart-line-even' : 'cart-line-odd') +
            '" cartRow="2"><td style="padding-left:15px;" class="cart-line-bottom cart-line-right">' +
            (_user.internalUser ? '<div style="float:right;"><a id="viewCartCrystalInfoLink" href="' +
            'http://intranet-apps/crystal/pages/product/default.aspx?PartNumber=' + encodeURIComponent(curLine.partNumber) + '" target="crystalInfo">' +
            'crystal info</a>&nbsp;&nbsp;&nbsp;' +
            '<a id="viewCartMoreInfoLink" moreInfoShowing="no" moreInfoPopulated="no">more info</a></div>' : '') + 
            '<div style="font-size:x-small;" id="viewCartLinePartNumber">' + curLine.partNumber + 
            (curLine.customerPartNumber == '' ? '' : ' (' + curLine.customerPartNumber + ')') +
            (curLine.packageQuantity > 1 ? ('&nbsp;&nbsp; - Available in quantity multiples of ' + curLine.packageQuantity + ' only.') : '') + 
            '</div></td><td align="center" class="cart-line-bottom cart-line-right">' +
            (!_user.internalUser ? '<a id="viewCartUpdateShipDateLink" class="date-picker-link">Change</a>' : '&nbsp;') +
            '</td><td align="center" class="cart-line-bottom cart-line-right"><a id="viewCartUpdateQuantityLink">Update</a></td>' + 
            '<td align="right" class="cart-line-bottom cart-line-right">';
        if (_user.quotePricing) {
            lineHtml += '<a id="viewCartUpdateUnitPriceLink">Update</a>';
        } else {
            lineHtml += '&nbsp;';
        }
        lineHtml += '</td><td align="right" style="padding-right:15px;" class="cart-line-bottom"><a id="viewCartRemoveLink">Remove</a></td></tr>';
                    
        // THIRD ROW ... for internal users, add another row that we can fill later with information
        if (_user.internalUser) {
            lineHtml += '<tr class="' + (cartRowCount % 2 == 0 ? 'cart-line-even' : 'cart-line-odd') + 
                '" style="display:none;" cartRow="3" moreInfoPricingPopulated="no"><td colspan="5" class="cart-line"><b>' + curLine.partNumber + '</b>';
                
            lineHtml += '<div id="moreInfoPricingOverrideReasonWrapper" style="display:' +
                (curLine.pricingOverrideReason == '' ? 'none' : 'block') + 
                ';"><div style="border:solid 1px black; margin-top:5px; margin-bottom:5px; padding:3px;"><b>' +
                'Pricing Override Reason:</b>&nbsp;&nbsp;&nbsp;<span id="moreInfoPricingOverrideReason">' + 
                curLine.pricingOverrideReason + '</span></div></div>';
            
            lineHtml += '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px black;">' +
                '<tr valign="top"><td style="padding-left:15px;">' +
                '<div id="moreInfoPart" style="padding-top:10px; font-size:12px;"></div>' + 
                '<div style="font-size:12px; padding-left:2px; padding-top:2px;"><b>ARO:</b> <span id="moreInfoARO">' + 
                    curLine.aroDays + '</span>, <b>List Price:</b> <span id="moreInfoListPrice">' +
                    curLine.listPrice + '</span></div>' + 
                '<div style="font-size:12px; padding-left:2px; padding-top:2px;" id="moreInfoAverageOrderSize"></div>' + 
                '<div style="font-size:12px; padding-left:2px; padding-top:2px;" id="moreInfoForecast"></div></td>' + 
                '<td align="right" style="width:200px; padding-right:15px;">' +
                '<div id="moreInfoATP" style="font-size:11px;"></div></td></tr></table>' +
                '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px black;"><tr valign="top">' +
                '<td style="padding-left:15px;"><div id="moreInfoPricing"></div></td></tr></table>' +
                '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px black;"><tr valign="top">' +
                '<td style="padding-left:15px;"><div id="moreInfoDistyInventory"></div></td></tr></table></td></tr>';
        }
        
        return lineHtml;
    };
        
    var createEmptyCartRow = function(partNum) {
        var priceCSS;
        var lineHtml = '<tr valign="top" partNumber="' + partNum + '" priceListId="" productId="" lineId="" originalQuantity="" ' + 
            'originalPrice="" class="' + (cartRowCount % 2 == 0 ? 'cart-line-even' : 'cart-line-odd') +
            '" cartRow="1"><td style="padding-left:15px;" class="cart-line cart-line-right">' +
            '<span style="font-size:small;" id="viewCartLineDescription">Adding to cart ...</span></td>' +
            '<td align="center" class="cart-line cart-line-right">' +
            '<div class="date-picker" id="viewCartLineShipDate"></div></td>' +
            '<td align="center" class="cart-line cart-line-right">' + 
            '<input type="text" id="viewCartUpdateQuantity" size="3" style="text-align:right" value=""></td>' +
            '<td align="right" class="cart-line cart-line-right" id="viewCartViewUnitPrice">' +
            '<input type="text" id="viewCartUpdateUnitPrice" size="7" ' +
            'style="text-align:right; background-color:#FFFFFF; border:solid 1px #A88863;" value="">' +
            '</td><td align="right" style="padding-right:15px;" class="cart-line" id="viewCartExtPrice"></td></tr>';
            
        // add on the second row with the part number and action links
        lineHtml += '<tr valign="bottom" partNumber="' + partNum + '" priceListId="" productId="" lineId="" originalQuantity="" ' +
            'originalPrice="" class="' + (cartRowCount % 2 == 0 ? 'cart-line-even' : 'cart-line-odd') +
            '" cartRow="2"><td style="padding-left:15px;" class="cart-line-bottom cart-line-right">' +
            (_user.internalUser ? '<div style="float:right;"><a id="viewCartCrystalInfoLink" href="' +
            'http://intranet-apps/crystal/pages/product/default.aspx?PartNumber=' + encodeURIComponent(partNum) + '" target="crystalInfo">' +
            'crystal info</a>&nbsp;&nbsp;&nbsp;' +
            '<a id="viewCartMoreInfoLink" moreInfoShowing="no" moreInfoPopulated="no">' +
            'more info</a></div>' : '') + '<div style="font-size:x-small;" id="viewCartLinePartNumber">' + partNum + 
            '</div></td><td align="center" class="cart-line-bottom cart-line-right">' +
            (!_user.internalUser ? '<a id="viewCartUpdateShipDateLink" class="date-picker-link">Change</a>' : '&nbsp;') + '</td>' +
            '<td align="center" class="cart-line-bottom cart-line-right"><a id="viewCartUpdateQuantityLink">Update</a></td>' + 
            '<td align="right" class="cart-line-bottom cart-line-right">';
        if (_user.quotePricing) {
            lineHtml += '<a id="viewCartUpdateUnitPriceLink">Update</a>';
        } else {
            lineHtml += '&nbsp;';
        }
        lineHtml += '</td><td align="right" style="padding-right:15px;" class="cart-line-bottom"><a id="viewCartRemoveLink">Remove</a></td></tr>';
            
                    
        // for internal users, add another row that we can fill later with information
        if (_user.internalUser) {
            lineHtml += '<tr class="' + (cartRowCount % 2 == 0 ? 'cart-line-even' : 'cart-line-odd') + 
                '" style="display:none;" cartRow="3" moreInfoPricingPopulated="no"><td colspan="5" class="cart-line"><b>' + partNum + '</b>';
                
            lineHtml += '<div id="moreInfoPricingOverrideReasonWrapper" style="display:none;">' +
                '<div style="border:solid 1px black; margin-top:5px; margin-bottom:5px; padding:3px;"><b>' +
                'Pricing Override Reason:</b>&nbsp;&nbsp;&nbsp;<span id="moreInfoPricingOverrideReason"></span></div></div>';
            
            lineHtml += '</b><table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px black;">' +
                '<tr valign="top"><td style="padding-left:15px;">' +
                '<div id="moreInfoPart" style="padding-top:10px; font-size:12px;"></div>' + 
                '<div style="font-size:12px; padding-left:2px; padding-top:2px;"><b>ARO:</b> <span id="moreInfoARO"></span>,' +
                '<b>List Price:</b> <span id="moreInfoListPrice"></span></div>' + 
                '<div style="font-size:12px; padding-left:2px; padding-top:2px;" id="moreInfoAverageOrderSize"></div>' + 
                '<div style="font-size:12px; padding-left:2px; padding-top:2px;" id="moreInfoForecast"></div></td>' + 
                '<td align="right" style="width:200px; padding-right:15px;">' +
                '<div id="moreInfoATP" style="font-size:11px;"></div></td></tr></table>' +
                '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px black;"><tr valign="top">' +
                '<td style="padding-left:15px;"><div id="moreInfoPricing"></div></td></tr></table>' +
                '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:solid 1px black;"><tr valign="top">' +
                '<td style="padding-left:15px;"><div id="moreInfoDistyInventory"></div></td></tr></table></td></tr>';
        }
        
        return lineHtml;
    };
        
    var displayMessage = function(message) {
        if (typeof(message) == "boolean") {
            if (message) {
                $.blockUI();
            } else {
                $.unblockUI();
            }
        } else if (typeof(message) == "number") {
            setTimeout(function() { $.unblockUI(); }, message);
        } else {
            $.blockUI(message);
        }            
    };

    var displayMessageWithClose = function(message, closeFn) {
        displayMessage(message + "<br/><br/><br/><a id='closeMessage'>Close</a>");
        $("#closeMessage").click(function() {
            $(this).unbind();
            displayMessage(false);
            
            if (typeof(closeFn) == "function")
                closeFn();
        });
    };
    
    var displayStatusMessage = function(result) {
        // check for status messages sent back to us
        if (result.statusMessage) {
            displayMessage(result.statusMessage);
            displayMessage(5000);
        } else {                
            displayMessage(false);
        }
    };
        
    var ignoreError = function(xhrequest, textStatus, errorThrown, elem) { 
        //alert(errorThrown); 
    };
    
    var loadMoreInfo = function(elem, section, singleStep) {
        var targetElem = $(elem).parents("tr:first").next().find("#moreInfo" + section);
        targetElem.html("<b>Loading ...</b>");
        
        var tr = $(elem).parents("tr:first");
        
        var postData = {};
        postData["action"] = "moreInfo" + section;
        postData["productId"] = tr.attr("productId");
        postData["quantity"] = tr.attr("originalQuantity");
        postData["priceListId"] = tr.attr("priceListId");
        
        JSC.ServerPost(postData, function(data, textStatus, elem2) { loadMoreInfoSuccess(data, textStatus, elem2, section, !singleStep); }, ignoreError, elem);
    };
    
    var loadMoreInfoPricing = function() {
        var rowCounter = 0;
        $("#viewCartTable tr:gt(0)").each(function() {
            var tr = $(this);
            if (tr.attr("cartRow") == "1") {
                var moreInfoRow = tr.next().next();
                if (moreInfoRow.attr("moreInfoPricingPopulated") == "no") {
                    var targetElem = moreInfoRow.find("#moreInfoPricing");

                    setTimeout(function() {
                        var postData = {};
                        postData["action"] = "moreInfoPricing";
                        postData["productId"] = tr.attr("productId");
                        postData["quantity"] = tr.attr("originalQuantity");
                        postData["priceListId"] = tr.attr("priceListId");
                        JSC.ServerPost(postData, function(data, textStatus, elem) {
                            elem.unbind();
                            elem.html(data);
                            // add on the show/hide link functionality for price breaks
                            $("a.more-info-pricing-toggle", elem).click(function() {
                                var that = $(this);
                                if (that.text() == "show") {
                                    that.text("hide");
                                    that.next().show();
                                } else {
                                    that.text("show");
                                    that.next().hide();
                                };
                            });
                        }, ignoreError, targetElem);
                    }, rowCounter * 500);
                    
                    rowCounter++;
                    
                    moreInfoRow.attr("moreInfoPricingPopulated", "yes");
                }
            }
        });
    }
    
    var loadMoreInfoSuccess = function(data, textStatus, elem, section, processNextSection) {
        var targetElem = $(elem).parents("tr:first").next().find("#moreInfo" + section);
        targetElem.unbind();
        targetElem.html(data);
        
        if (section == "Part" && data != "Item does not exist." && processNextSection)
            loadMoreInfo(elem, "DistyInventory", false);
        if (section == "DistyInventory" && processNextSection)
            loadMoreInfo(elem, "ATP", false);
        if (section == "ATP")
        {
            // add on link bindings for any error links
            addCartBinds(targetElem);
        }
        if (section == "ATP" && processNextSection)
            loadMoreInfo(elem, "AverageOrderSize", false);
        if (section == "AverageOrderSize" && processNextSection)
            loadMoreInfo(elem, "Forecast", false);
    };
    
    var quoteIt = function() {
        displayMessage("Generating quote ...");
        JSC.ServerPost({'action':'sendQuote'}, function(data) {
            displayMessageWithClose(data);
        }, ignoreError, null);
    };
    
    var removeLine = function(removeElem) {
        var curRow = $(removeElem).parents("tr:first");
        var curLine = curRow.attr("lineId");

        if (curLine != null)
            displayMessage("Removing line ...");
        
        var postData = {};
        postData["action"] = "removeLine";
        postData["lineId"] = curLine;
        JSC.ServerPost(postData,  function(data, textStatus, elem) {
            var result = JSC.ConvertServerDataToLocal(data);
    
            if (result.serverDataOk && !result.error) {
                // remove the 2 lines associated with this item
                $(elem).parents("tr:first").unbind();
                $(elem).parents("tr:first").prev().unbind();
                if (_user.internalUser)
                    $(elem).parents("tr:first").next().remove();
                $(elem).parents("tr:first").prev().remove();
                $(elem).parents("tr:first").remove();
                cartRowCount--;

                if (result.lines.length == 0) {
                    $("#quickEntryWrapper").show();
                    $("#viewCartWrapper").hide();
                } else {
                    updateCartSummary(result);
                    
                    // update the background colors on the rows
                    var rowCounter = 0;
                    var rowCounter2 = 0;
                    var counterCutoff = (_user.internalUser ? 3 : 2);
                    $("#viewCartTable").children().children(":gt(0)").each(function() {
                        var that = $(this);
                        that.removeClass("cart-line-even");
                        that.removeClass("cart-line-odd");
                        that.addClass((rowCounter % 2 == 0) ? "cart-line-even" : "cart-line-odd");

                        rowCounter2++;
                        if (rowCounter2 == counterCutoff) {
                            rowCounter2 = 0;                        
                            rowCounter++;
                        }
                    });
                }
                
                displayStatusMessage(result);
    
                JSCE.Fire("CartItemRemoved", null, "ViewCart.removeLine");
            }
        }, ignoreError, removeElem);
    };

    var setupCartList = function() {
        if (_user.internalUser) {
            $("#viewCartCartList").hide();
        } else {
            $("#viewCartCarts").change(function() {
                // hide the cart
                $("#viewCartWrapper").hide();
                
                clearCartBinds();
                var postData = {};
                postData["action"] = "changeCart";
                postData["cartName"] = $("#viewCartCarts option:selected").text();
                
                if ($("#viewCartCarts option:selected").text() == "My Cart")
                    $("#removeCartLink").hide();
                else
                    $("#removeCartLink").show();

                JSC.ServerPost(postData, function() { JSCE.Fire("CartSelected", null, "ViewCart.setupCartList"); }, ignoreError, null);
            });
            
            // remove cart link causes a page refresh after the callback
            $("#removeCartLink").click(function() {
                if (window.confirm("Please confirm deletion of cart '" + $("#viewCartCarts option:selected").text() + "'")) {
                    var postData = {};
                    postData["action"] = "deleteCart";
                    postData["cartName"] = $("#viewCartCarts option:selected").text();
                    JSC.ServerPost(postData, function() { window.location.reload(); }, ignoreError, null);
                }
            });
                
            var postData = {};
            postData["action"] = "cartList";
            JSC.ServerPost(postData, updateCartListSuccess, ignoreError, null);
        }
    };
    
    var setUpPromoCode = function() {
        $("#viewCartPromoCodeSubmit").click(changePromoCode);
        $("#viewCartPromoCodeInput").keydown(function(e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                changePromoCode();
            }
        });
    };
    
    var setUpZipEstimate = function() {
        $("#viewCartZipEstimateSubmit").click(changeZipCode);
        $("#viewCartZipInput").keydown(function(e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                changeZipCode();
            }
        });
    };
    
    var setUpQuickEntry = function() {
        $("#viewCartQuickEntrySubmit").click(function() {addQuickEntryLine("viewCart");});
        $("#quickEntrySubmit").click(function() {addQuickEntryLine("quickEntry");});
        
        $("#viewCartPartNumberInput").keydown(function(e) { 
            if (e.keyCode == 13) {
                e.preventDefault();
                $("#viewCartQuantityInput").focus(); 
            }
        });

        $("#viewCartPartNumberInput").autocomplete("/www/PartNumberAutocomplete.tsc", 
            {minChars:4, cacheLength:10, onItemSelect: function(item) {
                $("#viewCartPartNumberInput").val(item.extra[0]);
                $("#viewCartQuantityInput").focus();
            }}
        );

        $("#viewCartQuantityInput").keydown(function(e) { 
            if (e.keyCode == 13 || (e.keyCode == 9 && !e.shiftKey)) {
                if ($("#viewCartPartNumberInput").val() != "" && $("#viewCartQuantityInput").val() != "") {
                    e.preventDefault();
                    $("#viewCartPartNumberInput").focus();
                    addQuickEntryLine("viewCart");
                }
            }
        });

        $("#quickEntryPartNumberInput").keydown(function(e) { 
            if (e.keyCode == 13) {
                e.preventDefault();
                $("#quickEntryQuantityInput").focus(); 
            }
        });

        $("#quickEntryPartNumberInput").autocomplete("/www/PartNumberAutocomplete.tsc", 
            {minChars:4, cacheLength:10, onItemSelect: function(item) {
                $("#quickEntryPartNumberInput").val(item.extra[0]);
                $("#quickEntryQuantityInput").focus();
            }}
        );

        $("#quickEntryQuantityInput").keydown(function(e) { 
            if (e.keyCode == 13 || (e.keyCode == 9 && !e.shiftKey)) {
                if ($("#quickEntryPartNumberInput").val() != "" && $("#quickEntryQuantityInput").val() != "") {
                    e.preventDefault();
                    addQuickEntryLine("quickEntry");
                }
            }
        });
    };
    
    var updateCart = function() {
        displayMessage("Loading cart ...");

        clearCartBinds();
                
        var postData = {};
        postData["action"] = "cartInfo";
        JSC.ServerPost(postData, updateCartSuccess, ignoreError, null);
    };
    
    var updateCartListSuccess = function(data, textStatus, elem) {
        var cartList = eval("(" + data + ")");
        
        // create the new list of options
        var options = "";
        var selectedIndex = -1;
        for (var i = 0; i < cartList.length; i++) {
            options += '<option value="' + cartList[i].basketId + '">' + cartList[i].cartName + '</option>';
            if (cartList[i].currentBasket)
                selectedIndex = i;
        }
        
        if (cartList.length <= 1) {
            $("#viewCartCartList").hide();
        } else {
            $("#viewCartCarts").html(options);
            $("#viewCartCarts").get(0).selectedIndex = selectedIndex;
            $("#viewCartCartList").show();

            if ($("#viewCartCarts option:selected").text() == "My Cart")
                $("#removeCartLink").hide();
            else
                $("#removeCartLink").show();
        }
    };
    
    var updateCartSuccess = function(data, textStatus, elem) {
        var result = JSC.ConvertServerDataToLocal(data);

        if (result.serverDataOk && !result.error) {
            if (result.lines.length == 0 && $("#quickEntryWrapper").css("display") == "none") {
                $("#quickEntryWrapper").show();
                $("#viewCartWrapper").hide();
            } else if (result.lines.length > 0) {
                var oldDisplayValue = $("#viewCartWrapper").css("display");
                
                $("#quickEntryWrapper").hide();
                $("#viewCartWrapper").show();

                updateCartSummary(result);
            
                var orderHtml = '<table width="100%" border="0" cellpadding="2" cellspacing="0" id="viewCartTable">' +
                    '<tr style="text-transform:uppercase; color:white; font-size:12px;"><td style="padding-left:15px; border-right:solid 1px white; padding-top:5px; padding-bottom:5px;">' +
                    'Product</td><td align="center" style="border-right:solid 1px white; padding-top:5px; padding-bottom:5px;">Ship Date</td><td align="center" ' +
                    'style="border-right:solid 1px white; padding-top:5px; padding-bottom:5px;">Qty</td><td align="right" style="border-right:solid 1px white; padding-top:5px; padding-bottom:5px;">Unit Price</td>' +
                    '<td align="right" style="padding-right:15px; padding-top:5px; padding-bottom:5px;">Ext. Price</td></tr>';
                var lineCount = result.lines.length - 1;
                for (var i = 0; i <= lineCount; i++) {
                    var curLine = result.lines[i];
                    orderHtml += createCartRow(curLine, result.priceListId, i);
                    cartRowCount++;
                }
                orderHtml += '</table>';
                $("#viewCartBasketLines").html(orderHtml);
           
                addCartBinds("#viewCartBasketLines");
                
                if (oldDisplayValue == "none") {
                    // if we are just turning it on, assuming first line added from quick entry, so select input field for focus
                    $("#viewCartPartNumberInput").focus();
                }
            }

            displayStatusMessage(result);
            
            loadMoreInfoPricing();
            
            Ubiquitous.CtrlMBlock("ViewCart.updateLeadTimes", true);
            updateLeadTimes();
        } else {
            // show the error message for 5 seconds
            displayMessage(result.errorMessage);
            displayMessage(5000);
        }
        
        if (!tableCornered) {
            $("#viewCartWrapper").corner();
            $("#quickEntryWrapper").corner();
            tableCornered = true;
        }

        Ubiquitous.CtrlMBlock("ViewCart.updateCart", false);
    };

    var updateCartSummary = function(basket) {
        $("#viewCartPromoCodeInput").val(basket.promoCode);
    
        if (basket.shippingSet) {
            $("#zipForEstimatesWrapper").hide();
        } else {
            $("#zipForEstimatesWrapper").show();
            $("#viewCartZipInput").val(basket.zipForEstimates);
        }
        
        $("#viewCartSubtotal").text(basket.subtotal);
        $("#viewCartTotal").text(basket.total);
        
        if (basket.zipForEstimates == "") {
            $("#viewCartShipping").text("N/A");
            $("#viewCartTax").text("N/A");
        } else {
            $("#viewCartShipping").text(basket.shipping);
            $("#viewCartTax").text(basket.tax);
        }

        $("#viewCartPromo").text(basket.promo);
        if (basket.promoCode == "")
            $("#viewCartPromoRow").hide();
        else
            $("#viewCartPromoRow").show();
    };
    
    var updateLeadTimes = function() {
    
        var showMLT = false;
        
        if (!_updatingLeadTimes) {
            _updatingLeadTimes = true;
            
            JSC.ServerPost({'action':'updateCartLeadTimes'}, function(data) {
                var result = eval("(" + data + ")");
                var lines = [];
                for (var i = 0; i < result.length; i++) {
                    lines[result[i].lineId] = result[i];
                }
                
                var updatingCount = 0;
                $("#viewCartTable tr").each(function() {
                    var thisRow = $(this);
                    var lineId = thisRow.attr("lineId");
                    if (thisRow.attr("cartrow") == "1" && lines[lineId] != null) {
                        if(lines[lineId].mltMessage == "1")
                         showMLT = true;
                         
                     
                     
                        thisRow.find("#viewCartLineShipDate").attr("expectedShipDate", lines[lineId].expectedShipDate).text(lines[lineId].customerRequestDate);
                        thisRow.next().next().find("#moreInfoARO").text(lines[lineId].aroDays);
                    } else if (thisRow.find("#viewCartLineShipDate").text() == "Updating") {
                        updatingCount++;
                        
                    }
                    
                });                
            
            if(showMLT)
                $("#showMLT").show();                    
            else
                $("#showMLT").hide();
            
                _updatingLeadTimes = false;
                Ubiquitous.CtrlMBlock("ViewCart.updateLeadTimes", false);
                
                if (updatingCount > 0) {
                    Ubiquitous.CtrlMBlock("ViewCart.updateLeadTimes", true);
                    updateLeadTimes();
                } else {
                    JSCE.Fire("CartLeadTimesUpdated", null, "ViewCart.updateLeadTimes");
                }
            }, ignoreError, null);
        }
    };
    
    var updatePrice = function() {
        var curRow = pricingOverrideRow;
        var curLine = curRow.attr("lineId");
        var origPrice = curRow.attr("originalPrice");

        var curPrice = $("#viewCartUpdateUnitPrice", curRow).val();

        if (origPrice != curPrice) {
            displayMessage("Updating unit price ...");
            
            var postData = {};
            postData["action"] = "updateCartPricing";
            postData["lineId"] = curLine;
            postData["unitPrice"] = curPrice;
            postData["overrideReason"] = $("#viewCartPricingReason").val();
            JSC.ServerPost(postData,  function(data, textStatus, elem) { 
                var result = JSC.ConvertServerDataToLocal(data);
                if (result.serverDataOk && !result.error) {
                    // get the row in the table
                    var inputRow = elem;
                    var linkRow = inputRow.next();
                        
                    var curLineId = inputRow.attr("lineId");
                    
                    // and the line on the order
                    var curLine = null;
                    for (var i = 0; i < result.lines.length; i++) {
                        if (result.lines[i].lineId == curLineId) {
                            curLine = result.lines[i];
                            break;
                        }
                    }
                    
                    if (curLine != null) {
                        inputRow.attr("originalPrice", curLine.unitPrice);
                        linkRow.attr("originalPrice", curLine.unitPrice);
                        
                        if (_user.quotePricing) {
                            $("#viewCartUpdateUnitPrice", inputRow).val(curLine.unitPrice);
                            if (curLine.unitPrice != curLine.customerPrice) {
                                inputRow.find("#viewCartUpdateUnitPrice").css("background-color", "#FF5050");
                                inputRow.find("#viewCartUpdateUnitPrice").css("border", "1px solid #A88863");
                            } else {
                                inputRow.find("#viewCartUpdateUnitPrice").css("background-color", "#FFFFFF");
                                inputRow.find("#viewCartUpdateUnitPrice").css("border", "1px solid #A88863");
                            }
                        } else {
                            $("#viewCartViewUnitPrice", inputRow).text(curLine.unitPrice);
                        }
                        
                        $("#viewCartExtPrice", inputRow).text(curLine.extPrice);
                    }
                    
                    updateCartSummary(result);
                    
                    displayStatusMessage(result);
                }
            }, ignoreError, curRow);
        } else {
            displayMessage("No changes made ...");
            displayMessage(2000);
        }
    };
    
    var updateQuantity = function(updateElem) {
        var curRow = $(updateElem).parents("tr:first");
        var curLine = curRow.attr("lineId");
        var origQty = curRow.attr("originalQuantity");
        
        var curQty = 0;
        if (curRow.attr("cartRow") == "1")
            curQty = $("#viewCartUpdateQuantity", curRow).val();
        else
            curQty = $("#viewCartUpdateQuantity", curRow.prev()).val();

        if (curQty == 0) {
            // remove the line
            if (curRow.attr("cartRow") == "1") {
                curRow.next().find("a#viewCartRemoveLink").click();
            } else {
                curRow.find("a#viewCartRemoveLink").click();
            }
        } else if (origQty != curQty) {
            displayMessage("Updating quantity ...");
            
            var postData = {};
            postData["action"] = "updateCartQuantity";
            postData["lineId"] = curLine;
            postData["quantity"] = curQty;
            JSC.ServerPost(postData,  function(data, textStatus, elem) { 
                var result = JSC.ConvertServerDataToLocal(data);
                if (result.serverDataOk && !result.error) {
                    // get the row in the table
                    var inputRow = $(elem).parents("tr:first");
                    var linkRow = $(elem).parents("tr:first");
                    if (inputRow.attr("cartRow") == "2") {
                        inputRow = inputRow.prev();
                    } else {
                        linkRow = linkRow.next();
                    }
                        
                    var curLineId = inputRow.attr("lineId");
                    
                    // and the line on the order
                    var curLine = null;
                    for (var i = 0; i < result.lines.length; i++) {
                        if (result.lines[i].lineId == curLineId) {
                            curLine = result.lines[i];
                            break;
                        }
                    }
                    
                    if (curLine != null) {
                        inputRow.attr("originalQuantity", curLine.quantity);
                        linkRow.attr("originalQuantity", curLine.quantity);
                        inputRow.attr("originalPrice", curLine.unitPrice);
                        linkRow.attr("originalPrice", curLine.unitPrice);
                        
                        $("div.date-picker", inputRow).text(curLine.expectedShipDate);
                        $("#viewCartUpdateQuantity", inputRow).val(curLine.quantity);
                        
                        if (_user.quotePricing) {
                            $("#viewCartUpdateUnitPrice", inputRow).val(curLine.unitPrice);
                        } else {
                            $("#viewCartViewUnitPrice", inputRow).text(curLine.unitPrice);
                        }
                        
                        $("#viewCartExtPrice", inputRow).text(curLine.extPrice);
                    }
                    
                    updateCartSummary(result);
                    updateLeadTimes();
                    
                    // trigger an update of the more info section
                    if (_user.internalUser) {
                        var moreInfoLink = $("#viewCartMoreInfoLink", linkRow);
                        
                        // if it's not showing, then just set the populated flag to no
                        if (moreInfoLink.attr("moreInfoShowing") == "no") {
                            moreInfoLink.attr("moreInfoPopulated", "no");
                        } else {
                            // flag it as not showing, not populated, then click it
                            var nextRow = linkRow.next();
                            nextRow.hide();
                            nextRow.find("#moreInfoPricing").html("");
                            nextRow.find("#moreInfoATP").html("");
                            nextRow.find("#moreInfoPart").html("");
                            moreInfoLink.attr("moreInfoShowing", "no");
                            moreInfoLink.attr("moreInfoPopulated", "no");
                            moreInfoLink.click();
                        }
                    }
                    
                    displayStatusMessage(result);
                }
            }, ignoreError, updateElem);
        } else {
            displayMessage("No changes made ...");
            displayMessage(2000);
        }
    };
    
    var updateShipDate = function(updateElem, shipDate) {
        var curRow = $(updateElem).parents("tr:first");
        var curLine = curRow.attr("lineId");
        
        displayMessage("Updating ship date ...");
            
        var postData = {};
        postData["action"] = "updateCartShipDate";
        postData["lineId"] = curLine;
        postData["shipDate"] = shipDate;
        JSC.ServerPost(postData,  function(data, textStatus, elem) { 
            var result = JSC.ConvertServerDataToLocal(data);
            if (result.serverDataOk && !result.error) {
                // get the row in the table
                var inputRow = $(elem).parents("tr:first");
                var curLineId = inputRow.attr("lineId");
                
                // and the line on the order
                var curLine = null;
                for (var i = 0; i < result.lines.length; i++) {
                    if (result.lines[i].lineId == curLineId) {
                        curLine = result.lines[i];
                        break;
                    }
                }
                
                if (curLine != null) {
                    $("div.date-picker", inputRow).text(curLine.customerRequestDate).attr("expectedShipDate", curLine.expectedShipDate);
                }
            }
            
            displayMessage(false);
        }, ignoreError, updateElem);
    };
    
    return {
        Init : function() {
            Ubiquitous.CtrlMBlock("ViewCart.InitAndLoad", true);
            JSCE.Subscribe("CartSelected", updateCart);
            JSCE.Subscribe("CartUpdated", updateCart);
            JSCE.Subscribe("ManageItClosed", function() {
                // workaround for corner bug in IE
                if ($.browser.msie) {
                    $("#viewCartWrapper").uncorner();
                    $("#quickEntryWrapper").uncorner();
                    tableCornered = false;
                }
            });

            JSCE.Subscribe("UbiquitousLoaded", ViewCart.Load);
        },
        
        Load : function() {
            _user = Ubiquitous.User();
            
            if (_user.oc) {
                $("#pricingNote").show();
                $("#pricingNoteCustomerName").text(_user.customerName);
            }
            
            pricingOverrideElem = $("#pricingOverrideForm")[0];
            
            $("#quoteItLink").click(quoteIt);
                        
            setupCartList();
            setUpQuickEntry();
            setUpPromoCode();
            setUpZipEstimate();
            Ubiquitous.CtrlMBlock("ViewCart.InitAndLoad", false);

            Ubiquitous.CtrlMBlock("ViewCart.updateCart", true);
            updateCart();
        },
        
        UpdatingLeadTimes : function() { return _updatingLeadTimes; }
    }
})();

ViewCart.Init();
