﻿/* CartManagement.js */

var cartPopupSuccessMessage = "";
var CartPreferenceSettings = function()
{
    this._priceType = "NotSet"; //null "Actual"; "Distributor";
    this._sortOrder = null;
    this._popupId = "";
    this.cartContainer = "";
    this._cartDefined = false;
    this._listOwner = '';
}

var shoppingCart = new Object();
var cartPreferenceSettings = new CartPreferenceSettings();
var testFlag = false;
var lastItem = '';

//***********Add item to cart***********//
var CartItem = function(cartControl)
{
    this._cartControl = cartControl;
    this._lineItem = null;

    this._isJustAdded = function()
    {
        return ((justAdded != undefined || justAdded != null) && justAdded == true);
    }

    this.addItems = function(itemNumbers, value)
    {
        var thisRef = this;
        var itemNumber = ($get(thisRef._cartControl.tbxItemNumber).value).replace(/^\s+|\s+$/g, '');

        if ($get(thisRef._cartControl.tbxQuantity) == null || $get(thisRef._cartControl.tbxQuantity).value == '')
        {
            if (this._cartControl.DestinationType == "Ditto")
            {
                $get(thisRef._cartControl.tbxQuantity).value = 0
            }
            else
            {
                $get(thisRef._cartControl.tbxQuantity).value = 1
            }
        }
        // Ditto can have a quantity of zero (unlike shopping cart)
        if ($get(thisRef._cartControl.tbxQuantity) != null && ($get(thisRef._cartControl.tbxQuantity).value > 0 || this._cartControl.DestinationType == "Ditto"))
        {
            addItemSpinner.show();
            //get Product info
            Ajax.timeoutPeriod = 15000;

            Amway.Core.Web.UI.Cart.CartControl.GetProduct(itemNumber, cartPreferenceSettings._listOwner, function(response)
            {
                if (response.value != null && response.value.IsItemFound)
                {
                    thisRef._lineItem = response.value;

                    var itemDTO = {};

                    //validate item
                    var isValid = thisRef._lineItem.IsItemFound;

                    // an item that is not available is allowed in a receipt
                    var isAllowNotAvailable = (thisRef._cartControl.DestinationType == "SalesReceipt");

                    //set qty
                    itemDTO.Quantity = $get(thisRef._cartControl.tbxQuantity).value;

                    //use the item number returned from service not the user entered itemnumber
                    itemDTO.ItemNumber = thisRef._lineItem.ItemNumber;
                    itemDTO.PriceType = cartPreferenceSettings._priceType;

                    if (thisRef._lineItem.Pricing != null && thisRef._lineItem.Pricing.length > 0)
                        itemDTO.PriceAmount = thisRef._lineItem.Pricing[0].SuggestedRetail;

                    //Disallow and IsPersonalizedHealthSkus
                    if (isValid)
                    {
                        if (thisRef._lineItem.IsPersonalizedHealthSku)
                        {
                            isValid = false;
                            thisRef.displayErrorMessage(NotOrderable);
                        }
                    }

                    //validate IsOrderable
                    if (isValid)
                    {
                        if (!thisRef._lineItem.IsOrderable)
                        {
                            isValid = false;
                            thisRef.displayErrorMessage(NotOrderable);
                        }
                    }

                    //validate availablity
                    if (isValid)
                    {
                        //TODO: some items may be orderable even if not IsAvailable (AO/BO?)
                        if (!thisRef._lineItem.IsAvailable && !isAllowNotAvailable)
                        {
                            isValid = false;
                            if ((typeof thisRef._lineItem.AvailabilityInfo == 'object') && (thisRef._lineItem.AvailabilityInfo.Message.length > 0))
                            {
                                thisRef.displayErrorMessage(thisRef._lineItem.AvailabilityInfo.Message);
                            }
                            else
                            {
                                thisRef.displayErrorMessage(NotOrderable);
                            }
                        }
                    }

                    //validate size color input
                    if (isValid)
                    {
                        var sizeColorCollection = thisRef._lineItem.SizeColor;

                        if (sizeColorCollection != null && sizeColorCollection.length != null && sizeColorCollection.length > 0)
                        {
                            var SizeColorDDL = document.getElementById(thisRef._cartControl.ddlSizeColor);

                            //missing item info feteching from getitem
                            if (SizeColorDDL.length == 0)
                            {
                                //size color info missing call get to populate item info
                                thisRef.updateItem(ProductPopupID, ProductPopupURL);
                                thisRef.updateAvailability();
                                thisRef.updateSizeColorDropDowm();
                                SizeColorSelectedOption = "0";
                                lastItem = itemNumber;

                            }
                            else
                            {
                                var SizeColorSelectedOption = SizeColorDDL.options[SizeColorDDL.selectedIndex].value;
                            }

                            if (SizeColorSelectedOption == "0" || SizeColorSelectedOption == "")
                            {
                                isValid = false;
                                thisRef.displayErrorMessage(MissingSizeColor);
                            }
                            else
                            {
                                itemDTO.SizeCode = SizeColorSelectedOption;
                                itemDTO.ColorCode = SizeColorSelectedOption;
                                // Update the item number to reflect the selection.
                                itemDTO.ItemNumber = SizeColorSelectedOption;
                            }
                        }
                    }

                    //adding item to a collection because no overloaded method exists to add individual items
                    var itemColl = new Array();
                    itemColl[0] = itemDTO;

                    if (isValid)
                    {
                        var destinationId = null;
                        var organizationID = null;
                        if (DestinationType == "SalesReceipt")
                        {
                            if (typeof (hdnTransactionId) != "undefined")
                            {
                                destinationId = document.getElementById(hdnTransactionId).value;
                            }
                            organizationID = cartPreferenceSettings._listOwner;
                        }
                        if ((DestinationType === "Ditto" || DestinationType === "ShoppingList") && typeof (hdnProfileId) != "undefined" && typeof (hdnOrganizationID) != "undefined")
                        {
                            destinationId = document.getElementById(hdnProfileId).value;
                            organizationID = document.getElementById(hdnOrganizationID).value;
                        }
                        Amway.Core.Web.UI.Cart.CartAddItemController.AddItems(itemColl, DestinationType, destinationId, organizationID, function(response)
                        {
                            var error;
                            if (response.error != null || response.value == null)
                            {
                                error = ErrorMessage;
                            }
                            else
                            {
                                error = response.value;
                            }
                            PopulateCartLineItemControls(DestinationType, error, thisRef);
                        });
                    }
                }
                else
                {
                    thisRef.displayErrorMessage(NotOrderable);
                }
                addItemSpinner.hide();
            }, null, null, null, cartajaxAdd_ontimeout);
        }
        else
        {
            thisRef.clearAddItemControl(true);
        }
        return false;
    }

    this.getItem = function(itemNumber, popupId, url)
    {
        var thisRef = this;
        itemNumber = ($get(thisRef._cartControl.tbxItemNumber).value).replace(/^\s+|\s+$/g, '');
        if (itemNumber != null && itemNumber != "" && lastItem != itemNumber)
        {
            thisRef.clearAddItemControl(false);
            addItemSpinner.show();
            //sanitize input here?
            Ajax.timeoutPeriod = 15000;
            //Ajax.onError = function(res) { HandleException(res); }

            Amway.Core.Web.UI.Cart.CartControl.GetProduct(itemNumber, cartPreferenceSettings._listOwner, function(response)
            {
                if (response.value != null && response.value.IsItemFound)
                {
                    thisRef._lineItem = response.value;
                    thisRef.updateItem(popupId, url);
                    thisRef.updateAvailability();
                    thisRef.updateSizeColorDropDowm();

                    if (thisRef._lineItem.ItemNumber != itemNumber && thisRef._lineItem.ItemNumber != null && !thisRef._lineItem.IsSizeColor)
                    {
                        $get(thisRef._cartControl.tbxItemNumber).value = thisRef._lineItem.ItemNumber;
                    }

                    lastItem = $get(thisRef._cartControl.tbxItemNumber).value;

                    if (thisRef._lineItem.IsPersonalizedHealthSku)
                    {
                        thisRef.displayErrorMessage(NotOrderable);
                    }
                    else
                    {
                        $get(thisRef._cartControl.lblErrorMessage).style.display = 'none';
                        //errorMsg.Show(false);
                    }
                }
                else
                {
                    thisRef.displayErrorMessage(NotOrderable);
                }
                addItemSpinner.hide();
            }, null, null, null, cartajaxGet_ontimeout);

        }
        return false;
    }

    this.updateItem = function(popupId, url)
    {
        //Update the link to show a popup
        var lnk = $('#' + this._cartControl.quickViewLink);
        var thisRef = this;
        lnk.bind("click", { popup: popupId, navUrl: url }, function(e)
        {
            showProductQuickView(thisRef._lineItem.ItemNumber, thisRef._cartControl.quickViewContent, thisRef._cartControl.quickViewLink, e.data.navUrl, e.data.popup);
        });

        var lbl = $get(this._cartControl.productNameLabel);

        if (this._lineItem.ItemName == null || this._lineItem.ItemName == "")
        {
            lnk.html(this._lineItem.ItemNumber);
            if (lbl != null)
            {
                lbl.innerHTML = this._lineItem.ItemNumber;
            }
        }
        else
        {
            lnk.html(this._lineItem.ItemName);
            if (lbl != null)
            {
                lbl.innerHTML = this._lineItem.ItemName;
            }
        }

        var qty = $get(this._cartControl.tbxQuantity);

        // The default quantity for DITTO is 0
        if (qty.value == '')
        {
            if (this._cartControl.DestinationType == "Ditto")
            {
                qty.value = 0;
            }
            else
            {
                // TFS 39610: Per user feedback, if the value is already empty,
                // leave it that way and do not default it clientside.  That way,
                // the user is able to type in any value they desire.
                ////qty.value = this._lineItem.Quantity;
            }
        }
    }

    this.updateAvailability = function()
    {
        if (this._lineItem.AvailabilityInfo != null && this._lineItem.AvailabilityInfo.Message.length != null && this._lineItem.AvailabilityInfo.Message.length > 0)
        {
            $get(this._cartControl.lblAvailability).style.display = '';
            $get(this._cartControl.lblAvailability).innerHTML = this._lineItem.AvailabilityInfo.Message;
            $get(this._cartControl.usrHlpAvailability).style.display = 'inline';
        }
        else
        {
            $get(this._cartControl.lblAvailability).style.display = 'none';
            $get(this._cartControl.lblAvailability).innerHTML = '';
            $get(this._cartControl.usrHlpAvailability).style.display = 'none';
        }
    }

    this.updateSizeColorDropDowm = function()
    {
        if (this._lineItem.IsSizeColor)
        {
            var SizeColorDDL = document.getElementById(this._cartControl.ddlSizeColor);
            SizeColorDDL.style.display = 'inline';

            var lblSizeColor = document.getElementById(this._cartControl.lblSizeColorHead);
            lblSizeColor.style.display = 'inline';

            var sizeColorCollection = this._lineItem.SizeColor;

            if (sizeColorCollection.length != null && sizeColorCollection.length > 0)
            {
                clearDropDownList(SizeColorDDL);

                addOption(SizeColorDDL, SelectOne, '0');

                for (var i = 0; i < sizeColorCollection.length; i++)
                {
                    addOption(SizeColorDDL, sizeColorCollection[i].DisplayName, sizeColorCollection[i].ProductId);
                }
            }
        }
    }

    this.clearAddItemControl = function(clearItemNum)
    {
        if (clearItemNum)
        {
            $get(this._cartControl.tbxItemNumber).value = '';
            $get(this._cartControl.tbxItemNumber).focus();
        }
        //clear additem control
        var SizeColorDDL = document.getElementById(this._cartControl.ddlSizeColor);
        clearDropDownList(SizeColorDDL);
        SizeColorDDL.style.display = 'none';
        var lblSizeColor = document.getElementById(this._cartControl.lblSizeColorHead);
        lblSizeColor.style.display = 'none';
        $get(this._cartControl.tbxQuantity).value = '';
        $get(this._cartControl.lblAvailability).innerHTML = '';
        $get(this._cartControl.usrHlpAvailability).style.display = 'none';
        $('#' + this._cartControl.quickViewLink).html('');
        var lbl = $get(this._cartControl.productNameLabel);
        if (lbl != null)
        {
            lbl.innerHTML = '';
        }
        $get(this._cartControl.lblAvailability).style.display = 'none';
        $get(this._cartControl.lblErrorMessage).innerHTML = '';
        $get(this._cartControl.lblErrorMessage).style.display = 'none';
        errorMsg.Show(false);
        lastItem = '';
    }

    this.displayErrorMessage = function(messageText)
    {
        //donot show the link or availability message while displaying an error
        $('#' + this._cartControl.quickViewLink).html('');
        var lbl = $get(this._cartControl.productNameLabel);
        if (lbl != null)
        {
            lbl.innerHTML = '';
        }
        $get(this._cartControl.lblAvailability).style.display = 'none';
        $get(this._cartControl.usrHlpAvailability).style.display = 'none';
        addItemSpinner.hide();
        $get(this._cartControl.lblErrorMessage).innerHTML = messageText;
        $get(this._cartControl.lblErrorMessage).style.display = 'inline';
        $get(this._cartControl.tbxItemNumber).focus();
        $get(this._cartControl.tbxItemNumber).select();
    }

    this.displayDomainErrorMessage = function(messageText)
    {
        addItemSpinner.hide();
        errorMsg.DisplayMsg(AmwayNotificationType.Error, messageText);

        //if error occurs scroll to top of window
        window.scrollTo(0, 0);
    }


    this.updateLineItems = function()
    {
        //TODO : verify if this the method to call
        RefreshLineItemControl(cartPreferenceSettings._sortOrder);
    }

    this.updateOrderSummary = function()
    {
        //Call to order sumary moved to RefreshLineItemControl
    }

    this.sizecoloronchange = function(popupId, url)
    {
        var thisRef = this;
        thisRef.updateItem(popupId, url);
        $get(this._cartControl.lblErrorMessage).innerHTML = '';
        $get(this._cartControl.lblErrorMessage).style.display = 'none';
    }
}

