﻿/** 
  <summary>
    Main Function:  calculation quote detail(shopping cart)
    Created Date:   08/17/2009
    Created By:     YW
    Modified Date: [MM/DD/YYYY]
    Modified By: [Your initial]
    Reason for Modifying: [Your comment]
*/


var QuoteDetail = new Array();

var QuoteDetailHiddenFieldID, quoteIDHiddenFieldID, customerIDHiddenFieldID, customerAccountTypeCodeHiddenFieldID, isWebSalesLogIn, 
    isLocalAreaHiddenFieldID, isFreightHiddenFieldID, isMultitpleShipResult;
    
var discountedSubtotalAmount, mimAmountToFreeShip, localDeliveryFeeAmount, totalDeliveryCost;

var promoTableID, promoDescLableID, promoAmountLableID, discountedSubtotalLabelID, subtotalLabelID, 
    promoCodeTextBoxID, normalPromotionHiddenFieldID, enterPromoCodeTableRowID, clearPromoCodeTableRowID, 
    promoTotalAmtHiddenFieldID, normalPromotionIDHiddenFieldID, promoCodeLabelID,
    townHiddenFieldID, taxRateHiddenFieldID, resellerHiddenFieldID, taxLabelID, taxAmtLabelID, 
    shipResultHiddenFieldID, totalShipCostLabelID, shipCostDescriptionLabelID, selectedShippingTxtID, 
    normalShippingCostLabelID, dropShippingCostLabelID,
    shipCostHiddenFieldID, dropShipCostHiddenFieldID, taxTotalHiddenFieldID,
    freightTotalLabelID, totalCostLabelID, finialTotalHiddenFieldID,
    itemCodeTextBoxID, itemQtyTextBoxID, addItemErrorLabelID, updateButtonID, focusIDHiddenFieldID,
    dollarAwayLabelID, freeShipInfoTableID, freeShippingSpanID, freightInfoSpanID, qualifyFreeShipSpanID,
    feeTotalHiddenFieldID, smallPkgFeeTableID, smallPkgFeeDescLabelID, smallPkgFeeAmtLabelID,
    accountFeeTableID, accountFeeDescLabelID, accountFeeAmtLabelID,
    smallPckFeeHiddenFieldID, customerAccountFeeTypeHiddenFieldID, customerAccountFeeHiddenFieldID;
    