function cartajaxAdd_ontimeout(span, ajaxResponse)
{
    __doPostBack('', '');
}

function cartajaxGet_ontimeout(span, ajaxResponse)
{
    if (DestinationType && DestinationType === "ShoppingList" && typeof errorMsg == "object")
    {
        errorMsg.DisplayMsg(AmwayNotificationType.Error, AjaxTimeoutMessage);
        addItemSpinner.hide();
    }
    else
    {
        addItemSpinner.hide();
        alert(AjaxTimeoutMessage);
    }
}

function clearDropDownList(selectbox)
{
    //clear the dropdown values
    //for (i = 0; i < selectbox.options.length; i++) {
    //Note: Always remove(0) and NOT remove(i)
    //	selectbox.remove(0)
    //}
    selectbox.options.length = 0;
}

function addOption(selectbox, text, value)
{
    var optn = document.createElement("option");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function CheckForCartViewPostbackRequired()
{
    // Here we will check to see if anything items were added to the cart.  If there were items added and the variable rebootIfItemsArePresent is defined, we need to do a postabck
    if (typeof lineItemContainer == "string" && typeof doPostbackIfItemsArePresent == "string")
    {
        var lineItems = document.getElementById(lineItemContainer);
        if (lineItems != null && lineItems.firstChild != null)
        {
            __doPostBack('', '');
        }
    }
}
function UpdatePriceType(cbxSetBagPrice, cartContainerId, popupInfo, ddlSortBy)
{
    cartPreferenceSettings._priceType = cbxSetBagPrice.value;

    var answer = confirm(popupInfo.content);

    if (answer)
    {
        Amway.Core.Web.UI.Cart.CartControl.UpdatePriceType(cartPreferenceSettings._priceType, function(response)
        {
            if (response.error != null)
            {
                //alert('Update price failed');
            }
            else
            {
                //alert('Update price succeeded, about to sort');
                RefreshLineItemControl(GetDdlValue(ddlSortBy));
            }
        });
    }
    else
    {
        cbxSetBagPrice.selectedIndex = prevIboSelectedIndex;
    }


    return true;
}

var prevIboSelectedIndex = 0;
function BindIboChange(cbxIbo)
{
    $("select#" + cbxIbo + " option").bind("mouseup", function(event)
    {
        prevIboSelectedIndex = event.currentTarget.selectedIndex;
    });
}

function showProductQuickView(itemNum, content, lnk, url, popupId)
{
    return ShowProductQuickView(popupId, url + itemNum, lnk, 615, 600, QuickViewTitle);
}

//***********Refresh Line item control***********//
function RefreshLineItemControl(sortField, callback)
{
    cartSpinner.show();
    cartError.clear();
    RefreshSummaryControl();

    Amway.Core.Web.UI.Cart.ViewCartControl.RefreshLineItemControl(sortField, cartPreferenceSettings._popupId, function(response)
    {
        var showErrorMessage = false;
        if (response.error == null)
        {
            if (response.value != null)
            {
                // on rare circumstances, the response is empty and it should not be.  But if it is, the solution is to refresh the page
                if (response.value == '')
                {
                    window.location = window.location;  // Does a postback
                }
                else
                {
                    // Set the inner html property of the place holder control to show the latest changes.
                    var holderControl = $get(lineItemContainer);
                    holderControl.innerHTML = response.value;
                    RunEmbeddedScripts(holderControl);
                    updateCartCount(callback);
                }
            }
            else
            {
                showErrorMessage = true;
            }
        }
        else
        {
            showErrorMessage = true;
        }

        // Show the error message.
        if (showErrorMessage == true)
        {
            // $get(shoppingCart.lblErrorMsg).innerHTML = response.error;
        }

        cartSpinner.hide();
    });
}

function RunEmbeddedScripts(htmlFragment)
{
    var scriptElem = $(htmlFragment).find("div.hiddenScript");
    var currElem;
    if (scriptElem.length == 1)
    {
        eval(scriptElem.html());
        scriptElem.empty();
    }
    else if (scriptElem.length > 1)
    {
        for (var index = 0; index < scriptElem.length; )
        {
            var elem = $(scriptElem[index]);
            eval(elem.html());
            elem.empty();
            index = index + 1;
        }
    }
}

function ImageVisibility(showHideText, idOfContainer, lblTextObj)
{
    //cartSpinner.show();
    document.body.style.cursor = "wait";
    var phraseText = eval('(' + lblTextObj + ')');
    var showImage = Amway.Core.Web.UI.Cart.CartControl.GetImageVisibilityPreference();
    var images = $("#" + idOfContainer + " tr td.MC_LYT_FirstItem img");
    if (showImage.value === true)
    {
        for (var i = 0; i < images.length; i++)
        {
            // Don't hide the toggle image for child items
            if (images[i].id.indexOf("imgSkuToggle") < 0)
            {
                if (images[i].alt == "?")
                {
                    images[i].style.display = 'block';
                }
                else
                {
                    images[i].style.display = 'none';
                }
            }
        }
        $(showHideText).text(phraseText.Show);
    }
    else
    {
        for (var i = 0; i < images.length; i++)
        {
            // Don't hide the toggle image for child items
            if (images[i].id.indexOf("imgSkuToggle") < 0)
            {
                images[i].style.display = 'block';
            }
        }
        $(showHideText).text(phraseText.Hide);
    }
    if (typeof showImage.value === "boolean")
    {
        //var waitForSave = Amway.Core.Web.UI.Cart.CartControl.SetImageVisibilityPreference(!showImage.value);
        Amway.Core.Web.UI.Cart.CartControl.SetImageVisibilityPreference(!showImage.value, ImageVisibilityCallback, null, null, null, ItemListTimeout);
    }
    //cartSpinner.hide();
    return false;
}

function ImageVisibilityCallback(ajaxResponse)
{
    document.body.style.cursor = "default";
    // TODO: Check ajaxResponse.error here
}

// Show / hide product thumbnails in the line item control
function ShowCartThumbnails(showHideTextObj)
{
    document.body.style.cursor = "wait";

    var phraseText = eval('(' + showHideTextObj + ')');
    var showImage = Amway.Core.Web.UI.Cart.CartControl.GetImageVisibilityPreference();
    var cartThumbnails = document.getElementsByTagName("img");
    var showHideLinks = document.getElementsByTagName("a");

    for (i = 0; i < cartThumbnails.length; i++)
    {
        if (cartThumbnails[i].attributes.getNamedItem("amwayImageType") && cartThumbnails[i].attributes.getNamedItem("amwayImageType").value == "cartthumbnail")
        {
            if (showImage.value === true)
            {
                cartThumbnails[i].style.display = 'none';
            }
            else
            {
                cartThumbnails[i].style.display = 'inline';
            }
        }
    }

    for (i = 0; i < showHideLinks.length; i++)
    {
        if (showHideLinks[i].id.indexOf("lnkBtnHideImages") >= 0)
        {
            if (showImage.value === true)
            {
                showHideLinks[i].innerHTML = phraseText.Show;
            }
            else
            {
                showHideLinks[i].innerHTML = phraseText.Hide;
            }
        }
    }

    if (typeof showImage.value === "boolean")
    {
        Amway.Core.Web.UI.Cart.CartControl.SetImageVisibilityPreference(!showImage.value, ShowCartThumbnailsCallback, null, null, null, ItemListTimeout);
    }
    return false;
}

function ShowCartThumbnailsCallback(ajaxResponse)
{
    document.body.style.cursor = "default";
    // TODO: Check ajaxResponse.error here
}

function ItemListTimeout()
{
    document.body.style.cursor = "default";
    //document.forms[0].submit();
}

//Check all javascript
function SelectLineItems(allCheckBox, idOfContainer)
{
    $("#" + idOfContainer + " input[type='checkbox']:enabled").attr('checked', allCheckBox.checked);
}

//Check if all line items were selected
function AreAllLineItemsSelected(idOfContainer)
{
    var checkboxes = $("#" + idOfContainer + " input[type='checkbox']:enabled")
    var index = 0;
    var correctName = "cbxSelection";  // All valid check boxes will have their name end with this string
    var allAreSelected = true;  // Assume true unless we find an item that is not selected
    for (index = 0; index < checkboxes.length; index++)
    {
        var chkbox = checkboxes[index];
        if ((correctName.length < chkbox.name.length)
        && (chkbox.name.substring(chkbox.name.length - "cbxSelection".length) == "cbxSelection")
        && (!chkbox.checked))
        {
            // This is a valid checkbox and it was not selected
            allAreSelected = false;
            break;
        }
    }

    return allAreSelected;
}

function CheckAllLineItemsSelected(lineItemCheckBox, allCheckedCheckBoxId, idOfContainer)
{
    if (lineItemCheckBox != null) // && !lineItemCheckBox.checked)
    {
        if (typeof idOfContainer == "string")
        {
            var allCheckedCheckBox = document.getElementById(allCheckedCheckBoxId);

            if (allCheckedCheckBox != null)
            {
                // Keep the "All" checkbox in sync with the line item checkboxes:
                allCheckedCheckBox.checked = AreAllLineItemsSelected(idOfContainer);
            }
        }
    }
}

//Check all javascript
function CheckChanged()
{
    __doPostBack('', '');
}

function ReloadOnEmpty(itemCount)
{
    if (itemCount == 0)
    {
        window.location = window.location;
    }
}

function RemoveLineItem(lnkRemove, lineItemId, ddlSortBy)
{
    var parentNode = $(lnkRemove.parentNode.parentNode.parentNode);
    var itemColl = new Array();

    itemColl[0] = {};
    var itemId = $get(lineItemId).value.split(',');
    itemColl[0].LineItemId = itemId[0];
    itemColl[0].ItemNumber = itemId[1];
    itemColl[0].IsDeleted = true;

    Amway.Core.Web.UI.Cart.CartControl.UpdateItems(itemColl, function(response)
    {
        if (response.error != null)
        {
            //TODO : There was an error processing the request.
            //alert('Update failed ' + response.error);
        }
        else if (response.value !== null)
        {
            //TODO : How to let user know this operation succeeded?
            //alert('Updated');
            parentNode.remove();
            //TODO : RefreshLineItemControl(GetDdlValue(ddlSortBy));
            RefreshLineItemControl(GetDdlValue(ddlSortBy), ReloadOnEmpty);
        }
    });

    return false;
}

function isControlChar(keyCode)
{
    return (keyCode < 41 || keyCode == 27 || keyCode == 127 || keyCode == 46);
}

function UpdateQuantity(txtQty, lineItemId, ddlSortBy, errLabel)
{
    var oldVal = $(txtQty).attr('oldval');
    if (oldVal === undefined)
    {
        oldVal = '';
    }

    var itemId = document.getElementById(lineItemId).value.split(',');
    var qty = parseInt($(txtQty).val(), 10);

    if (isNaN(qty) || qty < 1)
    {
        $('#' + errLabel).css('display', 'block');
        $(txtQty).val(oldVal);
        $(txtQty).trigger('focus');
        return false;
    }

    $('#' + errLabel).css('display', 'none');

    if (oldVal != $(txtQty).val())
    {
        if (typeof DestinationType !== 'undefined' && DestinationType == "SalesReceipt")
        {
            $(txtQty).attr('oldval', $(txtQty).val());
            UpdateSalesReceiptLineItems(itemColl, GetDdlValue(ddlSortBy));
        }
        else
        {
            Amway.Core.Web.UI.Cart.CartControl.UpdateItem(itemId[0], '', 0, qty, function(response)
            {
                if (response.error != null)
                {
                    //TODO : There was an error processing the request.
                    //alert('Update failed ' + response.error);
                }
                else if (response.value != null)
                {
                    //TODO : How to let user know this operation succeeded?
                    $(txtQty).attr('oldval', $(txtQty).val());
                    RefreshLineItemControl(GetDdlValue(ddlSortBy));
                }
            });
        }
    }
}

function PriceFormatter(prefix, suffix)
{
    var _prefix = prefix;
    var _suffix = suffix;

    this.Format = function(price)
    {
        var formattedPrice = '';
        if (isNaN(price))
        {
            price = parseFloat(price);
        }
        if (!isNaN(price) && isFinite(price))
        {
            try
            {
                if (typeof price === "string")
                {
                    price = parseFloat(price);
                }
                price = parseFloat(price.toFixed(2));
            }
            catch (e)
            {
                //do nothing. this is an odd bug
            }
            if (price % 100 === 0)
            {
                formattedPrice = _prefix + price + _suffix;
            }
            else
            {
                formattedPrice = _prefix + price;
            }
        }
        return formattedPrice;
    }
}
var priceFormatter;

function UpdateSelectedPrice(ddlPrice, tbxIboPrice, ddlSortBy, lineItemId, validationObj, txtQty, spnDiscountPrice)
{
    if (ddlPrice.selectedIndex > -1)
    {
        var priceType;
        var price = 0;
        var canUpdate = true;
        var txtBox = document.getElementById(tbxIboPrice);
        var data = ddlPrice.value.split("~");
        priceType = data[0];

        // NOTE: Price I Determine will not have a second data element.
        if (data.length > 1)
        {
            price = data[1];
            if (spnDiscountPrice != '')
            {
                var help = document.getElementById(spnDiscountPrice);
                help.style.display = "none";
            }
        }
        else
        {
            if (spnDiscountPrice != '')
            {
                var help = document.getElementById(spnDiscountPrice);
                help.style.display = "inline";
            }
            canUpdate = false;
            txtBox.style.display = "block";
            txtBox.value = priceFormatter.Format(validationObj.customPrice);

            try
            {
                txtBox.focus();
            }
            catch (ex)
            {
            }
        }

        // Do not save the record if they selected "Price I Determine".  We must wait until they actually enter in the new price.
        if (canUpdate === true)
        {
            txtBox.style.display = 'none';
            UpdatePrice(document.getElementById(lineItemId).value, price, priceType, GetDdlValue(ddlSortBy), $get(txtQty).value);
        }
    }
}

function GetDdlHtml(ddl)
{
    if (ddl.options == null)
        ddl = document.getElementById(ddl);
    return ddl.options[ddl.selectedIndex].innerHTML;
}

function GetDdlValue(ddl)
{
    if (ddl.options == null)
        ddl = document.getElementById(ddl);
    return ddl.options[ddl.selectedIndex].value;
}

function ValidatePrice(event, validationObj) {
    if (window.event && event.keyCode === 13) {
        return false; //needed since IE treats an enter in the text box as a form submit
    }

    if (window.event) {
        event = window.event;
    }
    // Attempt to allow function keys, and edit keys
    if (event.charCode == 0) { return; }

    var keynum = 0;
    if (event.keyCode) {
        keynum = event.keyCode;
    } else if (event.which) {
        keynum = event.which;
    }

    // Checking for 31 and 127 is for Apple devices which don't get blocked above when backspace character (8) is typed.
    if (keynum <= 31 || keynum == 127) { return; }

    var keychar = String.fromCharCode(keynum);
    var numcheck = /[\$\.\d]/;

    var isValid = ((keynum == undefined) || numcheck.test(keychar));

    if (validationObj != undefined && validationObj.lblErr != undefined) {
        if (isValid) {
            $('#' + validationObj.lblErr).css("display", "none");
        }
        else {
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
            $('#' + validationObj.lblErr).html(validationObj.formatErr);
        }
    }

    return isValid;
}

function UpdateIboDeterminedPrice(tbxItemPrice, lineItemId, ddlPrice, ddlSortBy, validationGrp, validationObj, txtQty)
{
    var errorLbl = $('#' + validationObj.lblErr);
    errorLbl.css("display", "none");

    var price = (Number)(tbxItemPrice.value.trim().replace('$', ''));
    if (isNaN(price) || price == 0)
    {
        showError(validationObj.formatErr);
    }
    else
    {
        price = parseFloat(price.toFixed(2));
        tbxItemPrice.value = priceFormatter.Format(price);
        var lowerPrice = parseFloat((validationObj.iboPrice).toFixed(2));
        var upperPrice = parseFloat((validationObj.iboPrice * 4.6).toFixed(2));

        if (price >= lowerPrice && price <= upperPrice)
        {
            if (typeof price == "string")
            {
                price = parseFloat(price);
            }
            cartError.removeError(tbxItemPrice.id);
            UpdatePrice($('#' + lineItemId).val(), price, validationObj.actualType, GetDdlValue(ddlSortBy), $get(txtQty).value);
        }
        else
        {
            showError(validationObj.rangeErr);
        }
    }

    function showError(errorText)
    {
        errorLbl.css("display", "block");
        errorLbl.html(errorText);
        tbxItemPrice.focus();
        cartError.addError(errorLbl.attr('id'));
    }
}

function UpdatePrice(itemId, price, priceType, sortBy, qty)
{
    itemId = itemId.split(',');
    price = price * 1;
    qty = qty * 1;

    if (typeof (DestinationType) != "undefined" && DestinationType == 'SalesReceipt')
    {
        UpdateSalesReceiptLineItems(itemColl);
    }
    else
    {
        Amway.Core.Web.UI.Cart.CartControl.UpdateItem(itemId[0], priceType, price, qty, function(response)
        {
            if (response.error != null)
            {
                //alert('Update price failed');
            }
            else if (response.value != null)
            {
                //alert('Update price succeeded, about to sort');
                RefreshLineItemControl(sortBy);
            }
        });
    }
}

function SortLineItems(ddlSortBy)
{
    //Which one to use?
    //RefreshLineItemControl(ddlSortBy.options[ddlSortBy.selectedIndex].value);
    var sortPhraseId = GetDdlValue(ddlSortBy);
    cartPreferenceSettings._sortOrder = sortPhraseId;
    Amway.Core.Web.UI.Cart.CartControl.SetSortPreference(sortPhraseId, function(response)
    {
        if (response.error == null)
        {
            RefreshLineItemControl(sortPhraseId);
        }
    });
}

//***********Line item control***********//

//***********************Mini Bag**************************//
//**Note: Mini Bag will now be hidden as part of CR 668 and CR 292*********//
var MiniBag = function()
{
    var _dialog = null;
    var _element = null;
    var _justAdded = false;
    var _bagParent;

    this.DialogOpen = function(e)
    {
        if (_dialog == null)
        {
            _initDialog(e.data);
        }
    }

    this.ProceedToCheckout = function(e, url)
    {
        if (_dialog != null)
        {
            _dialog.close();
            if (typeof url === "string")
            {
                window.location = url;
            }
        }
    }

    this.CloseMiniBag = function(e)
    {
        if (_dialog != null)
        {
            _dialog.close();
        }
    }

    this.AddToCart = function(items, callbackFunc)
    {
        //Commented Shopping bag as part of the CR 668 and CR 292
        if (isNullOrUndefined(items))
        {
            items = new Array();
        }

        for (i = 0; i < items.length; i++)
        {
            items[i].PriceType = ""; // Per Nick, the service layer will make the correct determination of the price type.  This approach is only valid for the Product pages only.
            items[i].IsDefaultPriceType = false;
        }

        var controller = Amway.Core.Web.UI.Cart.CartAddItemController || top.Amway.Core.Web.UI.Cart.CartAddItemController;

        controller.AddItems(items, "ShoppingCart", "", "", function(response)
        {
            if (response.error != null)
            {
                alert(response.error.Message);
            }

            if (response.value != null)
            {
                if (response.value.toString().length > 0)
                {
                    // Display an error message if returned.
                    alert(response.value);
                }
                else
                {
                    updateCartCount();

                    if (top.RefreshLineItemControl)
                    {
                        var sortPreference = Amway.Core.Web.UI.Cart.CartControl.GetSortPreference();

                        if (typeof sortPreference.value == "string" && top.cartPreferenceSettings._cartDefined === true)
                        {
                            top.RefreshLineItemControl(sortPreference.value);
                        }
                    }
                }
            }

            if (typeof callbackFunc == "function")
            {
                callbackFunc(response);
            }
        });
    }

    function _initDialog(dialog)
    {
        //get a reference to all the elements
        _dialog = dialog;
        _element = $(dialog._dialogElem);
        _bagParent = _element.parent();

        //event handlers for the shopping bag parent
        _bagParent.focus(_popupGotFocus);
        _bagParent.mouseenter(_popupGotFocus);
        _bagParent.bind("click", _popupGotFocus);
        _bagParent.blur(_popupLostFocus);
        _bagParent.mouseleave(_popupLostFocus);
    }

    function _popupGotFocus()
    {
        //_bagParent.fadeIn("slow");
    }

    function _popupLostFocus()
    {
        /*_bagParent.fadeOut("slow", function() {
        _dialog.close();
        });*/
    }
}

var miniBag = new MiniBag();
var updateCartCallback = null;

// This method updates the "x ITEMS IN CART" message
function updateCartCount(callback)
{
    try
    {

        var isDifferentIFrameDomain = false;
        try
        {
            isDifferentIFrameDomain = (window.document.domain != window.parent.document.domain) ? true : false;
        } catch (ex)
        {
            isDifferentIFrameDomain = true;
        }

        if (isDifferentIFrameDomain)
        {
            if (typeof CartItemCountUpdate == "function")
            {
                CartItemCountUpdate();
            }
        } else
        {
            if (typeof top.CartItemCountUpdate == "function")
            {
                top.CartItemCountUpdate();
            }
        }
    }
    catch (ex)
    {
        // In case there is some funky cross domain error, don't let it show up for the user.
    }

    UpdateYouHaveItemsMessage();
}

// This updates the "You have x items in your cart" message
function UpdateYouHaveItemsMessage()
{
    var lblBag = null;

    // Only defined on shopping viewcart page
    if (typeof (lblItemsBagMsg02) == "string")
    {
        lblBag = $get(lblItemsBagMsg02);
    }

    // Only defined on shopping viewcart page
    if (typeof (window.parent.lblItemsBagMsg02) == "string")
    {
        lblBag = window.parent.$get(window.parent.lblItemsBagMsg02);
    }

    if (lblBag != null)
    {
        Amway.Core.Web.UI.Cart.CartControl.GetShoppingCartCountText(function(response)
        {
            try
            {
                if (response != null)
                {
                    lblBag.innerHTML = response.value;
                }
            }
            catch (ex)
            {
                // In case there is some funky cross domain error, don't let it show up for the user.
            }
        });
    }
}



function EmptyShoppingBag(btnEmptyBag, cartContainerId, popupInfo)
{
    var popupOptions = { isModal: true, beforeCloseHandler: this.dialogClose, isEmpty: false };

    popupOptions.buttons = {
        'Yes': function(event)
        {
            popupOptions.isEmpty = true;
            $(this).dialog('close');
        },
        'No': function(event)
        {
            popupOptions.isEmpty = false;
            $(this).dialog('close');
        }
    };

    $("#emptyBagConfirmDlg").attr("title", popupInfo.title);
    var popup = new AmwayPopup("emptyBagConfirmDlg", popupOptions, null);
    $("#emptyBagConfirmDlg").html(popupInfo.content);

    popup.showDialog();

    this.dialogClose = function(event)
    {
        $(this).dialog('close');
        return true;
    }
    return popupOptions.isEmpty;
}

var ItemStatusChange = function(showOnLoad, lnkId)
{
    var _showOnLoad = showOnLoad;
    var _lnk = $('#' + lnkId);
    var _dialog;

    _lnk.css("display", "none");

    if (_showOnLoad === true)
    {
        //can any one tell me why this is required?
        window.setTimeout(triggerOpen, 10);
    }

    function triggerOpen()
    {
        _lnk.trigger('click');
    }

    this.DialogOpen = function(event)
    {
        _dialog = event.data;
    }

    this.okBtnClick = function(event)
    {
        _dialog.close();
    }

    this.cancelBtnClick = function(event)
    {
        _dialog.close();
        window.location = window.location;
    }
}

function ShowProductQuickView(popupId, navigateUrl, launchElementId, width, height, popupTitle)
{
    if (popupId == null || popupId == '' || popupId == undefined)
    {
        popupId = usrProductQuickViewPopup;
    }

    return OpenAmwayPopup(popupId, navigateUrl, launchElementId, width, height, popupTitle, true);
}

// This is a special performance function built specifically for Ditto.
function ShowProductQuickViewDitto(skuId, launchElementId)
{
    var popupId = m_DittoPopupId;

    if (popupId == null || popupId == '' || popupId == undefined)
    {
        popupId = usrProductQuickViewPopup;
    }

    var navigateUrl = m_DittoNavigateUrl.replace("{0}", skuId);
    var width = m_DittoPopupWidth;
    var height = m_DittoPopupHeight
    var popupTitle = m_DittoPopupTitle;

    return OpenAmwayPopup(popupId, navigateUrl, launchElementId, width, height, popupTitle, true);
}

var CartAddressControl = function() {
    var _popup = null;
    var _this;
    var _textSoftErrorMsg;
    var _textHardErrorMsg;
    var _isAddresssValidated = false;
    var _isAddresssNewValidated = false;
    var _isAdd = false;
    var _isEdit = false;
    var _isCartAddressPopup = false;
    var destinationType;
    var OrderAddressDTO = null;
    var _originalTimeout;
    var _longTimeout = 60000;
    var _isShowSpinner = false;
    var _btnSpinner = null;
    var _reEditAddress = false;
    var _AddressReEdited = false;
    var _unmodifiedCopyForComparison = "";
    this.DialogOpen = function(event) {
        _isCartAddressPopup = true;
        _popup = event.data;
        // If _reEditAddress is set to true, then we do not want to overwrite the values from cartEditAddressId
        if (_reEditAddress) {
            _reEditAddress = false;
            _unmodifiedCopyForComparison =
                $('#' + cartEditAddressId.CareOfName).val() + '|' +
                $('#' + cartEditAddressId.Line1).val() + '|' +
                $('#' + cartEditAddressId.Line2).val() + '|' +
                $('#' + cartEditAddressId.City).val() + '|' +
                $('#' + cartEditAddressId.RegionCode).val() + '|' +
                $('#' + cartEditAddressId.zipcode1).val() +
                $('#' + cartEditAddressId.zipcode2).val();

            _AddressReEdited = true; // Allows us to postback as a Stored Address rather than an Edited Address.
        }
        else {
            var postalCode = $('#' + cartDisplayAddressId.zipcode).text();
            var zip1 = postalCode.substring(0, 5);
            var zip2 = postalCode.substring(5);
            if (postalCode.length == 6) {
                zip1 = postalCode.substring(0, 3);
                zip2 = postalCode.substring(3);
            }
            errorMsg.Show(false);
            destinationType = $('#' + cartDisplayAddressId.destinationType).val();
            $('#' + cartEditAddressId.CareOfName).val($('#' + cartDisplayAddressId.CareOfName).text());
            $('#' + cartEditAddressId.Line1).val($('#' + cartDisplayAddressId.Line1).text());
            $('#' + cartEditAddressId.Line2).val($('#' + cartDisplayAddressId.Line2).text());
            $('#' + cartEditAddressId.City).val($('#' + cartDisplayAddressId.City).text());
            $('#' + cartEditAddressId.RegionCode).val($('#' + cartDisplayAddressId.RegionCode).text());
            $('#' + cartEditAddressId.zipcode1).val(zip1);
            $('#' + cartEditAddressId.zipcode2).val(zip2);
            $('#' + cartEditAddressId.Phone).val(cartDisplayAddressId.PhoneUnformatted);
            $('#' + cartEditAddressId.Phone + "WithMask").val(cartDisplayAddressId.PhoneUnformatted);
            $('#' + cartEditAddressId.Phone + "WithMask").focus();
            $('#' + cartEditAddressId.CareOfName).focus();
            $('#' + cartEditAddressId.Phone + "_text").val(cartDisplayAddressId.PhoneFormatted);
            $('#' + cartEditAddressId.PhoneExt).val($('#' + cartDisplayAddressId.PhoneExt).text());
            $('#' + cartEditAddressId.BestContactTime + " :[value='" + $("#" + cartDisplayAddressId.BestContactTime + " :checked").val() + "']").attr("checked", "checked");
            $('#' + cartEditAddressId.Email).val($('#' + cartDisplayAddressId.Email).text());
            $('#' + cartEditAddressId.reenteremail).val($('#' + cartDisplayAddressId.Email).text());
            $('#' + cartEditAddressId.profileId).val($('#' + cartDisplayAddressId.profileId).text());
            $('#' + cartEditAddressId.customerID).val($get(cartDisplayAddressId.customerID).value);
            $('#' + cartEditAddressId.addressId).val($('#' + cartDisplayAddressId.addressId).val());
            $('#' + cartEditAddressId.taxCode).val($('#' + cartDisplayAddressId.taxCode).val());
        }
        $('#' + cartAddAddressId.FirstName).val('');
        $('#' + cartAddAddressId.LastName).val('');
        $('#' + cartAddAddressId.Line1).val('');
        $('#' + cartAddAddressId.Line2).val('');
        $('#' + cartAddAddressId.City).val('');
        $('#' + cartAddAddressId.RegionCode).val('');
        $('#' + cartAddAddressId.zipcode1).val('');
        $('#' + cartAddAddressId.zipcode2).val('');
        $('#' + cartAddAddressId.Phone).val('');
        $('#' + cartAddAddressId.Phone + "WithMask").val('');
        $('#' + cartAddAddressId.Phone + "_text").val('');
        $('#' + cartAddAddressId.PhoneExt).val('');
        $('#' + cartAddAddressId.Email).val('');
        $('#' + cartAddAddressId.reenteremail).val('');
        $('#' + cartAddAddressId.aliasname).val('');
        $('#' + cartAddAddressId.taxCode).val('');

        document.getElementById(cartEditAddressId.error).style.display = 'none';
        $get(cartAddAddressId.error).style.display = 'none';

        //Hide all validation errors  
        if (window.Page_Validators) {
            for (var i = 0; i < Page_Validators.length; i++) {
                var vValidator = Page_Validators[i];
                vValidator.isvalid = true;
                ValidatorUpdateDisplay(vValidator);
            }
        }
    }

    this.IsCartAddressPopup = function() {
        return _isCartAddressPopup;
    }

    this.AddAddress = function(event, btn) {
        _isAdd = true;
        _isEdit = false;

        var hdnBypassValidateNewAddress = document.getElementById(hdnBypassValidateNewAddressId);

        var webServiceError = cartAddAddressId.webServiceError;

        if (testFlag) {
            webServiceError = null;
        }

        OrderAddressDTO = FormJSONOrderAddress(cartAddAddressId);

        ClearErrorMessage(cartAddAddressId.error);

        var PopupID = cartAddAddressId.addressVerification;

        var PopupURL = cartAddAddressId.addressVerificationUrl;

        var isValid = GroupClientValidate(cartAddAddressId.validationGroup);

        increaseTimeout();

        if (isValid) {
            increaseTimeout(btn.id);
            showSpinner(btn.id, 'validationGroup');
            _isShowSpinner = true;
            _btnSpinner = btn.id;
            Amway.Core.Web.UI.Cart.CartAddressControl.ValidateAddress(OrderAddressDTO, true, false, function(response) {
                if (response.value != null) {
                    var isMainAddressSame = IsMainAddressSame(OrderAddressDTO, response.value);
                    if (response.value.IsValid && isMainAddressSame) {
                        _this.BindAddressVerified(cartAddAddressId, response.value);
                        _this.Submit();
                    }
                    else if (response.value.BypassAllowed || (response.value.IsValid && !isMainAddressSame)) {
                        _this.BindAddressVerified(cartAddAddressId, response.value);
                        cleanup();
                        OpenAddressVerificationPopup(PopupID, PopupURL, false);
                    }
                    else if (response.value.Errors != null) {
                        SetErrorMessageCollection(cartAddAddressId.error, cartAddAddressId.errorControlMessage, cartAddAddressId.webServiceError, response.value.Errors);
                        cleanup();
                    }
                    else {
                        SetErrorMessage(cartAddAddressId.error, cartAddAddressId.errorControlMessage, cartAddAddressId.webServiceError, null);
                        cleanup();
                    }
                }
                else {
                    SetErrorMessage(cartAddAddressId.error, cartAddAddressId.errorControlMessage, cartAddAddressId.webServiceError, null);
                    cleanup();
                }
            }, null, null, null, function(e) {
                SetErrorMessage(cartAddAddressId.error, cartAddAddressId.errorControlMessage, cartAddAddressId.webServiceError, null);
                cleanup();
            });
        }
        return false; // we do not want a postback here
    }

    function increaseTimeout() {
        if (typeof _originalTimeout === "undefined") {
            _originalTimeout = Ajax.timeoutPeriod;
        }

        if (Ajax.timeoutPeriod !== _longTimeout) {
            Ajax.timeoutPeriod = _longTimeout;
        }
    }

    function cleanup() {
        Ajax.timeoutPeriod = _originalTimeout;
        if (_isShowSpinner) {
            $('div.jquery-ajax-loader').css('display', 'none');
            _isShowSpinner = false;
        }
    }

    //Set the address to refresh.
    function SetAddAddressRefresh() {
        OrderAddressDTO = FormJSONOrderAddress(cartAddAddressId);
        $get(cartDisplayAddressId.hidden).value = JSON.stringify(OrderAddressDTO);
        $get(cartDisplayAddressId.addtoMyAddress).checked = OrderAddressDTO.IsContactSaved;
        $get(cartDisplayAddressId.defaultAddress).checked = OrderAddressDTO.IsPrimary;
        if (destinationType == "Ditto") {
            blockPage();
            BindShippingAddress(cartDisplayAddressId, cartAddAddressId);
            ShowTaxJurisdiction(OrderAddressDTO);
            unblockPage();
        }
        else {
            cleanup();
            __doPostBack('refreshNewAddress', $get(cartDisplayAddressId.hidden).value);
        }
    }

    this.UpdateAddress = function(event, btn) {
        _isAdd = false;
        _isEdit = true;

        var webServiceError = cartEditAddressId.webServiceError;

        if (testFlag) {
            webServiceError = null;
        }

        //Clear the error messages dispalyed.
        ClearErrorMessage(cartEditAddressId.error);

        //Address verification pop up id.
        var PopupID = cartEditAddressId.addressVerification;

        //Address verification pop up id.
        var PopupURL = cartEditAddressId.addressVerificationUrl;

        //Form address DTO.
        OrderAddressDTO = FormJSONOrderAddress(cartEditAddressId);

        if (typeof $('#' + cartDisplayAddressId.addressId) == 'object') {
            OrderAddressDTO.AddressID = $('#' + cartDisplayAddressId.addressId)[0].defaultValue;
        }

        var isValid = GroupClientValidate(cartEditAddressId.validationGroup);

        if (isValid) {
            increaseTimeout(btn.id);
            showSpinner(btn.id, 'validationGroup');
            _isShowSpinner = true;
            _btnSpinner = btn.id;
            Amway.Core.Web.UI.Cart.CartAddressControl.ValidateAddress(OrderAddressDTO, true, false, function(response) {
                if (response.value != null) {
                    var isMainAddressSame = IsMainAddressSame(OrderAddressDTO, response.value);
                    if (response.value.IsValid && isMainAddressSame) {
                        _btnSubmitId = btn.id;
                        _this.BindAddressVerified(cartEditAddressId, response.value);
                        _this.Submit();
                    }
                    else if (response.value.BypassAllowed || (response.value.IsValid && !isMainAddressSame)) {
                        _this.BindAddressVerified(cartEditAddressId, response.value);
                        cleanup();
                        OpenAddressVerificationPopup(PopupID, PopupURL, false);
                    }
                    else if (response.value.Errors != null) {
                        SetErrorMessageCollection(cartEditAddressId.error, cartEditAddressId.errorControlMessage, cartAddAddressId.webServiceError, response.value.Errors);
                        cleanup();
                    }
                    else {
                        SetErrorMessage(cartEditAddressId.error, cartEditAddressId.errorControlMessage, cartEditAddressId.webServiceError, null);
                        cleanup();
                    }
                }
                else {
                    SetErrorMessage(cartEditAddressId.error, cartEditAddressId.errorControlMessage, cartEditAddressId.webServiceError, null);
                    cleanup();
                }
            }, null, null, null, function(e) {
                SetErrorMessage(cartAddAddressId.error, cartAddAddressId.errorControlMessage, cartAddAddressId.webServiceError, null);
                cleanup();
            }); //ends Amway.Core.Web.UI.Cart.CartAddressControl.ValidateAddress(param-list); 
        }
        return false; // we do not want a postback here
    }

    //Set the address to refresh.
    function SetEditAddressRefresh() {
        OrderAddressDTO = FormJSONOrderAddress(cartEditAddressId);
        $get(cartDisplayAddressId.hidden).value = JSON.stringify(OrderAddressDTO);
        $get(cartDisplayAddressId.addtoMyAddress).checked = false;
        $get(cartDisplayAddressId.defaultAddress).checked = OrderAddressDTO.IsPrimary;
        if (destinationType == "Ditto") {
            blockPage();
            BindShippingAddress(cartDisplayAddressId, cartEditAddressId);
            // ToDo: The SOA layer is not responding correctly.  Until it is, I am commenting out the IF portion
            //if ((typeof $('#' + cartDisplayAddressId.taxCode).val() !== 'undefined')) {
            //    var taxCode = $get(cartDisplayAddressId.taxCode).value;
            //    if (taxCode == null || taxCode.trim() == '') {
            ShowTaxJurisdiction(OrderAddressDTO);
            //    }
            //}
            unblockPage();
        }
        else {
            cleanup();
            var postBackValue = 'refreshAddress';
            // Even though we may have flagged this address as _AddressReEdited, if the user modified it
            // then we cannot do a postback as "refreshStoredAddress" because the tax jurisdiction would never fire
            // so we must check the address for edits against the unmodified copy.
            var _finalCopyForComparison =
                OrderAddressDTO.CareOfName + '|' +
                OrderAddressDTO.Line1 + '|' +
                OrderAddressDTO.Line2 + '|' +
                OrderAddressDTO.City + '|' +
                OrderAddressDTO.RegionCode + '|' + 
                OrderAddressDTO.PostalCode;
            if (_AddressReEdited && _unmodifiedCopyForComparison == _finalCopyForComparison) {
                postBackValue = 'refreshStoredAddress';
            }
            __doPostBack(postBackValue, $get(cartDisplayAddressId.hidden).value);
        }
    }

    //Add cancel.
    this.AddCancel = function(event, btn) {
        $('#' + cartAddAddressId.FirstName).val('');
        $('#' + cartAddAddressId.LastName).val('');
        $('#' + cartAddAddressId.Phone).val('');
        $('#' + cartAddAddressId.Phone + "WithMask").val('');
        $('#' + cartAddAddressId.Phone + "_text").val('');
        $('#' + cartAddAddressId.PhoneExt).val('');
        $('#' + cartAddAddressId.Email).val('');
        $('#' + cartAddAddressId.reenteremail).val('');
        $('#' + cartAddAddressId.City).val('');
        $('#' + cartAddAddressId.RegionCode).val('');
        $('#' + cartAddAddressId.Line1).val('');
        $('#' + cartAddAddressId.Line2).val('');
        $('#' + cartAddAddressId.zipcode1).val('');
        $('#' + cartAddAddressId.zipcode2).val('');
        $('#' + cartAddAddressId.aliasname).val('');
        $('#' + cartAddAddressId.addtoMyAddress)[0].checked = false;
        $('#' + cartAddAddressId.defaultAddress)[0].checked = false;
        $('#' + cartDisplayAddressId.addtoMyAddress)[0].checked = false;
        $('#' + cartDisplayAddressId.defaultAddress)[0].checked = false;
        _this.AddAddressChecked();
        return close();
    }

    //Edit Cancel.
    this.EditCancel = function(event, btn) {
        $('#' + cartEditAddressId.CareOfName).val('');
        $('#' + cartEditAddressId.Phone).val('');
        $('#' + cartEditAddressId.Phone + "WithMask").val('');
        $('#' + cartEditAddressId.Phone + "_text").val('');
        $('#' + cartEditAddressId.PhoneExt).val('');
        $('#' + cartEditAddressId.cartEditAddressId).val('');
        $('#' + cartEditAddressId.reenteremail).val('');
        $('#' + cartEditAddressId.City).val('');
        $('#' + cartEditAddressId.RegionCode).val('');
        $('#' + cartEditAddressId.Line1).val('');
        $('#' + cartEditAddressId.Line2).val('');
        $('#' + cartEditAddressId.zipcode1).val('');
        $('#' + cartEditAddressId.zipcode2).val('');
        $('#' + cartEditAddressId.aliasname).val('');
        $('#' + cartEditAddressId.defaultAddress)[0].checked = false;
        $('#' + cartDisplayAddressId.addtoMyAddress)[0].checked = false;
        $('#' + cartDisplayAddressId.defaultAddress)[0].checked = false;
        return close();
    }

    // If the address sent in the given string is not complete,
    // we will prepare the Edit Address Popup so the user can edit it
    // and then we open the Edit Popup and return TRUE
    // If the address is OK, we simply return FALSE
    this.EditAddressIfBad = function(addressString) {
        var OrderAddressDTO = eval('(' + addressString + ')');
        // Currently we only validate the object itself, and the email address.  We could add the phone if desired.
        if (typeof OrderAddressDTO == 'object' &&
            (OrderAddressDTO.Email == '' || OrderAddressDTO.Email == 'undefined' || OrderAddressDTO.Email == null)) {
            _isCartAddressPopup = true;
            //_popup = event.data;
            var postalCode = OrderAddressDTO.PostalCode;
            var zip1 = postalCode.substring(0, 5);
            var zip2 = postalCode.substring(5);
            if (postalCode.length == 6) {
                zip1 = postalCode.substring(0, 3);
                zip2 = postalCode.substring(3);
            }
            errorMsg.Show(false);

            if (OrderAddressDTO.CareOfName == null || OrderAddressDTO.CareOfName == '') {
                OrderAddressDTO.CareOfName = OrderAddressDTO.FirstName + " " + OrderAddressDTO.LastName;
                OrderAddressDTO.CareOfName = OrderAddressDTO.CareOfName.trim();
            }
            $('#' + cartEditAddressId.CareOfName).val(OrderAddressDTO.CareOfName);
            $('#' + cartEditAddressId.Line1).val(OrderAddressDTO.Line1);
            $('#' + cartEditAddressId.Line2).val(OrderAddressDTO.Line2);
            $('#' + cartEditAddressId.City).val(OrderAddressDTO.City);
            $('#' + cartEditAddressId.RegionCode).val(OrderAddressDTO.RegionCode);
            $('#' + cartEditAddressId.zipcode1).val(zip1);
            $('#' + cartEditAddressId.zipcode2).val(zip2);
            $('#' + cartEditAddressId.Phone).val(OrderAddressDTO.Phone);
            $('#' + cartEditAddressId.Phone + "WithMask").val(OrderAddressDTO.Phone);
            $('#' + cartEditAddressId.Phone + "_text").val(OrderAddressDTO.Phone);
            $('#' + cartEditAddressId.PhoneExt).val(OrderAddressDTO.Extn);
            $('#' + cartEditAddressId.BestContactTime + " :[value='" + $("#" + OrderAddressDTO.BestContactTime + " :checked").val() + "']").attr("checked", "checked");
            $('#' + cartEditAddressId.Email).val(OrderAddressDTO.Email);
            $('#' + cartEditAddressId.reenteremail).val(OrderAddressDTO.Email);
            $('#' + cartEditAddressId.profileId).val(OrderAddressDTO.ProfileID);
            $('#' + cartEditAddressId.customerID).val(OrderAddressDTO.CustomerID);
            $('#' + cartEditAddressId.taxCode).val(OrderAddressDTO.TaxCode).val();

            document.getElementById(cartEditAddressId.error).style.display = '';
            $get(cartAddAddressId.error).style.display = '';

            _reEditAddress = true;

            FireEvent(document.getElementById(cartDisplayAddressId.editAddressPopup), 'click');

            $('#' + cartEditAddressId.Phone + "WithMask").focus();
            $('#' + cartEditAddressId.Email).focus();

            for (var i = 0; i < Page_Validators.length; i++) {
                ValidatorValidate(Page_Validators[i], null, null);
                if (!Page_Validators[i].isvalid) {
                    Page_Validators[i].style.display = "inline";
                }
            }

            window.scrollTo(0, 0);

            return true;
        }
        else {
            return false;
        }
    }

    //Submit add/edit address.
    this.Submit = function() {
        _isAddresssValidated = false;
        _isAddresssNewValidated = false;
        if (_btnSpinner != null) {
            showSpinner(_btnSpinner, 'validationGroup');
            _isShowSpinner = true;
        }
        if (_isAdd) {
            SetAddAddressRefresh();
        }
        else if (_isEdit) {
            SetEditAddressRefresh();
        }
        else {  // visitor
            cleanup();
            __doPostBack(cartAddressVisitorBtn, '');
        }
    }

    this.ShowErrorMessages = function(errors) {
        if (typeof cartAddAddressId === 'object') {
            SetErrorMessageCollection(cartAddAddressId.error, cartAddAddressId.errorControlMessage, cartAddAddressId.webServiceError, errors);
        }
        else if (typeof cartEditAddressId === 'object') {
            SetErrorMessageCollection(cartEditAddressId.error, cartEditAddressId.errorControlMessage, cartEditAddressId.webServiceError, errors);
        }
    }

    //Email and Phone Verification
    function OpenEmailPhoneVerificationPopUp(addressId) {
        var windowIds = new Object();
        options = {};
        options.resize = false;
        var wnd = new AmwayPopupWindow(addressId.phoneOrEmailRequired, options);
        wnd.showWindow("/Shop/MyAccount/AddressPhoneOrEmailRequired.aspx", 500, 200);
    }
    function close() {
        _isAddresssValidated = false;
        _isAddresssNewValidated = false;
        if (typeof _btnSubmitId === "string") {
            $('div.jquery-ajax-loader').css('display', 'none');
        }
        _popup.close();
        return false;
    }
    this.CancelValidation = function() {
        _isAddresssValidated = false;
        _isAddresssNewValidated = false;
    }
    this.AddressVerificationClosed = function(details) {
        if (typeof cartEditAddressId === 'object') {
            _this.BindAddressVerified(cartEditAddressId, details);
        }
        else if (typeof cartAddAddressId === 'object') {
            _this.BindAddressVerified(cartAddAddressId, details);
        }
        else if (typeof cartAddressVisitor === 'object') {
            _this.BindAddressVerified(cartAddressVisitor, details);
        }
    }
    this.BindAddressVerified = function(addressId, details) {
        var city = document.getElementById(addressId.City);
        var line1 = document.getElementById(addressId.Line1);
        var line2 = document.getElementById(addressId.Line2);
        var state = document.getElementById(addressId.RegionCode);
        var hdnState = document.getElementById(addressId.hdnState);
        var zip1 = document.getElementById(addressId.zipcode1);
        var zip2 = document.getElementById(addressId.zipcode2);
        var postalCode = details.PostalCode;
        var zipcd1 = postalCode.substring(0, 5);
        var zipcd2 = postalCode.substring(5);
        if (postalCode.length == 6) {
            zipcd1 = postalCode.substring(0, 3);
            zipcd2 = postalCode.substring(3);
        }
        var taxCode = document.getElementById(addressId.taxCode);
        city.value = details.City;
        state.value = details.RegionCode;
        hdnState.value = details.RegionCode.substring(0, 2);

        if (typeof taxCode != 'undefined' && taxCode != null) {
            taxCode.value = details.TaxJurisdictionCode;
        }
        line1.value = details.Line1;
        line2.value = (details.Line2 == null) ? "" : details.Line2;
        zip1.value = zipcd1;
        zip2.value = zipcd2;
        _isAddresssValidated = true;
    }
    this.AddAddressChecked = function() {
        var checkbox = document.getElementById(cartAddAddressId.addtoMyAddress);
        if (checkbox != null) {
            var display = 'none';
            if (checkbox.checked == true) {
                display = '';
            }
            SetDisplay(cartAddAddressId.description, display);
            var valReq = document.getElementById(cartAddAddressId.valDescription);
            if (valReq != null) {
                ValidatorEnable(valReq, checkbox.checked);
                if (checkbox.checked) {
                    valReq.isvalid = true;
                    ValidatorUpdateDisplay(valReq);
                }
                else {
                    var aliasnameCtrl = document.getElementById(cartAddAddressId.aliasname);
                    if (typeof aliasnameCtrl != "undefined") {
                        aliasnameCtrl.value = '';
                    }
                }
            }
            var valReg = document.getElementById(cartAddAddressId.valDescriptionAsciiRegex);
            if (valReg != null) {
                ValidatorEnable(valReg, checkbox.checked);
            }
        }
        return true;
    }

    function BindShippingAddress(displayId, addressId) {
        if (typeof $('#' + displayId.CareOfName) == 'object') {
            if ((typeof $('#' + addressId.CareOfName).val() !== 'undefined') && (typeof $('#' + addressId.CareOfName).val() !== '')) {
                $('#' + displayId.CareOfName).html($('#' + addressId.CareOfName).val());
            }
            else if (typeof $('#' + addressId.FirstName) == 'object') {
                $('#' + displayId.CareOfName).html($('#' + addressId.FirstName).val() + ' ' + $('#' + addressId.LastName).val());
            }
        }
        $('#' + displayId.Phone).html($('#' + addressId.Phone).val());
        $('#' + displayId.Phone + "WithMask").html($('#' + addressId.Phone + "WithMask").val());
        $('#' + displayId.Phone + "_text").html($('#' + addressId.Phone + "_text").val());
        $('#' + displayId.PhoneExt).html($('#' + addressId.PhoneExt).val());
        $('#' + displayId.Email).html($('#' + addressId.Email).val());
        $('#' + displayId.City).html($('#' + addressId.City).val());
        $('#' + displayId.RegionCode).html($('#' + addressId.RegionCode).val());
        $('#' + displayId.Line1).html($('#' + addressId.Line1).val());
        if ($('#' + addressId.Line2).val() == "") {
            document.getElementById(divShowAddressLine2).style.display = 'none';
            $('#' + displayId.Line2).html = "";
        }
        else {
            document.getElementById(divShowAddressLine2).style.display = '';
            document.getElementById(divShowAddressLine2).className = '';
            $('#' + displayId.Line2).html($('#' + addressId.Line2).val());
        }

        $('#' + displayId.aliasname).html($('#' + addressId.aliasname).val());
        $('#' + displayId.zipcode).html($('#' + addressId.zipcode1).val() + "" + $('#' + addressId.zipcode2).val());
        if (typeof FormatCartAddressPostalCode == "function") {
            var zipcodeFormatted = FormatCartAddressPostalCode($('#' + addressId.zipcode1).val() + $('#' + addressId.zipcode2).val());
            $('#' + displayId.zipcodeFormatted).html(zipcodeFormatted);
        }
        $('#' + displayId.customerID).val($get(addressId.customerID).value);

        if ((typeof $('#' + addressId.taxCode).val() !== 'undefined') && (typeof $('#' + displayId.taxCode).val() !== 'undefined')) {
            $('#' + displayId.taxCode).val($get(addressId.taxCode).value);
        }

        if (_isAdd) {
            _this.AddCancel();
        }
        else if (_isEdit) {
            _this.EditCancel();
        }
        cleanup();
        return close();
    }

    function SaveEditedAddress(addresId) {
    }

    _this = this;
}

function FireEvent(obj, evt) {
    var fireOnThis = obj;
    if (document.createEvent) {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent(evt, true, false);
        fireOnThis.dispatchEvent(evObj);
    } else if (document.createEventObject) {
        fireOnThis.fireEvent('on' + evt);
    }
}

function OpenAddressVerificationPopup(popupID, popupURL, isMAC)
{
    var windowIds = new Object();
    options = {};
    options.resize = false;
    var wnd = new AmwayPopupWindow(popupID, options);
    var url = popupURL + "?IncludeOffshore=" + isMAC;
    wnd.showWindow(url, 600, 400);
}

function IsMainAddressSame(orderAddressDTO, responseAddress)
{
    // we don't verify with the user if the backend just added a postal code extension
    var postalCode = GetLeftString(orderAddressDTO.PostalCode, responseAddress.PostalCode);

    // Note: region codes from the MAC dropdown can have a ":" followed by true or false,
    // so we strip these characters off if they are there
    var regionCodeA = orderAddressDTO.RegionCode != null ? orderAddressDTO.RegionCode.substring(0, 2) : '';
    var regionCodeB = responseAddress.RegionCode != null ? responseAddress.RegionCode.substring(0, 2) : '';

    if (IsSameString(orderAddressDTO.City, responseAddress.City) &&
        IsSameString(regionCodeA, regionCodeB) &&
        IsSameString(orderAddressDTO.PostalCode, postalCode))
    {
        return true;
    }
    return false;
}

function IsAddressSame(address1, address2) {
    if (typeof address1 == 'undefined' && typeof address2 == 'undefined') {
        return true;
    }
    if (typeof address1 == 'undefined' || typeof address2 == 'undefined') {
        return false;
    }
    if (address1 == null && address2 == null) {
        return true;
    }
    if (address1 == null || address2 == null) {
        return false;
    }
    
    if (IsSameString(address1.Line1, address2.Line1) &&
        IsSameString(address1.Line2, address2.Line2) &&
        IsSameString(address1.City, address2.City) &&
        IsSameString(address1.RegionCode, address2.RegionCode) &&
        IsSameString(address1.PostalCode, address2.PostalCode))
    {
        return true;
    }
    return false;
}

function IsSameString(str1, str2)
{
    var isSame = false;
    if (typeof str1 == "string")
    {
        if (typeof str2 == "string")
        {
            if (str1.trim().toUpperCase() == str2.trim().toUpperCase())
            {
                isSame = true;
            }
        }
    }
    else if (!(typeof str2 == "string"))
    {
        isSame = true;
    }
    return isSame;
}

function GetLeftString(str1, str2)
{
    if ((typeof str1 == "string") && (str1 != null) && (typeof str2 == "string") && (str2 != null))
    {
        if (str2.length > str1.length)
        {
            return str2.substr(0, str1.length);
        }
    }
    return str2;
}

function GroupClientValidate(validationGroup)
{
    Page_InvalidControlToBeFocused = null;
    if (typeof (Page_Validators) == "undefined")
    {
        return true;
    }
    var i;
    for (i = 0; i < Page_Validators.length; i++)
    {
        GroupValidatorValidate(Page_Validators[i], validationGroup, null);
    }
    GroupValidatorUpdateIsValid(validationGroup);
    ValidationSummaryOnSubmit(validationGroup);
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
}

function GroupValidatorValidate(val, validationGroup, event)
{
    if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, validationGroup))
    {
        if (typeof (val.evaluationfunction) == "function")
        {
            val.isvalid = val.evaluationfunction(val);
            if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
                    typeof (val.focusOnError) == "string" && val.focusOnError == "t")
            {
                ValidatorSetFocus(val, event);
            }
        }
        ValidatorUpdateDisplay(val);
        val.style.display = val.isvalid ? "none" : "inline";
    }
}

function GroupValidatorUpdateIsValid(validationGroup)
{
    Page_IsValid = GroupValidatorsValid(Page_Validators, validationGroup);
}

function GroupValidatorsValid(validators, validationGroup)
{
    if ((typeof (validators) != "undefined") && (validators != null))
    {
        var i;
        for (i = 0; i < validators.length; i++)
        {
            if (IsValidationGroupMatch(validators[i], validationGroup))
            {
                if (!validators[i].isvalid)
                {
                    return false;
                }
            }
        }
    }
    return true;
}

function FormJSONOrderAddress(addressId)
{
    var orderAddressDTO = {};
    if (typeof $('#' + addressId.FirstName) == 'object')
    {
        if (typeof $('#' + addressId.FirstName).val() !== 'undefined')
        {
            orderAddressDTO.FirstName = $('#' + addressId.FirstName).val();
        }
    }
    if (typeof $('#' + addressId.LastName) == 'object')
    {
        if (typeof $('#' + addressId.LastName).val() !== 'undefined')
        {
            orderAddressDTO.LastName = $('#' + addressId.LastName).val();
        }
    }
    if (typeof $('#' + addressId.CareOfName) == 'object')
    {
        if (typeof $('#' + addressId.CareOfName).val() !== 'undefined')
        {
            orderAddressDTO.CareOfName = $('#' + addressId.CareOfName).val();
        }
    }
    if (typeof $('#' + addressId.Line1) == 'object')
    {
        if (typeof $('#' + addressId.Line1).val() !== 'undefined')
        {
            orderAddressDTO.Line1 = $('#' + addressId.Line1).val();
        }
    }
    if (typeof $('#' + addressId.Line2) == 'object')
    {
        if (typeof $('#' + addressId.Line2).val() !== 'undefined')
        {
            orderAddressDTO.Line2 = $('#' + addressId.Line2).val();
        }
    }
    if (typeof $('#' + addressId.City) == 'object')
    {
        if (typeof $('#' + addressId.City).val() !== 'undefined')
        {
            orderAddressDTO.City = $('#' + addressId.City).val();
        }
    }
    if (typeof $('#' + addressId.RegionCode) == 'object')
    {
        if (typeof $('#' + addressId.RegionCode).val() !== 'undefined')
        {
            orderAddressDTO.RegionCode = $('#' + addressId.RegionCode).val();
        }
    }
    if (typeof $('#' + addressId.zipcode1) == 'object')
    {
        if (typeof $('#' + addressId.zipcode1).val() !== 'undefined')
        {
            orderAddressDTO.PostalCode = $('#' + addressId.zipcode1).val() + $('#' + addressId.zipcode2).val();
        }
    }
    orderAddressDTO.Phone = '';
    if (typeof $('#' + addressId.Phone) == 'object')
    {
        if (typeof $('#' + addressId.Phone).val() !== 'undefined')
        {
            orderAddressDTO.Phone = $('#' + addressId.Phone).val();
        }
    }
    orderAddressDTO.Extn = '';
    if (typeof $('#' + addressId.PhoneExt) == 'object')
    {
        if (typeof $('#' + addressId.PhoneExt).val() !== 'undefined')
        {
            orderAddressDTO.Extn = $('#' + addressId.PhoneExt).val();
        }
    }
    orderAddressDTO.BestContactTime = '';
    if (typeof $('#' + addressId.BestContactTime) == 'object')
    {
        if (typeof $('#' + addressId.BestContactTime).val() !== 'undefined')
        {
            orderAddressDTO.BestContactTime = $("#" + addressId.BestContactTime + " :checked").val();
        }
    }
    orderAddressDTO.Email = '';
    if (typeof $('#' + addressId.Email) == 'object')
    {
        if (typeof $('#' + addressId.Email).val() !== 'undefined')
        {
            orderAddressDTO.Email = $('#' + addressId.Email).val();
        }
    }
    if (typeof $('#' + addressId.aliasname) == 'object')
    {
        if (typeof $('#' + addressId.aliasname).val() !== 'undefined')
        {
            orderAddressDTO.AliasName = $('#' + addressId.aliasname).val();
        }
    }
    if (typeof $('#' + addressId.taxCode) == 'object')
    {
        if (typeof $('#' + addressId.taxCode).val() !== 'undefined')
        {
            orderAddressDTO.TaxCode = $('#' + addressId.taxCode).val();
        }
    }
    orderAddressDTO.CustomerID = '';
    if (typeof $('#' + addressId.customerID) == 'object')
    {
        if (typeof $('#' + addressId.customerID).val() !== 'undefined')
        {
            orderAddressDTO.CustomerID = $('#' + addressId.customerID).val();
        }
    }

    orderAddressDTO.ProfileID = '';
    if (typeof cartDisplayAddressId == 'object')
    {
        if (typeof $('#' + cartDisplayAddressId.profileId) == 'object')
        {
            orderAddressDTO.ProfileID = $('#' + cartDisplayAddressId.profileId)[0].defaultValue;
        }
    }
    if (typeof $('#' + addressId.defaultAddress) == 'object')
    {
        if (typeof $('#' + addressId.defaultAddress).val() !== 'undefined')
        {
            orderAddressDTO.IsPrimary = $('#' + addressId.defaultAddress)[0].checked;
        }
    }
    if (typeof $('#' + addressId.addtoMyAddress) == 'object')
    {
        if (typeof $('#' + addressId.addtoMyAddress).val() !== 'undefined')
        {
            orderAddressDTO.IsContactSaved = $('#' + cartAddAddressId.addtoMyAddress)[0].checked;
        }
    }
    return orderAddressDTO;

}
function SetRequiredFieldMarker(ctrlId, isReqField)
{
    var ctrl = document.getElementById(ctrlId);
    if (ctrl != null)
    {
        var i = ctrl.innerHTML.lastIndexOf('<');
        if (i > 0)
        {
            var n = ctrl.innerHTML.length;
            var mark = ' ';
            if (isReqField)
            {
                mark = '*';
            }
            ctrl.innerHTML = ctrl.innerHTML.substring(0, i - 1) + mark + ctrl.innerHTML.substring(i, n);
        }
    }
}