var cartonizationPath, shipToAddressHiddenFieldID, shipOptionPopupBehaviorID, shippingOptionTableAreaID, addressInCartLabelID, showShippingOptionLinkButtonID;    
    
    // calculate shipping result
    function CalculateShippingResult()
    {
        var inputStr = cartonizationPath + "|@WS@|";
        if (!quoteIDHiddenFieldID || !$get(quoteIDHiddenFieldID) || $get(quoteIDHiddenFieldID).value == "")
        {
            return;
        }
        inputStr += $get(quoteIDHiddenFieldID).value + "|@WS@|";
    
        // ship to address
        if (!shipToAddressHiddenFieldID || !$get(shipToAddressHiddenFieldID) || $get(shipToAddressHiddenFieldID).value == "")
        {
            return;
        }
        inputStr += $get(shipToAddressHiddenFieldID).value + "|@WS@|";
        
        // customer ID
        if (customerIDHiddenFieldID && $get(customerIDHiddenFieldID) && 
            $get(customerIDHiddenFieldID).value != "")
        {
            inputStr += $get(customerIDHiddenFieldID).value  + "|@WS@|";
        }
        else
        {
            inputStr += "0|@WS@|";
        }
        
        // customer account type code
        if (customerAccountTypeCodeHiddenFieldID && $get(customerAccountTypeCodeHiddenFieldID) && 
            $get(customerAccountTypeCodeHiddenFieldID).value != "")
        {
            inputStr += $get(customerAccountTypeCodeHiddenFieldID).value  + "|@WS@|";
        }
        else
        {
            inputStr += "|@WS@|";
        }
        
        inputStr += isWebSalesLogIn.toString();
        ShoppingCartService.CalculateShippingResult(inputStr, ProcessShippingResult);
    }
    
    // ProcessShippingResult
    function ProcessShippingResult(result)
    {        
        var processShipResult = result.split("|@WS@|");
        if (processShipResult.length < 4 )
        {
            PopupMessage("Cannot Calculate Shipping", result, null, null);
            return;
        }
        
        // is local
        var isLocal = processShipResult[0];
        if (isLocalAreaHiddenFieldID && $get(isLocalAreaHiddenFieldID))
        {
            $get(isLocalAreaHiddenFieldID).value = isLocal;
        }
        
        // is freight
        var isFreight = processShipResult[1];
        if (isFreightHiddenFieldID && $get(isFreightHiddenFieldID))
        {
            $get(isFreightHiddenFieldID).value = isFreight;
        }
        
        // ship result
        var shipResult = processShipResult[2];
        if (shipResultHiddenFieldID && $get(shipResultHiddenFieldID))
        {
            $get(shipResultHiddenFieldID).value = shipResult;
        }
        
        // address string
        var addressStr = processShipResult[3];       
        
        if (addressInCartLabelID && $get(addressInCartLabelID) && addressStr != "")
        {
            $get(addressInCartLabelID).innerHTML = addressStr;
        }    
                
        if (shipResult)
        {
            // ship to address
            if (!shipToAddressHiddenFieldID || !$get(shipToAddressHiddenFieldID) || $get(shipToAddressHiddenFieldID).value == "")
            {
                return;
            }
            var shipToAddressStr = $get(shipToAddressHiddenFieldID).value;
            
            // selected ship method
            var selecteShipMethod = "";
            if (selectedShippingTxtID && $get(selectedShippingTxtID))
            {
                selecteShipMethod = $get(selectedShippingTxtID).value;
            }
            
            var inputStr = shipToAddressStr + "|@WS@|" + selecteShipMethod + "|@WS@|" + shipResult;
            
            ShoppingCartService.ShowShipResult(inputStr, ShowShipResultTable);
        }
    }
    
    // show delivery results table
    function ShowShipResultTable(shipResultStr)
    {        
        var shipResultList = shipResultStr.split("|@WS@|");
        if (shipResultList.length < 7 )
        {
            return;
        }
        
        if (shippingOptionTableAreaID && $get(shippingOptionTableAreaID))
        {
            $get(shippingOptionTableAreaID).innerHTML = shipResultList[0];
        }
        
        if (shipOptionPopupBehaviorID && shipOptionPopupBehaviorID != "")
        {
            $find(shipOptionPopupBehaviorID).show();
        } 
        
        // selected values
        var selectedShipCity = shipResultList[1];
        var selectedTaxRate = shipResultList[2];
        var warehouseDeliveryCost = shipResultList[3];
        var dropShipDeliveryCost = shipResultList[4];
        var selectedShipMethod = shipResultList[5];
        isMultitpleShipResult = shipResultList[6];
        
        if ($get(selectedShippingTxtID))
        {
            $get(selectedShippingTxtID).value = selectedShipMethod;
        }
        
        if ($get(shipCostHiddenFieldID))
        {
            $get(shipCostHiddenFieldID).value = warehouseDeliveryCost;
        }
        
        if ($get(dropShipCostHiddenFieldID))
        {
            $get(dropShipCostHiddenFieldID).value = dropShipDeliveryCost;    
        }        

        if ($get(townHiddenFieldID))
        {
            $get(townHiddenFieldID).value = selectedShipCity;
        }
        
        if ($get(taxRateHiddenFieldID))
        {
            $get(taxRateHiddenFieldID).value = selectedTaxRate;    
        }    
        
        if (showShippingOptionLinkButtonID && $get(showShippingOptionLinkButtonID ))
        {
            $get(showShippingOptionLinkButtonID ).style.display = 'none';
            if (isMultitpleShipResult == "True")
            {
                $get(showShippingOptionLinkButtonID ).style.display = 'block';
            }
        }
          
        ShowSummary();  
        
        CloseLoadingImage(); 
    }

    // clear promotion from quote    
    function ClearPromoCode()
    {        
        $get(normalPromotionHiddenFieldID).value = "";
        $get(promoTableID).style.display = 'none';
        $get(clearPromoCodeTableRowID).style.display = 'none'; 
        $get(enterPromoCodeTableRowID).style.display = 'block'; 
        $get(promoCodeTextBoxID).value = "";
        $get(promoTotalAmtHiddenFieldID).value = "";
        $get(normalPromotionIDHiddenFieldID).value = "";
              
        // get quote details
        GetQuoteDetails();
        
        if (QuoteDetail != null && QuoteDetail.length > 0)
        {
            var i = 0;
            discountedSubtotalAmount = 0;
            for (i = 0; i < QuoteDetail.length; i ++)
            {
                // sales discount == 0
                if (parseFloat(QuoteDetail[i][7]) == 0)
                {
                    if (parseFloat(QuoteDetail[i][6]) > 0)
                    {
                        QuoteDetail[i][10] = Math.round((parseFloat(QuoteDetail[i][4]) - parseFloat(QuoteDetail[i][6])) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                    }
                    else
                    {
                        QuoteDetail[i][10] = Math.round((Math.round(parseFloat(QuoteDetail[i][4]) * 100) / 100) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                    }
                }
                else
                {
                    QuoteDetail[i][10] = Math.round((Math.round(parseFloat(QuoteDetail[i][7]) *100) / 100) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                }
                discountedSubtotalAmount += Math.round(parseFloat(QuoteDetail[i][10]) * 100) / 100;
            }
                
            DisplayPriceLable(subtotalLabelID, discountedSubtotalAmount, false, false); 
                                
            SetQuoteDetails();
        }
        
        ShoppingCartService.ClearPromotionCode();
        
        ShowSummary();
    }
    
    // calculate    
    function ValidatePromoCode()
    {
        var normalPromotion= $get(normalPromotionHiddenFieldID);
            
        if (normalPromotion.value != "")
        {
            var inputStr = normalPromotion.value + "|@WS@|";
            
            var customerIDHiddenField = $get(customerIDHiddenFieldID);
            var quoteIDHiddenField = $get(quoteIDHiddenFieldID);
            
            inputStr += customerIDHiddenField.value + "|@WS@|" + quoteIDHiddenField.value;
        
            ShoppingCartService.CheckPromotionCode(inputStr, ProcessPromoCode);
        }
        return false;
    }
    
    function ProcessPromoCode(result)
    {        
        var ItemPromotions = DeSerializeItemPromotions(result);
                
        var NewQuoteDetail = new Array();
        
        if (ItemPromotions != null && ItemPromotions.length > 0 && ItemPromotions[0].length > 12)
        {
            $get(promoDescLableID).innerHTML = ItemPromotions[0][4];
            
            var discountAmount = 0;
            var subtotalAmount = 0;
            discountedSubtotalAmount = 0;
            
            // get quote details
            GetQuoteDetails();
            
            if (QuoteDetail != null && QuoteDetail.length > 0)
            {
                var i = 0;
                var oneQuoteDetail;
                var item;
                var itemCode;
                var discountedItemsOrderTotal = 0;
                var discounted = false;
                
                for (i = 0; i < QuoteDetail.length; i ++)
                {
                    // sales discount == 0
                    if (parseFloat(QuoteDetail[i][7]) == 0)
                    {
                        if (parseFloat(QuoteDetail[i][6]) > 0)
                        {
                            QuoteDetail[i][10] = Math.round((parseFloat(QuoteDetail[i][4]) - parseFloat(QuoteDetail[i][6])) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                        }
                        else
                        {
                            QuoteDetail[i][10] = Math.round((Math.round(parseFloat(QuoteDetail[i][4]) * 100) / 100) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                        }
                    }
                    else
                    {
                        QuoteDetail[i][10] = Math.round((Math.round(parseFloat(QuoteDetail[i][7]) *100) / 100) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                    }
                
                    // item                    
                    if (QuoteDetail[i][2] != null)
                    {
                        item = DeSerializeItem(QuoteDetail[i][2]);
                        itemCode = item[0];
                        
                        var j = 0;
                        for (j = 0; j < ItemPromotions.length; j ++)
                        {
                            if (ItemPromotions[j].length > 12 && itemCode == ItemPromotions[j][0])
                            {
                                discountedItemsOrderTotal += parseFloat(QuoteDetail[i][10]);
                                break;
                            }
                        }
                    }
                }
                
                i = 0;
                
                for (i = 0; i < QuoteDetail.length; i ++)
                {
                    discounted = false;
                    // item                    
                    if (QuoteDetail[i][2] != null)
                    {
                        item = DeSerializeItem(QuoteDetail[i][2]);
                        itemCode = item[0];
                        
                        var j = 0;
                        for (j = 0; j < ItemPromotions.length; j ++)
                        {
                            if (ItemPromotions[j].length > 12 && itemCode == ItemPromotions[j][0])
                            {
                                subtotalAmount += Math.round(parseFloat(QuoteDetail[i][10]) * 100) / 100;
                            
                                //IsDiscountPercent
                                if (ItemPromotions[j][8].toUpperCase() == "TRUE")
                                {
                                    //FinalTotalAmt
                                    QuoteDetail[i][10] = parseFloat(QuoteDetail[i][10]) * (1 - (parseFloat(ItemPromotions[j][9]) / 100));
                                }
                                else
                                {
                                    QuoteDetail[i][10] = parseFloat(QuoteDetail[i][10]) - parseFloat(ItemPromotions[j][9]) * (parseFloat(QuoteDetail[i][10]) / discountedItemsOrderTotal);
                                }
                
                                discountedSubtotalAmount +=  Math.round(parseFloat(QuoteDetail[i][10]) * 100) / 100;
                                discounted = true;
                                break;
                            }
                        }
                        
                        // for items not qualified for promotion
                        if (!discounted)
                        {
                            subtotalAmount += Math.round(parseFloat(QuoteDetail[i][10]) * 100) / 100;
                            discountedSubtotalAmount +=  Math.round(parseFloat(QuoteDetail[i][10]) * 100) / 100;
                        }
                    }
                }
                
                DisplayPriceLable(subtotalLabelID, subtotalAmount, false, false);
                if (ItemPromotions[0][8].toUpperCase() == "TRUE")
                {
                    DisplayPriceLable(promoAmountLableID, (subtotalAmount - discountedSubtotalAmount), false, true);
                    $get(promoTotalAmtHiddenFieldID).value = subtotalAmount - discountedSubtotalAmount;
                }
                else
                {
                    DisplayPriceLable(promoAmountLableID, parseFloat(ItemPromotions[0][9]), false, true); 
                    $get(promoTotalAmtHiddenFieldID).value = ItemPromotions[0][9];
                }            
                
                DisplayPriceLable(discountedSubtotalLabelID, discountedSubtotalAmount, false, false);                         
                            
                $get(normalPromotionIDHiddenFieldID).value = ItemPromotions[0][1];    
                $get(promoCodeLabelID).innerHTML = ItemPromotions[0][5];   
            }
            SetQuoteDetails();        
            
            $get(promoTableID).style.display = 'block'; 
            $get(clearPromoCodeTableRowID).style.display = 'block'; 
            $get(enterPromoCodeTableRowID).style.display = 'none'; 
        }
        else
        {         
            $get(promoTableID).style.display = 'none';
            $get(clearPromoCodeTableRowID).style.display = 'none'; 
            $get(enterPromoCodeTableRowID).style.display = 'block'; 
            $get(promoTotalAmtHiddenFieldID).value = "";
            $get(normalPromotionIDHiddenFieldID).value = "";
            $get(normalPromotionHiddenFieldID).value = "";
              
            ShoppingCartService.ClearPromotionCode();
            
            PopupMessage("P.R. Number", result, null, null);
        }
        
        // recalculat tax and total
        ShowSummary();
    }

    // flip local shipping
    function FlipFreeLocalShipping()
    {    
        // delivery cost
        var selectedShipMethod = $get(selectedShippingTxtID);
        var shipCost = 0;
        
        // for local delivery , we show free shipping info
        if (selectedShipMethod.value == DELIVERY_CODE_OURTRUCK ||
            selectedShipMethod.value == DELIVERY_CODE_1FEDEX_OURTRK ||
            selectedShipMethod.value == DELIVERY_CODE_1UPSOURTRK )
        {   
            if ($get(shipCostHiddenFieldID) && $get(shipCostHiddenFieldID).value != "")
            {
                shipCost = parseFloat($get(shipCostHiddenFieldID).value);
            }                
                    
            // check free shipping
            if (mimAmountToFreeShip > 0 && freeShipInfoTableID && 
                freeShipInfoTableID  && freeShippingSpanID && qualifyFreeShipSpanID )
            {
                if (mimAmountToFreeShip > discountedSubtotalAmount)
                {
                    // show dollar-away free shipping info
                    if (dollarAwayLabelID && $get(dollarAwayLabelID) && shipCost > 0 &&
                        mimAmountToFreeShip - discountedSubtotalAmount < 50)
                    {
                        $get(freeShipInfoTableID).style.display = 'block'; 
                        $get(freeShippingSpanID).style.display = 'block'; 
                        $get(qualifyFreeShipSpanID).style.display = 'none'; 
                        if ($get(freightInfoSpanID))
                        {
                            $get(freightInfoSpanID).style.display = 'none';     
                        }   
                                
                        DisplayPriceLable(dollarAwayLabelID, parseFloat(mimAmountToFreeShip) - parseFloat(discountedSubtotalAmount), false, false);
                    }
                }                    
                else 
                {
                    // qualify for free shipping
                    if (selectedShipMethod != null && shipCost != null && shipCost == 0)
                    {
                        $get(freeShipInfoTableID).style.display = 'block'; 
                        $get(freeShippingSpanID).style.display = 'none'; 
                        $get(qualifyFreeShipSpanID).style.display = 'block'; 
                        if ($get(freightInfoSpanID))
                        {
                            $get(freightInfoSpanID).style.display = 'none';     
                        }   
                    }
                }
            } 
        }                     
    }

    // show summary
    function ShowSummary()
    {             
        // calculate tax
        CalculateTax();  
        
        $get(smallPkgFeeTableID).style.display = 'none'; 
        $get(smallPkgFeeDescLabelID).style.display = 'none'; 
        $get(smallPkgFeeAmtLabelID).style.display = 'none'; 
        $get(accountFeeTableID).style.display = 'none'; 
        $get(accountFeeDescLabelID).style.display = 'none'; 
        $get(accountFeeAmtLabelID).style.display = 'none';    
        
        if ($get(freeShipInfoTableID))
        {
            $get(freeShipInfoTableID).style.display = 'none'; 
        }
        
        if ($get(freeShippingSpanID))
        {
            $get(freeShippingSpanID).style.display = 'none'; 
        }
        if ($get(qualifyFreeShipSpanID))
        {
            $get(qualifyFreeShipSpanID).style.display = 'none'; 
        }
        if ($get(freightInfoSpanID))
        {
            $get(freightInfoSpanID).style.display = 'none';     
        }         
        
        // get subtotal
        if (discountedSubtotalAmount <= 0)
        {                        
            // get quote details
            GetQuoteDetails();
            if (QuoteDetail != null && QuoteDetail.length > 0)
            {
                var i = 0;
                discountedSubtotalAmount = 0;
                for (i = 0; i < QuoteDetail.length; i ++)
                {
                    discountedSubtotalAmount += parseFloat(QuoteDetail[i][10]);
                }
            }   
        }  
        
        // update quote sub total
        ShoppingCartService.UpdateCartSubtotal($get(quoteIDHiddenFieldID).value + "|@WS@|" + discountedSubtotalAmount, ProcessDiscountedSubTotal); 
    }
    
    function ProcessDiscountedSubTotal(quoteHeaderStr)
    {        
        if (quoteHeaderStr && quoteHeaderStr != "")
        {
            ShowCartHeader(quoteHeaderStr);
        }
    
        var finalTotal = 0;
        
        var freightTotalLabel = $get(freightTotalLabelID);
        var totalCostLabel = $get(totalCostLabelID);        
        if (freightTotalLabel != null)
        {
            freightTotalLabel.style.display = 'none'; 
        }
                
        // shipping hasn't calculated
        var shipResult = $get(shipResultHiddenFieldID);
        
        if (shipResult == null || shipResult.value == "")
        {
            if (freightTotalLabel != null)
            {
               freightTotalLabel.style.display = 'none'; 
            }
            if (shipCostDescriptionLabelID && $get(shipCostDescriptionLabelID))
            {
                $get(shipCostDescriptionLabelID).innerHTML = "Total Shipping:&nbsp;";
            }
            if (totalCostLabel != null)
            {
                totalCostLabel.innerHTML = "$?.??";
            }
            
            if ($get(totalShipCostLabelID) != null)
            {
                $get(totalShipCostLabelID).innerHTML = "$?.??";
            }
            
            return;
        }
        
        // no ship method selected
        var selectedShipMethod = $get(selectedShippingTxtID);     
           
        if (selectedShipMethod == null || selectedShipMethod.value == "")
        {
            if (freightTotalLabel != null)
            {
                freightTotalLabel.style.display = 'none'; 
            }
            if (shipCostDescriptionLabelID && $get(shipCostDescriptionLabelID))
            {
                $get(shipCostDescriptionLabelID).innerHTML = "Total Shipping:&nbsp;";
            }
            if (totalCostLabel != null)
            {
                totalCostLabel.innerHTML = "$?.??";
            }
            
            if ($get(totalShipCostLabelID) != null)
            {
                $get(totalShipCostLabelID).innerHTML = "$?.??";
            }
            return;
        }
        
        totalDeliveryCost = 0;
        
        // shipping cost
        var shipCost = 0;
        if ($get(shipCostHiddenFieldID) && $get(shipCostHiddenFieldID).value != "")
        {
            shipCost = parseFloat($get(shipCostHiddenFieldID).value);     
            
            if (normalShippingCostLabelID && $get(normalShippingCostLabelID))
            {
                if (shipCost >= 0)
                {
                    DisplayPriceLable(normalShippingCostLabelID, shipCost, false, false);
                }
                else
                {
                    $get(normalShippingCostLabelID).innerHTML = "$?.??";
                }
            }
        }
        
        if (shipCost >= 0)
        {
            totalDeliveryCost += shipCost;
        }
        
        // drop ship cost
        var dropShipCost = 0;
        if ($get(dropShipCostHiddenFieldID) && $get(dropShipCostHiddenFieldID).value != "")
        {
            dropShipCost = parseFloat($get(dropShipCostHiddenFieldID).value);  
            if (dropShippingCostLabelID && $get(dropShippingCostLabelID))
            {
                if (dropShipCost >= 0)
                {
                    DisplayPriceLable(dropShippingCostLabelID, dropShipCost, false, false);
                }
                else
                {
                    $get(dropShippingCostLabelID).innerHTML = "$?.??";
                }
            }  
        }
        
        if (dropShipCost >= 0)
        {
            totalDeliveryCost += dropShipCost;
        }
        
        var isLocalArea = "False";
        if (isLocalAreaHiddenFieldID && $get(isLocalAreaHiddenFieldID) && 
            $get(isLocalAreaHiddenFieldID).value != "")
        {
            isLocalArea = $get(isLocalAreaHiddenFieldID).value;
        }
        
        var isFreight = "False";
        if (isFreightHiddenFieldID && $get(isFreightHiddenFieldID) && 
            $get(isFreightHiddenFieldID).value != "")
        {
            isFreight = $get(isFreightHiddenFieldID).value;
        }
        
        // is freight shipping
        if ((isLocalArea != "True" &&
            (isWebSalesLogIn != "True" || (isWebSalesLogIn == "True" && selectedShipMethod.value != DELIVERY_CODE_WILLCALL))
            )
            && (isFreight == "True" || 
                selectedShipMethod.value == DELIVERY_CODE_1FREIGHT ||
                selectedShipMethod.value == DELIVERY_CODE_NOT_AVAILABLE) ||            
                totalDeliveryCost <= 0 && selectedShipMethod.value == DELIVERY_CODE_DROPSHIP)
        {
            if ($get(freeShipInfoTableID) && $get(freightInfoSpanID))
            {
                $get(freeShipInfoTableID).style.display = 'block'; 
                $get(freightInfoSpanID).style.display = 'block';     
            }  
            
            if (shipCostDescriptionLabelID && $get(shipCostDescriptionLabelID))
            {
                $get(shipCostDescriptionLabelID).innerHTML = "Total Shipping:&nbsp;";
            }
            if (totalCostLabel != null)
            {
                totalCostLabel.innerHTML = "$?.??";
            }
            if ($get(totalShipCostLabelID) != null)
            {
                $get(totalShipCostLabelID).innerHTML = "$?.??";
            }
            if (freightTotalLabel != null)
            {
               freightTotalLabel.style.display = 'block'; 
            }
            return;
        }   
        
        // shipping desc
        if (shipCostDescriptionLabelID && $get(shipCostDescriptionLabelID))
        {
            if (selectedShipMethod.value == DELIVERY_CODE_OURTRUCK && dropShipCost == 0)
            {
                $get(shipCostDescriptionLabelID).innerHTML = "Paper Mart Delivery Truck:&nbsp;";
            }
            else
            {
                $get(shipCostDescriptionLabelID).innerHTML = "Total Shipping:&nbsp;";
            }
        }  
        
        // get local delivery and all fee amount from web service
        var inputStr = $get(quoteIDHiddenFieldID).value + "|@WS@|" +
                       $get(customerIDHiddenFieldID).value + "|@WS@|" +    
                       $get(customerAccountTypeCodeHiddenFieldID).value + "|@WS@|" +  
                       discountedSubtotalAmount + "|@WS@|" +    
                       $get(shipResultHiddenFieldID).value + "|@WS@|" + 
                       selectedShipMethod.value;  
                       
        try
        {                       
            ShoppingCartService.GetMisShippingAndFees(inputStr, ProcessFinalTotal);
        }
        catch (err)
        {                
            // set free local shipping info
            FlipFreeLocalShipping(); 
                    
            var finalTotal = Math.round(discountedSubtotalAmount * 100) / 100;
                
            // display shipping cost
            DisplayPriceLable(totalShipCostLabelID, totalDeliveryCost, false, false);     
                   
            // shipping cost
            finalTotal += Math.round(totalDeliveryCost * 100) / 100;
                
            // fee total
            if ($get(feeTotalHiddenFieldID) != null && $get(feeTotalHiddenFieldID).value != "")
            {            
                var feeTotal = parseFloat($get(feeTotalHiddenFieldID).value);             
                if (feeTotal > 0)
                {
                    finalTotal += Math.round(feeTotal * 100) / 100;
                }
            }            
                
            // tax amount
            if ($get(taxTotalHiddenFieldID) != null && $get(taxTotalHiddenFieldID) != "")
            {
                var taxAmt = 0;
                try
                {
                    taxAmt = parseFloat($get(taxTotalHiddenFieldID).value);        
                } 
                catch (err) { }
                
                if (taxAmt > 0)
                {
                    finalTotal += Math.round(taxAmt * 100) / 100;
                }
            }
                
            // show order total
            DisplayPriceLable(totalCostLabelID, finalTotal, true, false);
            if (finialTotalHiddenFieldID && $get(finialTotalHiddenFieldID))
            {
                $get(finialTotalHiddenFieldID).value = finalTotal;
            } 
        }
    }

    // calculate fee
    function ProcessFinalTotal(result)
    {    
        var processFeeResult = result.split("|@WS@|");
        
        var feeTotalCost = 0;
        $get(feeTotalHiddenFieldID).value = feeTotalCost;
        mimAmountToFreeShip = 300;
              
        if (processFeeResult != null || processFeeResult.length >= 9)
        {
            // shipping cost changed
            if (processFeeResult[0] == "True")
            {
                if (processFeeResult[1] != "")
                {
                    var shipCost = parseFloat(processFeeResult[1]);
                    
                    if (shipCost >= 0)
                    {
                        totalDeliveryCost = parseFloat(processFeeResult[1]);
                    }
                    
                    if (normalShippingCostLabelID && $get(normalShippingCostLabelID))
                    {
                        if (shipCost >= 0)
                        {
                            DisplayPriceLable(normalShippingCostLabelID, shipCost, false, false);
                        }
                        else
                        {
                            $get(normalShippingCostLabelID).innerHTML = "$?.??";
                        }
                    }
                    
                    if ($get(shipCostHiddenFieldID) && $get(shipCostHiddenFieldID).value != "")
                    {
                        $get(shipCostHiddenFieldID).value = processFeeResult[1]; 
                    }
                    
                    // drop ship cost
                    var dropShipCost = 0;
                    if ($get(dropShipCostHiddenFieldID) && $get(dropShipCostHiddenFieldID).value != "")
                    {
                        dropShipCost = parseFloat($get(dropShipCostHiddenFieldID).value);  
                    }
                    
                    if (dropShipCost >= 0)
                    {
                        totalDeliveryCost += dropShipCost;
                    }
                }
                if (processFeeResult[2] != "")
                {
                    $get(shipResultHiddenFieldID).value = processFeeResult[2];
                }
                
                if (processFeeResult[3] != "")
                {
                    // minimun order
                    mimAmountToFreeShip = parseFloat(processFeeResult[3]);
                }
            }
            
            // small package fee
            if (processFeeResult[4] != "" && processFeeResult[5] != "" && processFeeResult[5] != "0")
            {
                var smallPkgFee = parseFloat(processFeeResult[5]);
                
                if (smallPkgFee > 0)
                {
                    $get(smallPkgFeeTableID).style.display = 'block'; 
                    $get(smallPkgFeeDescLabelID).style.display = 'block'; 
                    $get(smallPkgFeeAmtLabelID).style.display = 'block'; 
                    
                    $get(smallPkgFeeDescLabelID).innerHTML = (processFeeResult[4]);
                    DisplayPriceLable(smallPkgFeeAmtLabelID, smallPkgFee, false, false);
                    
                    if (smallPckFeeHiddenFieldID && $get(smallPckFeeHiddenFieldID))
                    {
                        $get(smallPckFeeHiddenFieldID).value = processFeeResult[5];
                    }
                    
                    feeTotalCost += Math.round(smallPkgFee * 100) / 100;
                }
            } 
            
            // customer account fee
            if (processFeeResult[6] != "" && processFeeResult[7] != "" && 
                processFeeResult[8] != "" && processFeeResult[8] != "0")
            {
                var accountFee = parseFloat(processFeeResult[8]);
                
                if (accountFee > 0)
                {
                    $get(accountFeeTableID).style.display = 'block'; 
                    $get(accountFeeDescLabelID).style.display = 'block'; 
                    $get(accountFeeAmtLabelID).style.display = 'block'; 
                    
                    $get(customerAccountFeeTypeHiddenFieldID).value = processFeeResult[6];
                    $get(accountFeeDescLabelID).innerHTML = processFeeResult[7];
                    DisplayPriceLable(accountFeeAmtLabelID, accountFee, false, false);
                    
                    if ($get(customerAccountFeeHiddenFieldID))
                    {
                        $get(customerAccountFeeHiddenFieldID).value = processFeeResult[8];
                    }
                    
                    feeTotalCost += Math.round(accountFee * 100) / 100;
                }
            }    
            $get(feeTotalHiddenFieldID).value = feeTotalCost;
            
            // recalculate tax
            CalculateTax();     
        }
                
        // set free local shipping info
        FlipFreeLocalShipping(); 
                
        var finalTotal = Math.round(discountedSubtotalAmount * 100) / 100;
        
        DisplayPriceLable(totalShipCostLabelID, totalDeliveryCost, false, false);
        
        finalTotal += Math.round(totalDeliveryCost * 100) / 100;
            
        // fee total
        if ($get(feeTotalHiddenFieldID) != null && $get(feeTotalHiddenFieldID).value != "")
        {            
            var feeTotal = parseFloat($get(feeTotalHiddenFieldID).value);             
            if (feeTotal > 0)
            {
                finalTotal += Math.round(feeTotal * 100) / 100;
            }
        }            
            
        // tax amount
        if ($get(taxTotalHiddenFieldID) != null && $get(taxTotalHiddenFieldID) != "")
        {
            var taxAmt = 0;
            try
            {
                taxAmt = parseFloat($get(taxTotalHiddenFieldID).value);        
            } 
            catch (err) { }
            
            if (taxAmt > 0)
            {
                finalTotal += Math.round(taxAmt * 100) / 100;
            }
        }
            
        // show order total
        DisplayPriceLable(totalCostLabelID, finalTotal, true, false);
        if (finialTotalHiddenFieldID && $get(finialTotalHiddenFieldID))
        {
            $get(finialTotalHiddenFieldID).value = finalTotal;
        } 
    }

    // calculat tax
    function CalculateTax()
    {
        GetQuoteDetails();
        var taxRateField = $get(taxRateHiddenFieldID);
        
        var taxRate = 0;
        if (taxRateField && taxRateField.value != "")
        {
            taxRate = parseFloat(taxRateField.value);
        }                      
                
        var resellerInfo = $get(resellerHiddenFieldID);
        var resellerTypes = new Array();
        
        /*  reseller    
                1	Food Industry
                2	Janitorial Industry
                3	Office Industry
                4	Packaging Industry
            
            Item:
                FOODI
                JANIT
                OFFIC
                PACKG
        */
        if (resellerInfo != null && resellerInfo.value != null && resellerInfo.value != "")
        {
            resellerTypes = DeSerializeResellers(resellerInfo.value)
        }
        
        var food = false;
        var janit = false;
        var offic = false;
        var packg = false;
        
        var i = 0;
        for (i = 0; i < resellerTypes.length; i ++)
        {
            if (resellerTypes[i] == "1")
            {
                food = true;
            }
            else if (resellerTypes[i] == "2")
            {
                janit = true;
            }
            else if (resellerTypes[i] == "3")
            {
                offic = true;
            }
            else if (resellerTypes[i] == "4")
            {
                packg = true;
            }
        }
        
        var taxTotal = 0;
        
        if (QuoteDetail != null && QuoteDetail.length > 0)
        {
            var oneQuoteDetail;
            var item;
            var taxable;
            for (i = 0; i < QuoteDetail.length; i ++)
            {
                oneQuoteDetail = QuoteDetail[i];
                item = DeSerializeItem(oneQuoteDetail[2]);
                
                // get final total 
                // sales discount == 0
                if ($get(normalPromotionHiddenFieldID) == null || $get(normalPromotionHiddenFieldID).value == "")
                {
                    if (parseFloat(QuoteDetail[i][7]) == 0)
                    {
                        if (parseFloat(QuoteDetail[i][6]) > 0)
                        {
                            QuoteDetail[i][10] = Math.round((parseFloat(QuoteDetail[i][4]) - parseFloat(QuoteDetail[i][6])) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                        }
                        else
                        {
                            QuoteDetail[i][10] = Math.round((Math.round(parseFloat(QuoteDetail[i][4]) * 100) / 100) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                        }
                    }
                    else
                    {
                        QuoteDetail[i][10] = Math.round((Math.round(parseFloat(QuoteDetail[i][7]) *100) / 100) * parseInt(QuoteDetail[i][3]) * 100) / 100;
                    }
                }
                
                taxable = true;
                
                if (item[11] == "FOODI")
                {
                    taxable = !food;
                }
                else if (item[11] == "JANIT")
                {
                    taxable = !janit;
                }
                else if (item[11] == "OFFIC")
                {
                    taxable = !offic;
                }
                else if (item[11] == "PACKG")
                {
                    taxable = !packg;
                }
                
                // if item is taxable, calculate tax
                if (taxable)
                {
                    QuoteDetail[i][5] = Math.round(parseFloat(QuoteDetail[i][10]) * taxRate) / 100;
                    taxTotal += parseFloat(QuoteDetail[i][5]);
                }
            }
        }
        
        if ($get(taxLabelID) != null)
        {
            if ($get(townHiddenFieldID) != null && taxRate > 0)
            {
                $get(taxLabelID).innerHTML = $get(townHiddenFieldID).value + " tax " +  taxRate + "%:";
            }
            else
            {
                $get(taxLabelID).innerHTML = "Tax:";
            }
        }
            
        // our truck delivery
        var selectedShipMethod = $get(selectedShippingTxtID);
        var shipCost = $get(shipCostHiddenFieldID);
        
        // tax on local delivery
        if (selectedShipMethod && shipCost && shipCost.value != "" && 
            taxRate > 0 && taxTotal > 0 && parseFloat(shipCost.value) > 0)
        {
            if (selectedShipMethod.value == DELIVERY_CODE_OURTRUCK ||
                selectedShipMethod.value == DELIVERY_CODE_1FEDEX_OURTRK ||
                selectedShipMethod.value == DELIVERY_CODE_1UPSOURTRK )
            {
//                taxTotal += Math.round(parseFloat(shipCost.value) * taxRate) / 100;
                taxTotal += parseFloat(shipCost.value) * taxRate / 100;
            }
        }
        
        // tax on mis fee
        var feeTotalHiddenField = $get(feeTotalHiddenFieldID);
        if (feeTotalHiddenField != null && feeTotalHiddenField.value != "" && 
            taxTotal > 0 && taxRate > 0)
        {
            var feeTotal = parseFloat(feeTotalHiddenField.value);
            
            if (feeTotal > 0)
            {
                taxTotal += Math.round(feeTotal * taxRate) / 100;
            }
        }
        
        $get(taxTotalHiddenFieldID).value = taxTotal;
        if ($get(taxAmtLabelID) != null)
        {
            if (taxTotal > 0)
            {
                DisplayPriceLable(taxAmtLabelID, taxTotal, false, false);
            }
            else
            {
                $get(taxAmtLabelID).innerHTML = "$0.00";
            }
        }
        
        SetQuoteDetails();
    }

    // add item to quote
    function AddItemToQuote()
    {        
        var inputStr = "";
            
        var customerIDHiddenField = $get(customerIDHiddenFieldID);
        var quoteIDHiddenField = $get(quoteIDHiddenFieldID);
        var itemCodeTextBox = $get(itemCodeTextBoxID);
        var itemQtyTextBox = $get(itemQtyTextBoxID);
            
        inputStr += customerIDHiddenField.value + "|@WS@|" + quoteIDHiddenField.value + "|@WS@|" + 
                        itemCodeTextBox.value+ "|@WS@|" + itemQtyTextBox.value + "|@WS@|" + isWebSalesLogIn;
        
        ShoppingCartService.AddItemToCart(inputStr, ProcessAddItem);
        return false;
    }
    
    function ProcessAddItem(result)
    {  
        // the quote is gone
        if (result == null || result == "")
        {
            $get(quoteIDHiddenFieldID).value = "";
            $get(addItemErrorLabelID).innerHTML = "Fail to add item, please try again!";
            $get(focusIDHiddenFieldID).value = itemCodeTextBoxID;
            $get(updateButtonID).click();
            return;
        }
    
        var AddItemResult = result.split("|@WS@|");
        
        if (AddItemResult.length == 1)
        {
            $get(addItemErrorLabelID).innerHTML = result;
            if (result == "Please enter valid order quantity")
            {
                $get(itemQtyTextBoxID).focus();
            }
            else
            {
                $get(itemCodeTextBoxID).focus();
            }
        }
        else
        {            
            $get(quoteIDHiddenFieldID).value = AddItemResult[1];
            $get(itemCodeTextBoxID).value = "";
            $get(itemQtyTextBoxID).value = "";
            $get(addItemErrorLabelID).innerHTML = "";
            $get(focusIDHiddenFieldID).value = itemCodeTextBoxID;
            $get(updateButtonID).click();
        }
    }


/*
* 0      quoteDetail.QuoteID
  1      quoteDetail.WarehouseID 
  2      quoteDetail.Item 
  3      quoteDetail.ItemQuantity 
  4      quoteDetail.ItemPriceBreak
  5      quoteDetail.TaxAmt
  6      quoteDetail.DiscountAmt
  7      quoteDetail.SalesDiscount
  8      quoteDetail.SalesDiscountType 
  9      quoteDetail.PercentDiscount
  10     quoteDetail.FinalTotalAmt 
*/
function GetQuoteDetails()
{
    var QuoteDetailHiddenField = $get(QuoteDetailHiddenFieldID);
    
    if (QuoteDetailHiddenField != null)
    {
        QuoteDetail = new Array();
        var detailList = QuoteDetailHiddenField.value.split("|@QuoteDetails@|");
        var i = 0;
        for (i = 0; i < detailList.length; i ++)
        {
            QuoteDetail[i] = detailList[i].split("|@OneQuoteDetail@|"); 
        }
    }
}

function SetQuoteDetails()
{
    var QuoteDetailHiddenField = $get(QuoteDetailHiddenFieldID);
    var quoteStr = "";
    
    var i = 0;
    var j = 0;
    var oneDetail;
    for (i = 0; i < QuoteDetail.length; i ++)
    {
        oneDetail = QuoteDetail[i];
        if (oneDetail.length >= 11)
        {
            for (j = 0; j < oneDetail.length; j ++)
            {
                quoteStr += oneDetail[j];
                
                if (j != oneDetail.length - 1)
                {
                    quoteStr += "|@OneQuoteDetail@|";
                }
            }
            if (i < QuoteDetail.length - 1 )
            {
                quoteStr += "|@QuoteDetails@|";
            }
        }
    }
    QuoteDetailHiddenField.value = quoteStr;
}

// display price label
function DisplayPriceLable(LabelID, Price, Bold, Negitive)
{
    if (!$get(LabelID))
    {
        return;
    }

    var priceStr = (Math.round(Price * 100) / 100).toString();
    var reversePriceStr = priceStr.split("").reverse().join("");
    
    var decIndex = reversePriceStr.indexOf(".");
    
    if (decIndex < 0)
    {
        reversePriceStr = "00." + reversePriceStr;
    }
    else
    {
        if (decIndex == 0)
        {
            reversePriceStr = "00" + reversePriceStr;
        }
        else
        {
            if (decIndex == 1)
            {
                reversePriceStr = "0" + reversePriceStr;
            }
        }
    }
    
    priceStr = "$" + reversePriceStr.split("").reverse().join("");
    
    if (Negitive)
    {
        priceStr = "- " + priceStr;
    }
    
    if (Bold)
    {
        $get(LabelID).innerHTML = "<b>" + priceStr + "</b>";
    }
    else
    {
        $get(LabelID).innerHTML = priceStr;
    }
}

function ShowQuoteDetail(QuoteDetailHiddenFieldID)
{
    GetQuoteDetails(QuoteDetailHiddenFieldID);
    var i = 0;
    var j = 0;
    var item;
    for (i = 0; i < QuoteDetail.length; i ++)
    {
        for (j = 0; j < QuoteDetail[i].length; j ++)
        {
            if (j == 2)
            {
                item = DeSerializeItem(QuoteDetail[i][j]);
                $get('testSpan').innerHTML += item[0] + " | ";
            }
            else
            {
                $get('testSpan').innerHTML +=QuoteDetail[i][j] + " | ";
            }
        }
            $get('testSpan').innerHTML +="<br>";
    } 
}

// delivery type code
var DELIVERY_CODE_OURTRUCK = "ORTRK";
var DELIVERY_CODE_WILLCALL = "WLLCL";
var DELIVERY_CODE_DROPSHIP = "SHMRK";
var DELIVERY_CODE_NORMAL_DROPSHIP = "DROPS";
var DELIVERY_CODE_1FREIGHT = "FRGHT";

var DELIVERY_CODE_1FEDEX_ECONO = "ECONO";
var DELIVERY_CODE_1ECONO = "ECON1";
var DELIVERY_CODE_PRIORITY_MAIL = "RPIML";

var DELIVERY_CODE_1AFEDEXOURTRK = "AFXTK";
var DELIVERY_CODE_1FEDEX_OURTRK = "FXTRK";
var DELIVERY_CODE_1FEDEX_GROUND = "FXGRD";
var DELIVERY_CODE_1FEDEX_EXPRSSAVR = "FX3DY";
var DELIVERY_CODE_1FEDEX_2DAY = "FX2DY";
var DELIVERY_CODE_1FEDEX_STDOVRNIT = "FX1PM";
var DELIVERY_CODE_1FEDEX_PRIOVRNIT = "FX1AM";
var DELIVERY_CODE_1FEDEX_INTLSGRND = "FXSTI";
var DELIVERY_CODE_1FEDEX_INTLECONO = "FXECI";

var DELIVERY_CODE_1UPSOURTRK = "UPTRK";
var DELIVERY_CODE_1UPSGROUND = "UPGRD";
var DELIVERY_CODE_1AUPSOURTRK = "AUPTK";
var DELIVERY_CODE_1UPSRED_MAIL = "UP1DY";
var DELIVERY_CODE_1UPSBLUE_MAIL = "UP2DY";
var DELIVERY_CODE_1UPS3DAY_MAIL = "UP3DY";

var DELIVERY_CODE_NOT_AVAILABLE = "NA";

var DELIVERY_CODE_SAME_DAY_SERVICE = "SMDSV";

// customer account type code
var ACCOUNT_TYPE_COD = "CODCA";
var ACCOUNT_TYPE_OPEN_ACCOUNT = "OPENA";
var ACCOUNT_TYPE_AMERICAN_EXPRESS = "AMEXC";
var ACCOUNT_TYPE_MASTER = "MASTC";
var ACCOUNT_TYPE_VISA = "VISAC";
var ACCOUNT_TYPE_CREDIT_CARD = "CCARD";
var ACCOUNT_TYPE_CASH = "CASHA";
var ACCOUNT_TYPE_UNKNOWN = "NONE";