function SetDisplay(ctrlId, display)
{
    var ctrl = document.getElementById(ctrlId);
    if (ctrl != null)
    {
        ctrl.style.display = display;
    }
}

function EnableValidator(id, val)
{
    if (typeof (id) == "string" && typeof (val) != "undefined")
    {
        var obj = $get(id);
        if (obj != null)
        {
            ValidatorEnable(obj, val);
        }
    }
}

function SetErrorMessage(ctrlId, msgId, text, wsErr)
{
    var ctrl = document.getElementById(ctrlId);
    var msg = document.getElementById(msgId);
    if (ctrl != null && msg != null)
    {
        if (wsErr != null)
        {
            msg.innerHTML = wsErr;
        }
        else
        {
            msg.innerHTML = text;
        }
        ctrl.style.display = '';
    }
}

function SetErrorMessageCollection(ctrlId, msgId, text, errors)
{
    Amway.Core.Web.UI.Cart.CartAddressControl.GetMessageHTML(errors, 'Error', function(response)
    {
        if (response.error === null)
        {
            SetErrorMessage(ctrlId, msgId, response.value, null);
        }
        else
        {
            SetErrorMessage(ctrlId, msgId, text, null);
        }
    });
}

function ClearErrorMessage(ctrlId)
{
    var ctrl = document.getElementById(ctrlId);
    if (ctrl != null)
    {
        ctrl.style.display = 'none';
    }
}

var cartAddressControl = new CartAddressControl();

function GetCleanZip(strZip)
{
    return strZip.replace(/[^a-zA-Z 0-9]+/g, '');
}

function EnableDisableCreditCardValidation(radValueID, hdnValueID)
{
    var options = document.getElementById(radValueID);
    var hdnValue = document.getElementById(hdnValueID);
    if (options.cells[0].childNodes[0].checked)
    {
        hdnValue.value = 'true';
        options.cells[0].childNodes[0].checked = true;
    }
    else
    {
        hdnValue.value = 'false';
        options.cells[0].childNodes[1].checked = true;
    }
}

function OpenCartAddressEditControl()
{
    $get(pnlAlert).style.display = 'none';
    $get(pnlEditAddress).style.display = '';
    return false;
}

function SelectStateDropDownValue(ddlStateID, hdnValueID)
{
    var ddlState = document.getElementById(ddlStateID);
    var hiddenfield = document.getElementById(hdnValueID);
    for (i = 0; i < ddlState.length - 1; i++)
    {
        if (ddlState[i].selected == true)
        {
            hiddenfield.value = ddlState[i].value;
        }
    }
}

function validateaddress()
{
    // Remove the validator control(s) from display.
    var myValidationGroup = "CartAddressGroup";
    var myValidators = Page_Validators;
    if ((typeof (myValidators) != "undefined") && (myValidators != null))
    {
        for (i = 0; i < myValidators.length; i++)
        {
            var myValidator = myValidators[i];
            if (myValidationGroup != null || IsValidationGroupMatch(myValidator, myValidationGroup))
            {
                if (myValidator.style.visibility.length > 0 && myValidator.style.display.length == 0)
                {
                    myValidator.style.visibility = '';
                }
                else if (myValidator.style.display.length > 0 && myValidator.style.visibility.length == 0)
                {
                    myValidator.style.display = '';
                }
            }
        }
    }
}

function VisitorShippingValidation()
{

    Page_IsValid = UpdateAddressForVisitor();

    Page_BlockSubmit = !Page_IsValid;

    if (Page_BlockSubmit)
    {
        unblockPage();
    }

    return Page_IsValid;
}

function UpdateAddressForVisitor()
{
    if (GroupClientValidate(cartAddressVisitor.validationGroup))
    {
        var OrderAddressDTO = FormJSONOrderAddress(cartAddressVisitor);

        Amway.Core.Web.UI.Cart.CartAddressControl.ValidateAddress(OrderAddressDTO, true, false, function(response)
        {
            if (response.value !== null)
            {
                var isMainAddressSame = IsMainAddressSame(OrderAddressDTO, response.value);
                if (response.value.IsValid && isMainAddressSame)
                {
                    errorMsg.Show(false);
                    cartAddressControl.BindAddressVerified(cartAddressVisitor, response.value);
                    __doPostBack(cartAddressVisitorBtn, '');
                }
                else if (response.value.BypassAllowed || (response.value.IsValid && !isMainAddressSame))
                {
                    errorMsg.Show(false);
                    OpenAddressVerificationPopup(cartAddressVisitor.addressVerification, cartAddressVisitor.addressVerificationUrl, false);
                }
                else if (response.value.Errors != null)
                {
                    errorMsg.DisplayDomainErrorMessages(AmwayNotificationType.Error, response.value.Errors);
                }
                else
                {
                    errorMsg.DisplayMsg(AmwayNotificationType.Error, cartAddressVisitor.webServiceError);
                }
            }
            else
            {
                errorMsg.DisplayMsg(AmwayNotificationType.Error, cartAddressVisitor.webServiceError);
            }
        });
    }
    return false;
}

//function DoVisitorAddressPostBack()
//{
//    cartAddressVisitor.recursive = true;
//    document.getElementById(cartAddressVisitorBtn).click();
//}

//Call Line items controls in diffrent modules.
function PopulateCartLineItemControls(DestinationType, error, thisRef)
{
    //DestinationType will have values in Amway.Core.Web.Cart.Data.CartDestinationType
    if (DestinationType == "ShoppingCart")
    {
        if (thisRef._isJustAdded())
        {
            thisRef.clearAddItemControl(true);
            justAdded = false;

            addItemSpinner.show();

            //TODO: Construct new way to refresh page
            //PostBack call was throwing a JS error if added item from multi then add from cart add
            //__doPostBack('refreshEmptyCart', '');
            window.location = window.location;
            thisRef.updateLineItems();
            thisRef.updateOrderSummary();

            //addItemSpinner.hide();

        }

        else if (error.length == 0)
        {
            thisRef.clearAddItemControl(true);
            thisRef.updateLineItems();
            thisRef.updateOrderSummary();
        }
        else
        {
            thisRef.displayDomainErrorMessage(error);
        }
    }
    else if (DestinationType == "ShoppingList")
    {
        RefreshControl(cartPreferenceSettings._sortOrder);
        thisRef.clearAddItemControl(true);
        if (error.length > 0)
        {
            scrollTo(0, 0);
            errorMsg.DisplayMsg(AmwayNotificationType.Error, error);
        }
        if (error.length == 0 && thisRef._isJustAdded())
        {
            window.location = window.location;
            justAdded = false;
        }
    }
    else if (DestinationType == "Ditto")
    {
        if (error.length == 0)
        {
            blockPage();
            thisRef.clearAddItemControl(true);
            RefreshDitto();
            unblockPage();
        }
        else
        {
            thisRef.displayDomainErrorMessage(error);
        }
    }
    else if (DestinationType == "SalesReceipt")
    {
        if (error.length == 0)
        {
            thisRef.clearAddItemControl(true);
            salesReceiptSettings._sortBy = cartPreferenceSettings._sortOrder;
            RefreshSalesReceiptControls(salesReceiptSettings);
        }
        else
        {
            thisRef.displayDomainErrorMessage(error);
        }
    }
}

function Redirect(url)
{
    if (typeof url === "string")
        window.location = url;
    return false;
}

function EditPHPProducts(packetName, cartName)
{
    Amway.Core.Web.UI.Cart.CartControl.AddPacketItemsToSelector(packetName);
    window.location.href = "/Shop/Product/Selector.aspx?s=PersonalizedHealth&Packet=" + packetName + "&source=cart&CartName=" + cartName;
}

var CartSpinner = function()
{
    var _shown = false;
    var _ctr = 0;
    this.show = function()
    {
        if (_shown === false)
        {
            if (typeof lineItemContainer == "undefined")
            {
                blockPage();
            }
            else
            {
                showSpinnerLarge(lineItemContainer, '');
            }
            _shown = true;
        }
        _ctr = _ctr + 1;
    }

    this.hide = function()
    {
        _ctr = _ctr - 1;
        if (_ctr < 1)
        {
            _ctr = 0;
            _shown = false;
            if (typeof lineItemContainer == "undefined")
            {
                unblockPage();
            }
            else
            {
                hideSpinnerLarge(lineItemContainer);
            }
        }
    }
}

var cartSpinner = new CartSpinner();

var CartError = function()
{
    var _errorIds;

    function _init()
    {
        if (_errorIds == null)
            _errorIds = [];
    }

    this.addError = function(itemId)
    {
        _init();
        if (_errorIds[itemId] == null)
        {
            _errorIds.push(itemId);
        }
    }

    this.count = function()
    {
        _init();
        return _errorIds.length;
    }

    this.errorsLeft = function()
    {
        _init();
        var isValid = true;
        var _this = this;
        for (var index = 0; index < _errorIds.length; index++)
        {
            if (_errorIds[index] != null)
            {
                var errorElem = document.getElementById(_errorIds[index]);
                if (errorElem == null)
                {
                    _errorIds = [];
                    break;
                }
                if (errorElem.style.display != 'none')
                {
                    isValid = false;
                }
            }
        }

        if (isValid)
        {
            blockPage();
        }

        return isValid;
    }

    this.removeError = function(itemId)
    {
        _init();
        if (_errorIds && _errorIds[itemId] != null)
        {
            _errorIds.splice(_errorIds[itemId], 1);
        }
    }

    this.clear = function()
    {
        _errorIds = [];
    }
}

var cartError = new CartError();

var AddItemSpinner = function()
{
    var _shown = false;
    var _ctr = 0;
    this.show = function()
    {
        if (_shown === false)
        {
            if (typeof AddItemControlDivID == "undefined")
            {
                blockPage();
            }
            else
            {
                showSpinnerLarge(AddItemControlDivID);
            }
            _shown = true;
        }
        _ctr = _ctr + 1;
    }

    this.hide = function()
    {
        _ctr = _ctr - 1;
        if (_ctr < 1)
        {
            _ctr = 0;
            _shown = false;
            if (typeof AddItemControlDivID == "undefined")
            {
                unblockPage();
            }
            else
            {
                hideSpinnerLarge(AddItemControlDivID);
            }
        }
    }
}

function Cart_AddToDittoCustomer(lnkRemove, lineItemId, qty, priceType, placedPrice)
{
    var itemId = $get(lineItemId).value.split(',');
    var id = itemId[1];
    var windowIds = new Object();
    options = {};
    options.resize = true;
    options.PopupTitle = "SaM";
    //var url = AddProductWithProductIdURL + id + "&quantity=" + qty + "&priceType=" + priceType + "&placedPrice=" + placedPrice;
    var url = AddProductWithProductIdURL + id + "&quantity=" + qty + "&placedPrice=" + placedPrice;
    Cart_ShowMessage("", null);  // Clear Message
    cartPopupSuccessMessage = ItemsAddedSuccessPhrase;
    var wnd = new AmwayPopupWindow(usrCartPopupControl, options);
    wnd.showWindow(url, 550, 200, true);
    return false;
}
function Cart_AddToShoppingList(lnkRemove, lineItemId, qty, createList, priceType, placedPrice)
{
    var itemId = $get(lineItemId).value.split(',');
    var id = itemId[1];
    var windowIds = new Object();
    options = {};
    options.resize = true;
    if (createList === null || createList === 'undefined')
    {
        createList = false;
    }
    Cart_ShowMessage("", null);  // Clear Message
    //var url = AddToShoppingListURL + "=" + id + "&quantity=" + qty + "&createList=" + createList + "&priceType=" + priceType + "&placedPrice=" + placedPrice;
    var url = AddToShoppingListURL + "=" + id + "&quantity=" + qty + "&createList=" + createList + "&placedPrice=" + placedPrice;
    if (typeof shoppingListID !== 'undefined')
    {
        url = url + "&shoppingListID=" + shoppingListID;
    }
    cartPopupSuccessMessage = ItemsAddedSuccessPhrase;
    var wnd = new AmwayPopupWindow(usrCartPopupControl, options);
    wnd.showWindow(url, 550, 300, true);

    return false;
}

function Cart_AddSupplementToShoppingListCustomer(packetName, packetDetails, createList)
{
    var itemColl = BuildItemCollectionFromPacket(packetName, packetDetails);
    if (itemColl.length > 0)
    {
        Amway.Core.Web.UI.ShoppingList.ShoppingListDetailsControl.AddToOtherShoppingList(itemColl, function(response)
        {
            if (response.error != null)
            {
                alert(response.error.Message);
            }
            else if (response.value != null)
            {
                var DestinationType = response.value;
                Cart_OpenCompactControl(createList, DestinationType);
            }
        });
    }
    return false;
}

function Cart_AddSupplementToDittoCustomer(packetName, packetDetails, createList)
{
    var itemColl = BuildItemCollectionFromPacket(packetName, packetDetails);
    if (itemColl.length > 0)
    {
        Amway.Core.Web.UI.ShoppingList.ShoppingListDetailsControl.AddItemsToDitto(itemColl, function(response)
        {
            if (response.error != null)
            {
                alert(response.error.Message);
            }
            else if (response.value != null)
            {
                var DestinationType = response.value;
                Cart_OpenCompactControl(createList, DestinationType);
            }
        });
    }
    return false;
}

function Cart_OpenCompactControl(createList, DestinationType)
{
    var windowIds = new Object();
    options = {};
    options.resize = true;
    var wnd = new AmwayPopupWindow(usrCartPopupControl, options);
    if (DestinationType === "ShoppingList")
    {
        var url = ShoppingListCompactURL;
        if (typeof createList !== 'undefined')
        {
            url = url + createList;
        }
        else
        {
            url = url + "false";
        }
        if (typeof shoppingListID !== 'undefined')
        {
            url = url + "&shoppingListID=" + shoppingListID;
        }
    }
    else if (DestinationType === "Ditto")
    {
        var url = AddProductToDittoURL + true;
    }
    shoppingListPopupCloseMessage = ItemsAddedSuccessPhrase;
    wnd.showWindow(url, 550, 250, true);
}

function CartPopupControlClose(sender, args)
{
    // NOTE: This function is called when the popup window closes no matter WHO opened it.
    // cartPopupSuccessMessage should be set by the method that invokes the Window Open command.

    var contentWnd = sender.get_contentFrame().contentWindow;
    if (contentWnd.ReturnValue == "true")
    {
        Cart_ShowMessage(cartPopupSuccessMessage, AmwayNotificationType.Information);
    }
    sender._titleElement.innerHTML = "";
    sender.SetUrl("about:blank");
}
function Cart_ShowMessage(message, messageType)
{
    if (typeof (errorMsg) != 'undefined')
    {
        if (message.length > 0)
        {
            errorMsg.DisplayPhrase(messageType, message);
        }
        else
        {
            errorMsg.Show(false);
        }
    }
}

var addItemSpinner = new AddItemSpinner();

function doClick(buttonName, e)
{
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13)
    {
        //Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn != null)
        { //If we find the button click it
            btn.click();
            // event is undefined in Firefox.
            if ((typeof event != "undefined") && (event != null) && (event.keyCode != null))
                event.keyCode = 0
        }
    }
}



var JSON = JSON || {};


// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function(obj)
{

    var t = typeof (obj);
    if (t != "object" || obj === null)
    {

        // simple data type
        if (t == "string") obj = '"' + obj + '"';
        return String(obj);

    }
    else
    {

        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);

        for (n in obj)
        {
            v = obj[n]; t = typeof (v);

            if (t == "string") v = '"' + v + '"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);

            json.push((arr ? "" : '"' + n + '":') + String(v));
        }

        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

function EmptyCartConfirm(val)
{
    if (confirm(val))
    {
        if (typeof blockPageNoValidation == "function")
        {
            blockPageNoValidation();
        }
        __doPostBack('EmptyShoppingCart', '');
        return false;  // Added this because the page was doing a double postabck.
        //return true;
    }
    else
    {
        return false;
    }
}

function navigateTo(src, url)
{
    if (typeof url == "string")
    {
        window.location = url;
    }
    return false;
}

function closeShoppingListMenu(src, loginUrl)
{
    //reference needed to the dialog element of the popup
    $($(src).parent().parent().parent()[0]).dialog('close');
    window.top.location.href = loginUrl;
    return false;
}

