Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Imports System.Xml
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Common
Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library.EntityMemberServices
Imports CharterDotCom.CommonEntities.Library.EntityEBSServices
Imports CharterDotCom.CommonEntities.Library.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
Imports CharterDotCom.CommonEntities.Library.EntityG2BServices
Imports CharterDotCom.WebSite.Library
Imports CharterDotCom.WebSite.Library.BLCommon
Imports Utilities

Partial Class Order_AffiliateChooseOptions
    Inherits CharterCMSPage

    ' Step 1 (Page_Load event): update the xml document based on the business components
    ' Step 2 (Page_Load event): create the controls based on the xml document (hiding rows containing controls of child features) 
    ' Step 3 (postback events): change the property values of the business components and update the xml document for the control causing the postback 
    ' Step 4 (Page_PreRender event): change the property values of the business components and update the xml document by applying default values (showing rows)
    ' Step 5 (Page_PreRender event): modify controls and show controls based on the business components

    Private _flag As Integer
    Private _document As XmlDocument
    Private _control As Dictionary(Of String, Control)
    Private TotalViewID As String
    Private DigitalPackageID As String

    '########################################################################
    'MODIFICATION   ROD COPELAND    DIGITAL REPACKAGING     SEPT 18, 2008
    '########################################################################
    Private customizationToDiscount1 As String = "413407"
    Private customizationToDiscount2 As String = "413408"
    Private customizationToDiscount3 As String = "414331" ' 1 free Premium channel
    Private customizationToDiscount4 As String = "413410" ' 2 free Premium channels
    '########################################################################

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetPageTitle("Choose Options")
        Dim acct As IAccount = AccountManager.Instance.GetAccount()
        If acct IsNot Nothing Then
            If (acct.AffliateID = CharterDotCom.CommonEntities.Library.Common.m_CHARTER_AFFLIATE_ID) Then
                Response.Redirect("ChooseOptions.aspx")
            End If
        End If

        Dim catalog As ICatalog
        Dim cart As ICart
        Dim item As KeyValuePair(Of String, ICartItem)
        Dim subItem As KeyValuePair(Of String, ISubCartItem)

        If Not Page.IsPostBack Then
            Me.Master.OrphanPage = True

            If AccountManager.Instance.GetAccount().ExistingService IsNot Nothing Then
                ucOrderStep.Visible = False
                ucOrderStep2.Visible = True
            Else
                ucOrderStep.Visible = True
                ucOrderStep2.Visible = False
            End If
        End If

        ' clear the message

        ltrMessage.Text = String.Empty

        ' retrieve catalog and cart

        catalog = AffliateCatalogManager.Instance.GetCatalog()

        If catalog Is Nothing Then
            Throw New MissingCatalogException()
        End If

        cart = catalog.Cart

        ' assign shopping cart's cart property
        ucShoppingCart.Cart = catalog.Cart

        ' initialize _document and _control

        _document = New XmlDocument()
        _document.LoadXml(Application("AffiliateChooseOptions"))

        _control = New Dictionary(Of String, Control)()

        ' update the _document setting attributes and adding new elements
        'SetViewIds()

        For Each item In cart.CartItems
            If item.Value.Type = ItemType.Bundle Then
                For Each subItem In item.Value.Children
                    UpdateDocument(subItem.Value)
                Next
            ElseIf item.Value.Type = ItemType.ServicePlan Then
                UpdateDocument(item.Value)
            End If
        Next

        '########################################################################
        'MODIFICATION   ROD COPELAND    DIGITAL REPACKAGING     SEPT 18, 2008
        '########################################################################
        'THIS CALL LOADS THE CONTROLS BASED UPON WHAT CUSTOMATION FEATURES 
        'AND FEATURE CHOICES ARE IN THE CARTITEMS ADDED TO THE CART. WILL 
        'LOAD THE CATAGORY FIRST, LIKE CABLE PRODUCTS, THEN IT WILL LOOP 
        'TO CALL LOADCATEGORY WHICH INTERNALLY CALLS LOADFEATURE IF FEATURES 
        'ARE AVAILABLE FOR THE CATEGORY.  THIS IS WHERE TO START WHEN FINDING 
        'HOW THE OPTIONS AND PRICES THAT GET WRITTEN TO THE PAGE.
        '########################################################################
        Call LoadProductCategoriesToThePage()



    End Sub

    Private Sub LoadProductCategoriesToThePage()
        Dim elem As XmlElement
        Dim ctrl As Control

        ' create controls for the "CableTV" category

        elem = _document.SelectSingleNode("/chooseOptions/category[@id='1' and @enabled='true']")

        If elem IsNot Nothing Then
            ctrl = LoadCategory(elem)
            pnlCableTV.Controls.Add(ctrl)
            pnlCableTV.Visible = True
        End If

        ' create controls for the "Internet" category

        elem = _document.SelectSingleNode("/chooseOptions/category[@id='2' and @enabled='true']")

        If elem IsNot Nothing Then
            ctrl = LoadCategory(elem)
            pnlInternet.Controls.Add(ctrl)
            pnlInternet.Visible = True
        End If

        ' create controls for the "Telephone" category

        elem = _document.SelectSingleNode("/chooseOptions/category[@id='3' and @enabled='true']")

        If elem IsNot Nothing Then
            ctrl = LoadCategory(elem)
            pnlTelephone.Controls.Add(ctrl)
            pnlTelephone.Visible = True
        End If

        ' create controls for the "singleton" feature

        elem = _document.SelectSingleNode("/chooseOptions/category/feature[@enabled='true' and @group]")
        If elem IsNot Nothing Then
            pnlCommon.Controls.Add(LoadFeature(elem))
            pnlCommon.Visible = True
        End If
    End Sub

    Private Sub UpdateDocument(ByVal servicePlan As ICartItem)
        Dim feature As KeyValuePair(Of String, ISubCartItem)
        Dim choice As KeyValuePair(Of String, ISubCartItem)
        Dim elem As XmlElement
        Dim childElem As XmlElement
        Dim i As Integer

        Select Case servicePlan.Category
            Case Category.Cable
                elem = _document.SelectSingleNode("/chooseOptions/category[@id='1']")
                SetAttribute(elem, "enabled", "true")
            Case Category.HSD
                elem = _document.SelectSingleNode("/chooseOptions/category[@id='2']")
                SetAttribute(elem, "enabled", "true")
            Case Category.Telephoney
                elem = _document.SelectSingleNode("/chooseOptions/category[@id='3']")
                SetAttribute(elem, "enabled", "true")
        End Select

        '######################################################################################
        'The following code is applied to all feature/choice node sets regardless of level
        '######################################################################################

        For Each feature In servicePlan.Children
            If servicePlan.Category = Category.Cable Then
                If feature.Value.Children IsNot Nothing AndAlso feature.Value.Children.ContainsKey(CStr(HttpContext.Current.Application(CharterDotCom.CommonEntities.Library.Common.m_TOTALVIEWID))) Then
                    elem = _document.SelectNodes(String.Format("//feature[@id='{0}']", feature.Value.ID)).Item(1)
                Else
                    elem = _document.SelectSingleNode(String.Format("//feature[@id='{0}']", feature.Value.ID))
                End If
            Else
                elem = _document.SelectSingleNode(String.Format("//feature[@id='{0}']", feature.Value.ID))
            End If

            If elem IsNot Nothing Then
                ' set attributes for the feature element

                SetAttribute(elem, "enabled", "true")
                SetAttribute(elem, "price", feature.Value.ListPrice)

                If feature.Value.Name <> String.Empty Then
                    SetAttribute(elem, "name", feature.Value.Name)
                End If

                If feature.Value.Description <> String.Empty Then
                    SetAttribute(elem, "description", feature.Value.Description)
                End If

                If feature.Value.IsSelected Then
                    SetAttribute(elem, "selected", "true")
                End If

                If feature.Value.Children.Count = 0 Then
                    SetAttribute(elem, "quantity", feature.Value.Quantity)
                End If

                If elem.Attributes("childControl").Value = "checkbox" Then
                    If feature.Value.MinChoiceSelection > 0 Then
                        SetAttribute(elem, "mustSelect", feature.Value.MinChoiceSelection)
                    End If
                End If

                ' set attributes for the choice elements

                For Each choice In feature.Value.Children
                    childElem = elem.SelectSingleNode(String.Format("choice[@id='{0}']", choice.Value.ID))

                    If childElem IsNot Nothing Then
                        SetAttribute(childElem, "price", choice.Value.ListPrice)

                        If choice.Value.Name <> String.Empty Then
                            SetAttribute(childElem, "name", choice.Value.Name)
                        End If

                        '10/8/2007 Brad Miller - Read Display Price and Price Frequency from database rather than XML
                        'not yet implemented
                        'If choice.Value.IsPriceDisplayed Then
                        '    SetAttribute(childElem, "showPrice", "true")
                        'End If

                        'If choice.Value.PriceFrequency = BLPriceFrequency.Monthly Then
                        '    SetAttribute(childElem, "priceFreq", "monthly")
                        'End If

                        If choice.Value.IsSelected Then
                            SetAttribute(childElem, "selected", "true")
                        End If
                    End If
                Next

                ' set attributes and ADD CHILD NODES for a feature whose MaxSelection > 0

                If feature.Value.MaxSelection > 0 Then
                    For i = feature.Value.MinSelection To feature.Value.MaxSelection
                        childElem = AddChildElement(elem, "choice", "")

                        SetAttribute(childElem, "id", String.Format("{0}_{1}", feature.Value.ID, i))

                        If GetAttribute(elem, "timesPrice") = "true" Then
                            SetAttribute(childElem, "name", String.Format("{0} - {1:C}", i, i * feature.Value.ListPrice))
                        Else
                            SetAttribute(childElem, "name", i)
                        End If

                        If i = feature.Value.Quantity Then
                            SetAttribute(childElem, "selected", "true")
                        End If
                    Next
                End If
            End If
        Next
    End Sub

    Private Function LoadCategory(ByVal elem As XmlElement) As Control
        Dim _table As HtmlTable
        Dim _row As HtmlTableRow
        Dim _cell As HtmlTableCell
        Dim _literal As Literal
        Dim _node As XmlNode
        Dim _nodes As XmlNodeList

        _table = New HtmlTable()
        _table.Attributes("id") = "order"
        _table.Attributes("cellpadding") = "0"
        _table.Attributes("cellspacing") = "0"

        _row = New HtmlTableRow()
        _cell = New HtmlTableCell()

        If elem.Attributes("description") IsNot Nothing Then
            _literal = New Literal()
            _literal.Text = String.Format("<p>{0}</p>", elem.Attributes("description").Value)
            _cell.Controls.Add(_literal)
        End If

        _nodes = elem.SelectNodes("feature[@enabled='true' and not(@group)]")

        For Each _node In _nodes
            _cell.Controls.Add(LoadFeature(_node))
        Next

        _row.Cells.Add(_cell)
        _table.Rows.Add(_row)

        Return _table
    End Function

    Private Function LoadFeature(ByVal elem As XmlElement) As Control
        Dim _table As HtmlTable
        Dim _row As HtmlTableRow
        Dim _cell As HtmlTableCell
        Dim _dropDownList As DropDownList
        Dim _textBox As TextBox
        Dim _radioButton As RadioButton
        Dim _checkBox As CheckBox
        Dim _label As Label
        Dim choiceNode As XmlNode
        Dim choiceNodes As XmlNodeList
        Dim childFeatureNode As XmlNode
        Dim childFeatureNodes As XmlNodeList
        Dim i As Integer

        '######################################################################################
        'The following code is applied to all feature/choice node sets regardless of level
        '######################################################################################
        ' create a table for the feature

        _table = New HtmlTable()
        _table.Attributes("cellpadding") = "0"
        _table.Attributes("cellspacing") = "0"

        ' create a row (and a table border) if the feature has a name

        If GetAttribute(elem, "name") <> String.Empty Then
            _cell = New HtmlTableCell()
            _cell.Attributes.Add("colspan", "3")
            _cell.InnerHtml = GetAttribute(elem, "name")
            If _cell.InnerHtml = "Wire Maintenance Protection" Then
                _cell.InnerHtml = "<b>Wire Maintenace Protection </b>"
            End If
            _row = New HtmlTableRow()
            _row.Attributes("id") = "sub"
            _row.Cells.Add(_cell)
            _table.Rows.Add(_row)
        End If

        ' create a row if the feature has a description

        If GetAttribute(elem, "description") <> String.Empty Then
            _cell = New HtmlTableCell()
            _cell.Attributes.Add("colspan", "3")
            _cell.InnerHtml = GetAttribute(elem, "description")

            _row = New HtmlTableRow()
            _row.Cells.Add(_cell)
            _table.Rows.Add(_row)
        End If

        If GetAttribute(elem, "childControl") = "listitem" Then
            ' create a dropdown list

            _dropDownList = New DropDownList()
            _dropDownList.ID = String.Format("ddl_{0}", elem.Attributes("id").Value)
            _dropDownList.Width = 250
            _dropDownList.AutoPostBack = True
            AddHandler _dropDownList.SelectedIndexChanged, AddressOf DropDownList_SelectedIndexChanged
            _control.Add(_dropDownList.ID, _dropDownList)

            choiceNodes = elem.SelectNodes("choice")

            For Each choiceNode In choiceNodes
                _dropDownList.Items.Add(New ListItem(GetAttribute(choiceNode, "name"), GetAttribute(choiceNode, "id")))
            Next

            _cell = New HtmlTableCell()
            _cell.Attributes.Add("colspan", "3")
            _cell.Style.Add("text-align", "left")
            _cell.Controls.Add(_dropDownList)

            _row = New HtmlTableRow()
            _row.Cells.Add(_cell)
            _table.Rows.Add(_row)

            ' render child features

            childFeatureNodes = elem.SelectNodes("feature[@enabled='true']")

            i = 1

            For Each childFeatureNode In childFeatureNodes
                ' create a row for each child feature 

                _row = New HtmlTableRow()
                _row.ID = String.Format("row_{0}_{1}", elem.Attributes("id").Value, i)
                _row.Visible = False ' HIDE CHILD ROW for a dropdown list 
                _control.Add(_row.ID, _row)


                _cell = New HtmlTableCell()
                _cell.Attributes.Add("colspan", "3")
                _cell.Style.Add("padding-left", "50px")

                _cell.Controls.Add(LoadFeature(childFeatureNode))

                _row.Cells.Add(_cell)
                _table.Rows.Add(_row)

                i = i + 1
            Next
        ElseIf GetAttribute(elem, "childControl") = "textbox" Then
            ' create a text box

            _textBox = New TextBox()
            _textBox.ID = String.Format("txt_{0}", elem.Attributes("id").Value)
            _textBox.Width = 250
            _textBox.AutoPostBack = True
            AddHandler _textBox.TextChanged, AddressOf TextBox_TextChanged
            _control.Add(_textBox.ID, _textBox)

            _cell = New HtmlTableCell()
            _cell.Attributes.Add("colspan", "3")
            _cell.Style.Add("text-align", "left")
            _cell.Controls.Add(_textBox)

            _row = New HtmlTableRow()
            _row.Cells.Add(_cell)
            _table.Rows.Add(_row)
        End If

        choiceNodes = elem.SelectNodes("choice")

        For Each choiceNode In choiceNodes
            _row = New HtmlTableRow()

            If GetAttribute(elem, "childControl") = "hidden" Then
                ' create a label

                _label = New Label()
                _label.ID = String.Format("lbl_{0}", choiceNode.Attributes("id").Value)
                _label.Text = choiceNode.Attributes("name").Value
                _control.Add(_label.ID, _label)

                _cell = New HtmlTableCell()
                _cell.Attributes.Add("colspan", "2")
                _cell.Controls.Add(_label)

                _row.Cells.Add(_cell)
            Else
                _cell = New HtmlTableCell()

                If GetAttribute(elem, "childControl") = "radiobutton" Then
                    _radioButton = New RadioButton()
                    _radioButton.ID = String.Format("rdo_{0}", choiceNode.Attributes("id").Value)
                    _radioButton.Text = choiceNode.Attributes("name").Value
                    _radioButton.GroupName = elem.Attributes("id").Value
                    _radioButton.AutoPostBack = True
                    AddHandler _radioButton.CheckedChanged, AddressOf RadioButton_CheckedChanged
                    _control.Add(_radioButton.ID, _radioButton)

                    _cell.Controls.Add(_radioButton)
                ElseIf GetAttribute(elem, "childControl") = "checkbox" Then
                    _checkBox = New CheckBox()
                    _checkBox.ID = String.Format("chk_{0}", choiceNode.Attributes("id").Value)
                    _checkBox.Text = choiceNode.Attributes("name").Value
                    _checkBox.AutoPostBack = True
                    AddHandler _checkBox.CheckedChanged, AddressOf CheckBox_CheckedChanged
                    _control.Add(_checkBox.ID, _checkBox)

                    _cell.Controls.Add(_checkBox)
                ElseIf GetAttribute(elem, "childControl") = "listitem" Then
                    Continue For
                ElseIf GetAttribute(elem, "childControl") = "textbox" Then
                    Continue For
                Else
                    Continue For
                End If

                _row.Cells.Add(_cell)

                _cell = New HtmlTableCell()
                _cell.Style("text-align") = "right"

                If GetAttribute(choiceNode, "showLearnMore") = "true" Then
                    _cell.InnerHtml = String.Format("<a href=""javascript:void(0)"" onClick=""javascript:window.open('../Visitors/ChoiceDetail.aspx?{0}={1}','mywindow','width=500,height=500,scrollbars=yes,resizeable=yes')"">Learn More</a>", QueryStringName.ChoiceID, choiceNode.Attributes("id").Value)
                End If

                _row.Cells.Add(_cell)
            End If

            _cell = New HtmlTableCell()
            _cell.Style("text-align") = "right"

            '10/26/2007 Brad Miller - Read Display Price and Price Frequency from database rather than XML
            'not yet implemented
            'If GetAttribute(choiceNode, "price") <> String.Empty Then
            '    If GetAttribute(choiceNode, "showPrice") = "true" Then
            '        _cell.InnerHtml = String.Format("${0:C}", GetAttribute(choiceNode, "price"))
            '        If GetAttribute(choiceNode, "priceFreq") = "monthly" Then
            '            _cell.InnerHtml &= ("/mo")
            '        End If
            '    End If
            'End If
            If GetAttribute(choiceNode, "price") <> String.Empty Then
                If GetAttribute(choiceNode, "showPrice") = "true" Then
                    _cell.InnerHtml = String.Format("${0:C}", GetAttribute(choiceNode, "price"))
                ElseIf GetAttribute(choiceNode, "showPrice") = "monthly" Then
                    _cell.InnerHtml = String.Format("${0:C}/mo", GetAttribute(choiceNode, "price"))

                End If
            End If

            _row.Cells.Add(_cell)

            _table.Rows.Add(_row)





            '######################################################################################################
            'M O D I F I C A TI O N     9/26/2007     ROD COPELAND
            '######################################################################################################
            'EMERGENCY FIX REQUESTED BY JIM GALLAGHER TO ADD THE MIN REQIREMENTS DESCRIPTION RIGHT AFTER THE 
            'SELFINSTALL HSI OPTION. LOOKING FOR THE 'SELF INSTALLATION, HIGH SPEED INTERNET' OPTION BEING WRITTEN.
            '######################################################################################################
            If choiceNode.Attributes("id").Value = "499253" Then
                Dim _descriptionRow As New HtmlTableRow()
                Dim _descriptionCell As New HtmlTableCell()
                Dim _descriptionLabel As New Label
                _descriptionLabel.Text = "*Minimum Requirement: Must be active Digital Cable subscriber.  All others please select professional installation option."
                _descriptionCell.Controls.Add(_descriptionLabel)
                _descriptionCell.Attributes.Add("colspan", "3")
                _descriptionRow.Cells.Add(_descriptionCell)
                _table.Rows.Add(_descriptionRow)
            End If
            '######################################################################################################




            ' render child features

            childFeatureNodes = choiceNode.SelectNodes("feature[@enabled='true']")

            If childFeatureNodes.Count > 0 Then
                _row = New HtmlTableRow()
                _row.ID = String.Format("row_{0}", choiceNode.Attributes("id").Value)
                _control.Add(_row.ID, _row)

                ' HIDE CHILD ROW for a radio button or a check box

                Select Case GetAttribute(elem, "childControl")
                    Case "radiobutton"
                        _row.Visible = False
                    Case "checkbox"
                        _row.Visible = False
                End Select

                _cell = New HtmlTableCell()
                _cell.Attributes.Add("colspan", "3")
                _cell.Style.Add("padding-left", "50px")

                For Each childFeatureNode In childFeatureNodes
                    _cell.Controls.Add(LoadFeature(childFeatureNode))
                Next

                _row.Cells.Add(_cell)
                _table.Rows.Add(_row)
            End If
        Next

        Return _table
    End Function

    Private Sub DropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ddl As DropDownList
        Dim id As String
        Dim itemID As String
        Dim quantity As Integer
        Dim featureNode As XmlNode
        Dim choiceID As String
        Dim choiceNode As XmlNode
        Dim choiceNodes As XmlNodeList

        ddl = CType(sender, DropDownList)
        id = ddl.ID.Substring(4)
        itemID = ddl.SelectedValue

        If itemID.IndexOf("_") > 0 Then
            quantity = CType(itemID.Substring(itemID.IndexOf("_") + 1), Integer)

            _flag = _flag + 1
            AffliateCatalogManager.Instance.AddSubCartItem(id, quantity, New Notify(AddressOf OnNotification))

            featureNode = _document.SelectSingleNode(String.Format("//feature[@id='{0}']", id))
            featureNode.Attributes("quantity").Value = quantity

            choiceNodes = _document.SelectNodes(String.Format("//feature[@id='{0}']/choice", id))

            For Each choiceNode In choiceNodes
                choiceID = choiceNode.Attributes("id").Value()

                If choiceID = itemID Then
                    SetAttribute(choiceNode, "selected", "true")
                    SetChildValues(choiceID, id)
                Else
                    SetAttribute(choiceNode, "selected", "false")
                    UnsetChildValues(choiceID, id)
                End If
            Next
        Else
            _flag = _flag + 1
            AffliateCatalogManager.Instance.AddSubCartItemWithParent(itemID, id, New Notify(AddressOf OnNotification))

            choiceNodes = _document.SelectNodes(String.Format("//feature[@id='{0}']/choice", id))

            For Each choiceNode In choiceNodes
                choiceID = choiceNode.Attributes("id").Value()

                If choiceID = itemID Then
                    SetAttribute(choiceNode, "selected", "true")
                    SetChildValues(choiceID, id)
                Else
                    SetAttribute(choiceNode, "selected", "false")
                    UnsetChildValues(choiceID, id)
                End If
            Next
        End If
    End Sub

    Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim tb As TextBox
        Dim id As String

        tb = CType(sender, TextBox)
        id = tb.ID.Substring(4)

        _flag = _flag + 1
        AffliateCatalogManager.Instance.AddSubCartItem(id, tb.Text, New Notify(AddressOf OnNotification))
    End Sub

    Private Sub RadioButton_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim rb As RadioButton
        Dim id As String
        Dim featureID As String
        Dim choiceID As String
        Dim choiceNode As XmlNode
        Dim choiceNodes As XmlNodeList

        rb = CType(sender, RadioButton)
        id = rb.ID.Substring(4)
        featureID = GetParentID(id)

        If rb.Checked Then
            _flag = _flag + 1
            AffliateCatalogManager.Instance.AddSubCartItemWithParent(id, featureID, New Notify(AddressOf OnNotification))

            choiceNodes = _document.SelectNodes(String.Format("//feature[@id='{0}']/choice", featureID))

            For Each choiceNode In choiceNodes
                choiceID = choiceNode.Attributes("id").Value()

                If choiceID = id Then
                    SetAttribute(choiceNode, "selected", "true")
                    SetChildValues(choiceID, featureID)
                Else
                    _flag = _flag + 1
                    AffliateCatalogManager.Instance.RemoveSubCartItem(choiceID, featureID, New Notify(AddressOf OnNotification))

                    SetAttribute(choiceNode, "selected", "false")
                    UnsetChildValues(choiceID, featureID)
                End If
            Next
        Else
            'this branch is never entered
            '_flag = _flag + 1
            'affliatecatalogmanager.Instance.RemoveSubCartItem(id, featureID, New Notify(AddressOf OnNotification))
            'UnsetChildValues(id, featureID)
        End If
    End Sub

    Private Sub CheckBox_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim cb As CheckBox
        Dim id As String
        Dim featureID As String
        Dim choiceNode As XmlNode

        cb = CType(sender, CheckBox)
        id = cb.ID.Substring(4)
        featureID = GetParentID(id)

        choiceNode = _document.SelectSingleNode(String.Format("//choice[@id='{0}']", id))

        If cb.Checked Then
            _flag = _flag + 1
            AffliateCatalogManager.Instance.AddSubCartItemWithParent(id, featureID, New Notify(AddressOf OnNotification))
            SetAttribute(choiceNode, "selected", "true")
            SetChildValues(id, featureID)
        Else
            _flag = _flag + 1
            AffliateCatalogManager.Instance.RemoveSubCartItem(id, featureID, New Notify(AddressOf OnNotification))
            SetAttribute(choiceNode, "selected", "false")
            UnsetChildValues(id, featureID)
        End If
    End Sub

    Private Sub SetChildValues(ByVal choiceID As String, ByVal featureID As String)
        Dim elem As XmlElement
        Dim node As XmlNode
        Dim nodes As XmlNodeList
        Dim childNode As XmlNode

        elem = _document.SelectSingleNode(String.Format("//choice[@id='{0}']", choiceID))

        nodes = elem.SelectNodes("feature[@enabled='true']")

        For Each node In nodes
            If GetAttribute(node, "childControl") = "hidden" Then
                childNode = node.SelectSingleNode("choice")

                If childNode IsNot Nothing Then
                    _flag = _flag + 1
                    AffliateCatalogManager.Instance.AddSubCartItemWithParent(childNode.Attributes("id").Value, node.Attributes("id").Value, AddressOf OnNotification)
                End If
            End If
        Next
    End Sub

    Private Sub UnsetChildValues(ByVal choiceID As String, ByVal featureID As String)
        Dim elem As XmlElement
        Dim nodes As XmlNodeList
        Dim node As XmlNode
        Dim childNodes As XmlNodeList
        Dim childNode As XmlNode
        Dim id As String

        elem = _document.SelectSingleNode(String.Format("//choice[@id='{0}']", choiceID))

        nodes = elem.SelectNodes("feature[@enabled='true']")

        For Each node In nodes
            Select Case GetAttribute(node, "childControl")
                Case "listitem"
                    childNode = node.SelectSingleNode("choice[@selected='true']")

                    If childNode IsNot Nothing Then
                        id = childNode.Attributes("id").Value

                        If id.IndexOf("_") > 0 Then
                            _flag = _flag + 1
                            AffliateCatalogManager.Instance.AddSubCartItem(node.Attributes("id").Value, 0, AddressOf OnNotification)
                        Else
                            _flag = _flag + 1
                            AffliateCatalogManager.Instance.RemoveSubCartItem(id, node.Attributes("id").Value, AddressOf OnNotification)
                        End If

                        SetAttribute(childNode, "selected", "false")
                    End If
                Case "textbox"
                    _flag = _flag + 1
                    AffliateCatalogManager.Instance.AddSubCartItem(node.Attributes("id").Value, String.Empty, AddressOf OnNotification)
                Case "hidden"
                    childNode = node.SelectSingleNode("choice")

                    If childNode IsNot Nothing Then
                        _flag = _flag + 1
                        AffliateCatalogManager.Instance.RemoveSubCartItem(childNode.Attributes("id").Value, node.Attributes("id").Value, AddressOf OnNotification)
                    End If
                Case "radiobutton"
                    childNode = node.SelectSingleNode("choice[@selected='true']")

                    If childNode IsNot Nothing Then
                        _flag = _flag + 1
                        AffliateCatalogManager.Instance.RemoveSubCartItem(childNode.Attributes("id").Value, node.Attributes("id").Value, AddressOf OnNotification)
                        SetAttribute(childNode, "selected", "false")
                    End If
                Case "checkbox"
                    childNodes = node.SelectNodes("choice[@selected='true']")

                    If childNodes IsNot Nothing Then
                        For Each childNode In childNodes
                            _flag = _flag + 1
                            AffliateCatalogManager.Instance.RemoveSubCartItem(childNode.Attributes("id").Value, node.Attributes("id").Value, AddressOf OnNotification)
                            SetAttribute(childNode, "selected", "false")
                        Next
                    End If
            End Select
        Next
    End Sub

    Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBack.Click
        While _flag <> 0
            Threading.Thread.Sleep(100)
        End While

        Response.Redirect("AffiliateUpSell.aspx")
    End Sub

    Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNext.Click
        Dim featureNode As XmlNode
        Dim featureNodes As XmlNodeList
        Dim choiceNodes As XmlNodeList
        Dim mustSelect As Integer
        Dim _format As String
        Dim sb As StringBuilder
        Dim txt As TextBox

        While _flag <> 0
            Threading.Thread.Sleep(100)
        End While

        If Page.IsValid Then
            sb = New StringBuilder()

            featureNodes = _document.SelectNodes("//feature[@enabled='true' and @mustSelect]")

            For Each featureNode In featureNodes
                mustSelect = CType(featureNode.Attributes("mustSelect").Value, Integer)

                choiceNodes = featureNode.SelectNodes("choice[@selected='true']")

                If choiceNodes.Count < mustSelect Then
                    sb.AppendFormat("<li>You must select at least {0} item(s) from the {1} list</li>", mustSelect, featureNode.Attributes("name").Value)
                End If
            Next

            featureNodes = _document.SelectNodes("//feature[@enabled='true' and @format]")

            For Each featureNode In featureNodes
                _format = featureNode.Attributes("format").Value

                If _format = "phoneNumber" Then
                    txt = CType(_control("txt_" & featureNode.Attributes("id").Value), TextBox)

                    If txt.Text <> String.Empty Then
                        If Not Regex.IsMatch(txt.Text, "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}|\(?\d{3}\)?[-\s.\s ]?\d{3}[-. ]\d{4}|(\d{10})") Then
                            sb.AppendFormat("<li>The value of {0} must be a phone number</li>", featureNode.Attributes("name").Value)
                        End If
                        Dim _phone As StringBuilder
                        Dim i As Integer
                        Dim c As Char
                        _phone = New StringBuilder
                        For i = 0 To txt.Text.Length - 1
                            c = CType(txt.Text(i), Char)
                            If Asc(c) >= 48 And Asc(c) <= 57 Then
                                _phone.Append(c)
                            End If
                        Next
                        txt.Text = _phone.ToString()
                        'Else
                        '	sb.AppendFormat("<li>You must enter a value for {0}</li>", featureNode.Attributes("name").Value)
                    End If
                End If
            Next

            If sb.ToString().Length = 0 Then
                Response.Redirect("AffiliateEnterInformation.aspx")
            Else
                sb.Insert(0, "<ul style='color:red'>")
                sb.Append("</ul>")
                ltrMessage.Text = sb.ToString()
            End If
        End If
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        Dim catalog As ICatalog
        Dim cart As ICart
        Dim item As KeyValuePair(Of String, ICartItem)
        Dim subItem As KeyValuePair(Of String, ISubCartItem)

        '########################################################################
        'MODIFICATION   ROD COPELAND    DIGITAL REPACKAGING     SEPT 18, 2008
        '########################################################################
        Dim applyDiscountPriceAsNeeded As Boolean = False
        Dim discountedCustomizationIDCollection As New List(Of String)
        Dim subItem2 As KeyValuePair(Of String, ISubCartItem)
        '#########################################################################

        ' wait for postback events to complete
        Me.ucShoppingCart.HBXInfo_PageName = Me.Master.HBXPageName
        Me.ucShoppingCart.HBXInfo_MLC = Me.Master.HBXMLC

        While _flag <> 0
            Threading.Thread.Sleep(100)
        End While

        catalog = AffliateCatalogManager.Instance.GetCatalog()

        If catalog Is Nothing Then
            Throw New MissingCatalogException()
        End If

        cart = catalog.Cart

        ' handle "forChoice" dependencies

        HandleForChoices()

        ' set default values 

        SetDefaultValues()

        While _flag <> 0
            Threading.Thread.Sleep(100)
        End While

        catalog = AffliateCatalogManager.Instance.GetCatalog()

        If catalog Is Nothing Then
            Throw New MissingCatalogException()
        End If

        cart = catalog.Cart

        ' change the properties of the controls

        For Each item In cart.CartItems
            If item.Value.Type = ItemType.Bundle Then
                For Each subItem In item.Value.Children
                    RenderServicePlan(subItem.Value)
                Next
            ElseIf item.Value.Type = ItemType.ServicePlan Then
                RenderServicePlan(item.Value)
            End If
        Next

        '########################################################################
        '########################################################################
        'MODIFICATION   ROD COPELAND    DIGITAL REPACKAGING     SEPT 18, 2008
        '########################################################################
        For Each item In cart.CartItems
            If Not (item.Value Is Nothing) Then
                If item.Value.Type = ItemType.Bundle Then
                    For Each subItem In item.Value.Children
                        For Each subItem2 In subItem.Value.Children
                            checkDiscountCustomizations(subItem2)
                        Next
                    Next
                Else
                    For Each subItem In item.Value.Children
                        checkDiscountCustomizations(subItem)
                    Next
                End If
            End If
        Next

    End Sub

    Private Sub HandleForChoices()
        Dim featureNode As XmlNode
        Dim featureNodes As XmlNodeList
        Dim featureID As String
        Dim choiceNode As XmlNode
        Dim choiceNodes As XmlNodeList
        Dim choiceID As String
        Dim forChoiceNode As XmlNode
        Dim forChoiceID As String
        Dim ddl As DropDownList
        Dim i As Integer
        Dim found As Boolean

        featureNodes = _document.SelectNodes("//feature[@enabled='true' and @childControl='listitem']")

        For Each featureNode In featureNodes
            featureID = featureNode.Attributes("id").Value
            choiceNodes = featureNode.SelectNodes("choice[@forChoice]")

            For Each choiceNode In choiceNodes
                choiceID = choiceNode.Attributes("id").Value
                forChoiceID = choiceNode.Attributes("forChoice").Value

                forChoiceNode = _document.SelectSingleNode(String.Format("//choice[@id='{0}' and @selected='true']", forChoiceID))

                If forChoiceNode Is Nothing Then
                    ddl = CType(_control("ddl_" & featureID), DropDownList)

                    For i = ddl.Items.Count - 1 To 0 Step -1
                        If ddl.Items(i).Value = choiceID Then
                            ddl.Items.RemoveAt(i)

                            If GetAttribute(choiceNode, "selected") = "true" Then
                                _flag = _flag + 1
                                AffliateCatalogManager.Instance.RemoveSubCartItem(choiceID, featureID, New Notify(AddressOf OnNotification))

                                SetAttribute(choiceNode, "selected", "false")
                                UnsetChildValues(choiceID, featureID)
                            End If

                            Exit For
                        End If
                    Next
                Else
                    ddl = CType(_control("ddl_" & featureID), DropDownList)

                    found = False

                    For i = ddl.Items.Count - 1 To 0 Step -1
                        If ddl.Items(i).Value = choiceID Then
                            found = True
                            Exit For
                        End If
                    Next

                    If Not found Then
                        ddl.Items.Add(New ListItem(GetAttribute(choiceNode, "name"), GetAttribute(choiceNode, "id")))
                    End If
                End If
            Next
        Next
    End Sub

    Private Sub SetDefaultValues()
        Dim featureNode As XmlNode
        Dim featureNodes As XmlNodeList

        featureNodes = _document.SelectNodes("/chooseOptions/category[@enabled='true']/feature[@enabled='true']")

        For Each featureNode In featureNodes
            SetChildDefaultValues(featureNode)
        Next
    End Sub

    Private Sub SetChildDefaultValues(ByVal featureNode As XmlNode)
        Dim selectedChoiceNode As XmlNode
        Dim featureID As String
        Dim defaultChoiceID As String
        Dim node As XmlNode
        Dim nodes As XmlNodeList

        featureID = featureNode.Attributes("id").Value

        If featureNode.Attributes("defaultChoice") IsNot Nothing Or featureNode.Attributes("defaultIndex") IsNot Nothing Then
            selectedChoiceNode = featureNode.SelectSingleNode("choice[@selected='true']")

            If selectedChoiceNode Is Nothing Then

                If featureNode.Attributes("defaultChoice") IsNot Nothing Then
                    defaultChoiceID = featureNode.Attributes("defaultChoice").Value
                    _flag = _flag + 1
                    AffliateCatalogManager.Instance.AddSubCartItemWithParent(defaultChoiceID, featureID, New Notify(AddressOf OnNotification))
                Else
                    defaultChoiceID = String.Format("{0}_{1}", featureID, featureNode.Attributes("defaultIndex").Value)
                    _flag = _flag + 1
                    AffliateCatalogManager.Instance.AddSubCartItem(featureID, CType(featureNode.Attributes("defaultIndex").Value, Integer), New Notify(AddressOf OnNotification))
                End If

                selectedChoiceNode = featureNode.SelectSingleNode(String.Format("choice[@id='{0}']", defaultChoiceID))
                SetAttribute(selectedChoiceNode, "selected", "true")
                SetChildValues(defaultChoiceID, featureID)
            End If
        End If

        nodes = featureNode.SelectNodes("choice[@selected='true']/feature[@enabled='true']")

        For Each node In nodes
            SetChildDefaultValues(node)
        Next
    End Sub

    Private Sub RenderServicePlan(ByVal servicePlan As ICartItem)
        Dim featureNode As XmlNode
        Dim choiceNode As XmlElement
        Dim feature As KeyValuePair(Of String, ISubCartItem)
        Dim choice As KeyValuePair(Of String, ISubCartItem)
        Dim i As Integer
        Dim id As String
        Dim ddl As DropDownList
        Dim ddl2 As DropDownList
        Dim rdo As RadioButton
        Dim chk As CheckBox
        Dim nodes As XmlNodeList
        Dim childNode As XmlNode


        For Each feature In servicePlan.Children
            featureNode = _document.SelectSingleNode(String.Format("//feature[@enabled='true' and @id='{0}']", feature.Value.ID))

            If featureNode IsNot Nothing Then
                Select Case featureNode.Attributes("childControl").Value
                    Case "listitem"
                        If feature.Value.Children.Count = 0 Then
                            ddl = CType(_control("ddl_" & feature.Value.ID), DropDownList)
                            id = ddl.ID.Substring(4)
                            ddl.SelectedValue = feature.Value.ID & "_" & feature.Value.Quantity

                            For i = 1 To ddl.Items.Count
                                If _control.ContainsKey(String.Format("row_{0}_{1}", id, i)) Then
                                    If i <= feature.Value.Quantity Then
                                        _control(String.Format("row_{0}_{1}", id, i)).Visible = True
                                    Else
                                        _control(String.Format("row_{0}_{1}", id, i)).Visible = False
                                    End If
                                End If
                            Next

                            nodes = _document.SelectNodes(String.Format("//feature[@id='{0}']/feature[@childControl='listitem']", id))

                            For i = 0 To nodes.Count - 1
                                ddl2 = _control(String.Format("ddl_{0}", nodes(i).Attributes("id").Value))

                                If i < feature.Value.Quantity Then
                                    childNode = nodes(i).SelectSingleNode("choice[@selected='true']")

                                    If childNode Is Nothing Then
                                        childNode = nodes(i).SelectNodes("choice")(0)
                                        SetAttribute(childNode, "selected", "true")

                                        _flag = _flag + 1
                                        AffliateCatalogManager.Instance.AddSubCartItemWithParent(childNode.Attributes("id").Value, nodes(i).Attributes("id").Value, New Notify(AddressOf OnNotification))

                                        ddl2.SelectedIndex = 0
                                    End If
                                End If
                            Next

                            For i = nodes.Count - 1 To 0 Step -1
                                ddl2 = _control(String.Format("ddl_{0}", nodes(i).Attributes("id").Value))

                                If i >= feature.Value.Quantity Then
                                    childNode = nodes(i).SelectSingleNode("choice[@selected='true']")

                                    If childNode IsNot Nothing Then
                                        SetAttribute(childNode, "selected", "false")

                                        _flag = _flag + 1
                                        AffliateCatalogManager.Instance.RemoveSubCartItem(childNode.Attributes("id").Value, nodes(i).Attributes("id").Value, New Notify(AddressOf OnNotification))
                                    End If

                                    ddl2.SelectedIndex = -1
                                End If
                            Next
                        Else
                            For Each choice In feature.Value.Children
                                choiceNode = featureNode.SelectSingleNode(String.Format("choice[@id='{0}']", choice.Value.ID))

                                If choice.Value.IsSelected Then
                                    CType(_control("ddl_" & feature.Value.ID), DropDownList).SelectedValue = choice.Value.ID

                                    If _control.ContainsKey(String.Format("row_{0}", choice.Value.ID)) Then
                                        _control(String.Format("row_{0}", choice.Value.ID)).Visible = True
                                    End If
                                Else
                                    If _control.ContainsKey(String.Format("row_{0}", choice.Value.ID)) Then
                                        _control(String.Format("row_{0}", choice.Value.ID)).Visible = False
                                    End If
                                End If
                            Next
                        End If
                    Case "radiobutton"
                        For Each choice In feature.Value.Children
                            choiceNode = featureNode.SelectSingleNode(String.Format("choice[@id='{0}']", choice.Value.ID))

                            If _control.ContainsKey("rdo_" & choice.Value.ID) Then
                                rdo = CType(_control("rdo_" & choice.Value.ID), RadioButton)
                                rdo.Checked = choice.Value.IsSelected

                                If _control.ContainsKey(String.Format("row_{0}", choice.Value.ID)) Then
                                    _control(String.Format("row_{0}", choice.Value.ID)).Visible = choice.Value.IsSelected
                                End If
                            End If
                        Next
                    Case "checkbox"
                        For Each choice In feature.Value.Children
                            choiceNode = featureNode.SelectSingleNode(String.Format("choice[@id='{0}']", choice.Value.ID))

                            If _control.ContainsKey("chk_" & choice.Value.ID) Then
                                chk = CType(_control("chk_" & choice.Value.ID), CheckBox)
                                chk.Checked = choice.Value.IsSelected

                                If _control.ContainsKey(String.Format("row_{0}", choice.Value.ID)) Then
                                    _control(String.Format("row_{0}", choice.Value.ID)).Visible = choice.Value.IsSelected
                                End If
                            End If
                        Next
                    Case "textbox"
                        CType(_control("txt_" & feature.Value.ID), TextBox).Text = feature.Value.Text
                    Case "hidden"
                        ' do nothing
                    Case Else
                        ' do nothing
                End Select
            End If
        Next
    End Sub

    Private Sub OnNotification(ByVal message As INotification)
        _flag = _flag - 1
    End Sub

    Private Function AddChildElement(ByVal parent As XmlElement, ByVal elemName As String, ByVal elemText As String) As XmlElement
        Dim elem As XmlElement

        elem = parent.OwnerDocument.CreateElement(elemName)
        elem.InnerText = elemText
        parent.AppendChild(elem)

        Return elem
    End Function

    Private Sub SetAttribute(ByVal elem As XmlElement, ByVal attrName As String, ByVal attrValue As String)
        Dim attr As XmlAttribute

        If elem.Attributes(attrName) Is Nothing Then
            attr = elem.OwnerDocument.CreateAttribute(attrName)
            attr.Value = attrValue
            elem.Attributes.Append(attr)
        Else
            elem.Attributes(attrName).Value = attrValue
        End If
    End Sub

    Private Function GetAttribute(ByVal elem As XmlElement, ByVal attrName As String) As String
        If elem.Attributes(attrName) Is Nothing Then
            Return String.Empty
        Else
            Return elem.Attributes(attrName).Value
        End If
    End Function

    Private Function GetParentID(ByVal childID As String) As String
        Return _document.SelectSingleNode(String.Format("//choice[@id='{0}']/../@id", childID)).Value
    End Function

    Private Sub SetViewIds()
        Try
            If Application(ApplicationKey.DigitalPackageID) Is Nothing Then
                Dim elem As XmlNode
                elem = _document.SelectSingleNode(String.Format("//feature[@name='{0}']", "Digital Channel Packages"))
                If Not elem Is Nothing Then
                    Application.Add(ApplicationKey.DigitalPackageID, elem.Attributes("id").Value)
                    DigitalPackageID = elem.Attributes("id").Value
                End If
                elem = _document.SelectSingleNode(String.Format("//choice[@name='{0}']", "Charter Total View"))
                If Not elem Is Nothing Then
                    Application.Add(ApplicationKey.CharterTotalViewID, elem.Attributes("id").Value)
                    TotalViewID = elem.Attributes("id").Value
                End If
            Else
                DigitalPackageID = Application(ApplicationKey.DigitalPackageID)
                TotalViewID = Application(ApplicationKey.CharterTotalViewID)
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub UpdateChooseOptionsHTMLPrice(ByVal choiceID As String, ByVal modifiedPrice As String)
        '########################################################################
        'MODIFICATION   ROD COPELAND    DIGITAL REPACKAGING     SEPT 18, 2008
        '########################################################################
        'AS PART OF THE DIGITAL REPACKAGING PROJECT THE REQUIREMENT TO ALLOW THE 
        'PRICE OF THE CHOICE TO CHANGE BASED ON HOW MANY OTHER CHOICES YOU'VE 
        'CHECKED, WE HAVE TO CHANGED THE PRICE DISPLAYED ON THE PAGE NEXT TO THE 
        'CHOICE AND CHANGE THE PRICE IN THE CART WHEN THE CHOICE IS SELECTED.  
        'THIS SUB PROCEDURE IS DEDICATED TO JUST CHANGING THE PRICE DISPLAYED 
        'NEXT TO THE CHOICE ON THE PAGE, CENTER COLUMN.  SO WE LOOP THROUGH THE 
        'CONTROLS ON THE PAGE UNTIL WE GET DOWN TO THE SPECIFIC TABLE CELL THAT 
        'CONTAINS THE PRICE FOR A SPECIFIC CHOICE, THEN APPLY DISCOUNTS TO THAT 
        'PRICE TO MATCH THE DISCOUNT PRICE IN THE CART THAT WOULD HAVE ALREADY 
        'BEEN APPLIED AT THIS POINT.
        '########################################################################
        Dim cableTVTable As HtmlTable
        Dim customizationsHTMLTable As HtmlTable
        Dim lCheckedCount As Integer = 0
        Dim choiceCollection As Dictionary(Of String, Boolean)

        For Each cableTVControl As Control In pnlCableTV.Controls
            If cableTVControl.GetType().Name.ToLower() = "htmltable" Then
                cableTVTable = cableTVControl
                For Each cableTVTableRow As HtmlTableRow In cableTVTable.Rows
                    For Each cableTVHtmlTable2 As Control In cableTVTableRow.Controls
                        For Each loadCategoryCell As Control In cableTVHtmlTable2.Controls
                            If loadCategoryCell.GetType().Name.ToLower() = "htmltable" Then
                                customizationsHTMLTable = loadCategoryCell
                                lCheckedCount = 0
                                choiceCollection = New Dictionary(Of String, Boolean)

                                '##############################################################
                                'LOOP TO FIND ROW THAT HAS THE CELL CHOICE CHECKBOXES IN QUESTION.
                                '##############################################################
                                For Each loadFeatureRow As HtmlTableRow In customizationsHTMLTable.Rows
                                    '##############################################
                                    'LOOP TO FIND CELL THAT HAS THE CHOICE CHECKBOX
                                    '##############################################
                                    For Each lcell As HtmlTableCell In loadFeatureRow.Cells
                                        '####################################################
                                        'LOOK FOR THE CLIENT ID. IT SHOULD HAVE THE CHOICE ID 
                                        'SIMULAR TO THE CHOICEID THAT WAS PASSED IN HERE.
                                        '####################################################
                                        If Not (lcell.ClientID Is Nothing) Then
                                            If lcell.ClientID.Length() > 27 Then
                                                If lcell.ClientID.Substring(27) = choiceID Then
                                                    If Not (lcell.ID Is Nothing) Then
                                                        If lcell.ID.Length() > 11 Then
                                                            If lcell.ID.Substring(11) = choiceID Then
                                                                '###########################################################
                                                                'MATCHING choiceID VALUES WOULD BE SIMULAR TO THE FOLLOWING:
                                                                '4995271, 4995272,4995273
                                                                '###########################################################
                                                                lcell.InnerHtml = modifiedPrice
                                                                Exit Sub
                                                            End If
                                                        End If
                                                    End If
                                                End If
                                            End If
                                        End If
                                        '####################################################
                                    Next
                                    '##############################################
                                Next
                                '##############################################################
                            End If
                        Next
                    Next
                Next
            End If
        Next

    End Sub

    Private Sub checkDiscountCustomizations(ByRef subItem As KeyValuePair(Of String, ISubCartItem))

        Dim featureAndChoiceNode As XmlNode
        Dim hasChoicesSelected As Boolean = False
        Dim choicesSelected As Integer = 0
        Dim subItem2 As KeyValuePair(Of String, ISubCartItem)

        If Not (subItem.Value Is Nothing) Then
            Select Case subItem.Key
                Case customizationToDiscount1
                    '##################################################################
                    'UPDATE THE CHOOSE OPTIONS XML TAKING AND APPLY ANY DISCOUNT PRICE. 
                    'PASS IN A CHOICE NODE AND THE PROCEDURE WILL UPDATE THE PRICE FOR 
                    'THE CHOICE AND ALL OF IT'S SIBLING CHOICES.
                    '##################################################################
                    featureAndChoiceNode = _document.SelectSingleNode("/chooseOptions/category/feature/choice[@id='4995271' or @id='4995272' or @id='4995273']")
                    If Not (featureAndChoiceNode Is Nothing) Then
                        Call updateChooseOptionsXMLChoicePrice(featureAndChoiceNode, customizationToDiscount1)
                    End If

                    featureAndChoiceNode = _document.SelectSingleNode("/chooseOptions/category/feature[@id='" & customizationToDiscount1 & "']")

                    '###################################################
                    'UPDATE THE HTML price THAT GETS DISPLAYED ON THE PAGE.
                    '###################################################
                    If Not (featureAndChoiceNode Is Nothing) Then
                        For Each choiceSiblingNode As XmlNode In featureAndChoiceNode.ChildNodes
                            If Not (choiceSiblingNode Is Nothing) Then
                                Call UpdateChooseOptionsHTMLPrice(choiceSiblingNode.Attributes("id").Value(), "$" & choiceSiblingNode.Attributes("price").Value())
                            End If
                        Next
                    End If

                Case customizationToDiscount3
                    '##################################################################
                    'UPDATE THE CHOOSE OPTIONS XML TAKING AND APPLY ANY DISCOUNT PRICE. 
                    'PASS IN A CHOICE NODE AND THE PROCEDURE WILL UPDATE THE PRICE FOR 
                    'THE CHOICE AND ALL OF IT'S SIBLING CHOICES.
                    '##################################################################
                    featureAndChoiceNode = _document.SelectSingleNode("/chooseOptions/category/feature/choice[@id='4995285' or @id='4995286' or @id='4995287']")
                    If Not (featureAndChoiceNode Is Nothing) Then
                        Call updateChooseOptionsXMLChoicePrice(featureAndChoiceNode, customizationToDiscount3)
                    End If

                    featureAndChoiceNode = _document.SelectSingleNode("/chooseOptions/category/feature[@id='" & customizationToDiscount3 & "']")

                    '###################################################
                    'UPDATE THE HTML price THAT GETS DISPLAYED ON THE PAGE.
                    '###################################################
                    If Not (featureAndChoiceNode Is Nothing) Then
                        For Each choiceSiblingNode As XmlNode In featureAndChoiceNode.ChildNodes
                            If Not (choiceSiblingNode Is Nothing) Then
                                Call UpdateChooseOptionsHTMLPrice(choiceSiblingNode.Attributes("id").Value(), "$" & choiceSiblingNode.Attributes("price").Value())
                            End If
                        Next
                    End If

                    '##############################################################
                    'DETERMINE IF ANY ARE SELECTED, IF SO THEN SHOW THE PRICES 
                    'FOR ALL THE OTHERS THAT ARE NOT SELECTED AND HIDE THE PRICE 
                    'FOR THE CHOICE THAT IS SELECTED.
                    '##############################################################
                    For Each subItem2 In subItem.Value.Children
                        Dim choiceItem As ISubCartItem = subItem2.Value
                        If Not (choiceItem Is Nothing) Then
                            If choiceItem.IsSelected = True Then
                                hasChoicesSelected = True
                                Exit For
                            End If
                        End If
                    Next

                    '##########################################################################
                    'WHEN NO ITEMS ARE CHECKED, DONT SHOW PRICES ON ANY AS THIS CUSTOMIZATION 
                    'HAS BEEN 1 FREE ITEM, CANT LIST $5 FOR ALL AS THERE ARE IN THE CATALOG 
                    'SINCE WE DONT KNOW WHICH ONE THEY WILL SELECT FIRST TO SHOW AS FREE. 
                    'TO RESOLVE, SHOW NO PRICES INITIALLY, ONCE ONE IS SELECTED, SHOW 
                    'OTHERS AS THEIR LIST PRICES.
                    '##########################################################################
                    If hasChoicesSelected Then
                        For Each subItem2 In subItem.Value.Children
                            Dim choiceItem As ISubCartItem = subItem2.Value
                            If Not (choiceItem Is Nothing) Then
                                '#################################################################
                                'FIND THE CHOICE THAT IS NOT SUPPOSED TO DISPLAY THE PRICE AND 
                                'REMOVE THE PRICE FROM THE HTML FOR JUST THIS CHOICE ONLY
                                '#################################################################
                                If choiceItem.FeatureType = FeatureType.IsPlaceholder Then
                                    If choiceItem.IsSelected = True Then
                                        UpdateChooseOptionsHTMLPrice(choiceItem.ID, "")
                                        '    Else
                                        '        UpdateChooseOptionsHTMLPrice(choiceItem.ID, "$" & choiceItem.Price)
                                    End If
                                    'Else
                                    '    UpdateChooseOptionsHTMLPrice(choiceItem.ID, "$" & choiceItem.Price)
                                End If
                            End If
                        Next
                    Else
                        For Each subItem2 In subItem.Value.Children
                            Dim choiceItem As ISubCartItem = subItem2.Value
                            If Not (choiceItem Is Nothing) Then
                                '#################################################################
                                'FIND THE CHOICE THAT IS NOT SUPPOSED TO DISPLAY THE PRICE AND 
                                'REMOVE THE PRICE FROM THE HTML FOR JUST THIS CHOICE ONLY
                                '#################################################################
                                UpdateChooseOptionsHTMLPrice(choiceItem.ID, "")
                            End If
                        Next
                    End If

                Case customizationToDiscount4
                    '##############################################################
                    'DETERMINE IF ANY ARE SELECTED, IF SO THEN SHOW THE PRICES 
                    'FOR ALL THE OTHERS THAT ARE NOT SELECTED AND HIDE THE PRICE 
                    'FOR THE CHOICE THAT IS SELECTED.
                    '##############################################################
                    For Each subItem2 In subItem.Value.Children
                        Dim choiceItem As ISubCartItem = subItem2.Value
                        If Not (choiceItem Is Nothing) Then
                            If choiceItem.IsSelected = True Then
                                choicesSelected += 1
                            End If
                        End If
                    Next

                    '##########################################################################
                    'WHEN NO ITEMS ARE CHECKED, DONT SHOW PRICES ON ANY AS THIS CUSTOMIZATION 
                    'HAS BEEN 2 FREE ITEMS, CANT LIST $10 FOR ALL AS THERE ARE IN THE CATALOG 
                    'SINCE WE DONT KNOW WHICH ONE THEY WILL SELECT FIRST TO SHOW AS FREE. 
                    'TO RESOLVE, SHOW NO PRICES INITIALLY, ONCE TWO ARE SELECTED, SHOW 
                    'THIRD WITH ITS LIST PRICE.
                    '##########################################################################
                    If choicesSelected > 1 Then
                        For Each subItem2 In subItem.Value.Children
                            Dim choiceItem As ISubCartItem = subItem2.Value
                            If Not (choiceItem Is Nothing) Then
                                '#################################################################
                                'FIND THE CHOICE THAT IS NOT SUPPOSED TO DISPLAY THE PRICE AND 
                                'REMOVE THE PRICE FROM THE HTML FOR JUST THIS CHOICE ONLY
                                '#################################################################
                                If choiceItem.FeatureType = FeatureType.IsPlaceholder Then
                                    If choiceItem.IsSelected = True Then
                                        UpdateChooseOptionsHTMLPrice(choiceItem.ID, "")
                                    Else
                                        UpdateChooseOptionsHTMLPrice(choiceItem.ID, "$" & choiceItem.Price)
                                    End If
                                Else
                                    UpdateChooseOptionsHTMLPrice(choiceItem.ID, "$" & choiceItem.Price)
                                End If
                            End If
                        Next
                    Else
                        For Each subItem2 In subItem.Value.Children
                            Dim choiceItem As ISubCartItem = subItem2.Value
                            If Not (choiceItem Is Nothing) Then
                                '#################################################################
                                'FIND THE CHOICE THAT IS NOT SUPPOSED TO DISPLAY THE PRICE AND 
                                'REMOVE THE PRICE FROM THE HTML FOR JUST THIS CHOICE ONLY
                                '#################################################################
                                UpdateChooseOptionsHTMLPrice(choiceItem.ID, "")
                            End If
                        Next
                    End If

                Case Else
                    ' Jonathan Parks 9/23/08
                    ' code here to check for one free video tier customizations web config setting...
                    If ExternalIDs.OneFreeVideoTierCustomization(subItem.Key) Then
                        '##############################################################
                        'DETERMINE IF ANY ARE SELECTED, IF SO THEN SHOW THE PRICES 
                        'FOR ALL THE OTHERS THAT ARE NOT SELECTED AND HIDE THE PRICE 
                        'FOR THE CHOICE THAT IS SELECTED.
                        '##############################################################
                        For Each subItem2 In subItem.Value.Children
                            Dim choiceItem As ISubCartItem = subItem2.Value
                            If Not (choiceItem Is Nothing) Then
                                If choiceItem.IsSelected = True Then
                                    hasChoicesSelected = True
                                    Exit For
                                End If
                            End If
                        Next

                        '##########################################################################
                        'WHEN NO ITEMS ARE CHECKED, DONT SHOW PRICES ON ANY AS THIS CUSTOMIZATION 
                        'HAS BEEN 1 FREE ITEM, CANT LIST $5 FOR ALL AS THERE ARE IN THE CATALOG 
                        'SINCE WE DONT KNOW WHICH ONE THEY WILL SELECT FIRST TO SHOW AS FREE. 
                        'TO RESOLVE, SHOW NO PRICES INITIALLY, ONCE ONE IS SELECTED, SHOW 
                        'OTHERS AS THEIR LIST PRICES.
                        '##########################################################################
                        If hasChoicesSelected Then
                            For Each subItem2 In subItem.Value.Children
                                Dim choiceItem As ISubCartItem = subItem2.Value
                                If Not (choiceItem Is Nothing) Then
                                    '#################################################################
                                    'FIND THE CHOICE THAT IS NOT SUPPOSED TO DISPLAY THE PRICE AND 
                                    'REMOVE THE PRICE FROM THE HTML FOR JUST THIS CHOICE ONLY
                                    '#################################################################
                                    If choiceItem.FeatureType = FeatureType.IsPlaceholder Then
                                        If choiceItem.IsSelected = True Then
                                            UpdateChooseOptionsHTMLPrice(choiceItem.ID, "")
                                        Else
                                            UpdateChooseOptionsHTMLPrice(choiceItem.ID, "$" & choiceItem.Price)
                                        End If
                                    Else
                                        UpdateChooseOptionsHTMLPrice(choiceItem.ID, "$" & choiceItem.Price)
                                    End If
                                End If
                            Next
                        Else
                            For Each subItem2 In subItem.Value.Children
                                Dim choiceItem As ISubCartItem = subItem2.Value
                                If Not (choiceItem Is Nothing) Then
                                    '#################################################################
                                    'FIND THE CHOICE THAT IS NOT SUPPOSED TO DISPLAY THE PRICE AND 
                                    'REMOVE THE PRICE FROM THE HTML FOR JUST THIS CHOICE ONLY
                                    '#################################################################
                                    UpdateChooseOptionsHTMLPrice(choiceItem.ID, "")
                                End If
                            Next
                        End If
                    End If

            End Select
        End If

    End Sub


    Private Sub updateChooseOptionsXMLChoicePrice(ByRef elem As XmlNode, ByVal customizationID As String)
        '########################################################################
        'MODIFICATION   ROD COPELAND    DIGITAL REPACKAGING     SEPT 18, 2008
        '########################################################################
        'UPDATE THE DOCUMENT XML USED TO POPULATE THE CHOOSE OPTIONS PAGE
        '########################################################################
        Dim choiceNode As XmlNode
        Dim choiceSiblingNode As XmlNode
        Dim choiceLoopNode As XmlNode
        Dim intDiscountSelectedItemCount As Integer = 0
        Dim discountFactor As Integer = 2
        Dim intSelectedLoopCnt As Integer = 1
        Dim intNewPrice As Integer = 0
        Dim updateNonSelectedChoice As Boolean = False

        If elem Is Nothing Then
            Exit Sub
        End If


        choiceNode = elem.SelectSingleNode(".")


        '####################################################################
        'SINCE WERE NOW APPLYING A DISCOUNT PRICE TO THE PRICE, WE NEED TO DO 
        'SOMETHING TO MAINTAIN THE ORIGINAL PRICE WHEN WE HAVE TO RECALC THE 
        'PRICE AS THEY SELECT AND DESELECT ITEMS.  WE NEED A COUNT OF HOW 
        'MANY SELECT ITEMS THERE ARE ALSO, THIS VALUE IS USED TO DETERMINE 
        'THE DISCOUNT AMOUNT IN THE BLOCK BELOW.
        '####################################################################
        For Each choiceSiblingNode In choiceNode.ParentNode()
            If Not (choiceSiblingNode.Attributes("price") Is Nothing) Then
                '##################################################################
                'SET A BASELINE PRICE IN THE XML TO BE USED TO DETERMINE THE 
                'DISCOUNT PRICE.  THE DISCOUNT PRICE WILL CHANGE BASED ON WHATS 
                'SELECTED ON THE PAGE.
                '##################################################################
                If (choiceSiblingNode.Attributes("originalPrice") Is Nothing) Then
                    SetAttribute(choiceSiblingNode, "originalPrice", choiceSiblingNode.Attributes("price").Value())
                End If

                '###############################################################
                'before we add the value we need to do a count of how many are 
                'selected to know how much to discount the one we are adding.
                '###############################################################
                If Not (choiceSiblingNode.Attributes("selected") Is Nothing) Then
                    If choiceSiblingNode.Attributes("selected").Value() = "true" Then
                        intDiscountSelectedItemCount = intDiscountSelectedItemCount + 1
                    End If
                End If
            End If
        Next
        '####################################################################



        '#############################################################
        'APPLY DISCOUNT PRICES TO NON SELECTED AND SELECTED ITEMS 
        'WHERE APPROPRIATE.  DISCOUNTS APPLIED ARE ALSO BASED UPON 
        'WHAT CUSTOMIZATION IS BEING APPLIED.
        '#############################################################
        Select Case customizationID
            Case customizationToDiscount1
                '########################################################
                'LOOP THROUGH ALL THE CHOICES AND APPLY DISCOUNTS TO 
                'EACH BASED ON THE DISCOUNT AMOUNT * THE TOTAL SELECTED.
                '########################################################
                For Each choiceLoopNode In choiceNode.ParentNode()
                    intNewPrice = 0
                    updateNonSelectedChoice = False

                    If Not (choiceLoopNode.Attributes("selected") Is Nothing) Then
                        If choiceLoopNode.Attributes("selected").Value() = "true" Then
                            '################################################################################
                            'THIS WILL BE ITEMS THAT HAVE BEEN SELECTED AND WE NEED TO FIND THE PRICE AS 
                            'EXPECTED IN ADDITION TO MAINTAINING THE DISCOUNTED PRICE FOR SUBSEQUENT ITEMS 
                            'THAT HAVE BEEN SELECTED AS WELL.
                            '################################################################################
                            Select Case intSelectedLoopCnt
                                Case 2
                                    If CType(choiceLoopNode.Attributes("price").Value(), Integer) < CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) Then
                                        intNewPrice = CType(choiceLoopNode.Attributes("price").Value(), Integer) - 2
                                    Else
                                        intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) - 2
                                    End If
                                Case 3
                                    If CType(choiceLoopNode.Attributes("price").Value(), Integer) < CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) Then
                                        intNewPrice = CType(choiceLoopNode.Attributes("price").Value(), Integer) - 4
                                    Else
                                        intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) - 4
                                    End If
                                Case Else
                                    intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer)
                            End Select

                            intSelectedLoopCnt = intSelectedLoopCnt + 1
                        Else
                            '##########################################################
                            'THIS SHOULD BE THE ITEMS THAT HAVE NOT BEEN SELECTED YET.
                            '##########################################################
                            updateNonSelectedChoice = True
                        End If
                    Else
                        '##########################################################
                        'THIS SHOULD BE THE ITEMS THAT HAVE NOT BEEN SELECTED YET.
                        '##########################################################
                        updateNonSelectedChoice = True
                    End If

                    If updateNonSelectedChoice Then
                        '##########################################################
                        'THIS SHOULD BE THE ITEMS THAT HAVE NOT BEEN SELECTED YET.
                        '##########################################################
                        intNewPrice = 0
                        Select Case intDiscountSelectedItemCount
                            Case 1
                                intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) - 2
                            Case 2
                                intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) - 4
                            Case Else
                                intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer)
                        End Select
                    End If

                    SetAttribute(choiceLoopNode, "price", intNewPrice)

                Next
                '#############################################################

            Case customizationToDiscount2
                '#################################################
                'PLACE HOLDER IN THE EVENT MODIFICATION TO CHOOSE 
                'OPTIONS XML IS NEEDED FOR THIS CUSTOMIZATION.
                '#################################################

            Case customizationToDiscount3
                '########################################################
                'LOOP THROUGH ALL THE CHOICES AND APPLY DISCOUNTS TO 
                'EACH BASED ON THE DISCOUNT AMOUNT * THE TOTAL SELECTED.
                '########################################################
                For Each choiceLoopNode In choiceNode.ParentNode()
                    intNewPrice = 0
                    updateNonSelectedChoice = False

                    If Not (choiceLoopNode.Attributes("selected") Is Nothing) Then
                        If choiceLoopNode.Attributes("selected").Value() = "true" Then
                            '################################################################################
                            'THIS WILL BE ITEMS THAT HAVE BEEN SELECTED AND WE NEED TO FIND THE PRICE AS 
                            'EXPECTED IN ADDITION TO MAINTAINING THE DISCOUNTED PRICE FOR SUBSEQUENT ITEMS 
                            'THAT HAVE BEEN SELECTED AS WELL.
                            '################################################################################
                            Select Case intSelectedLoopCnt
                                Case 3
                                    If CType(choiceLoopNode.Attributes("price").Value(), Integer) < CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) Then
                                        intNewPrice = CType(choiceLoopNode.Attributes("price").Value(), Integer) - 2
                                    Else
                                        intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) - 2
                                    End If
                                Case Else
                                    intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer)
                            End Select

                            intSelectedLoopCnt = intSelectedLoopCnt + 1
                        Else
                            '##########################################################
                            'THIS SHOULD BE THE ITEMS THAT HAVE NOT BEEN SELECTED YET.
                            '##########################################################
                            updateNonSelectedChoice = True
                        End If
                    Else
                        '##########################################################
                        'THIS SHOULD BE THE ITEMS THAT HAVE NOT BEEN SELECTED YET.
                        '##########################################################
                        updateNonSelectedChoice = True
                    End If

                    If updateNonSelectedChoice Then
                        '##########################################################
                        'THIS SHOULD BE THE ITEMS THAT HAVE NOT BEEN SELECTED YET.
                        '##########################################################
                        intNewPrice = 0
                        Select Case intDiscountSelectedItemCount
                            Case 2
                                intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer) - 2
                            Case Else
                                intNewPrice = CType(choiceLoopNode.Attributes("originalPrice").Value(), Integer)
                        End Select
                    End If

                    SetAttribute(choiceLoopNode, "price", intNewPrice)

                Next

            Case customizationToDiscount4
                '#################################################
                'PLACE HOLDER IN THE EVENT MODIFICATION TO CHOOSE 
                'OPTIONS XML IS NEEDED FOR THIS CUSTOMIZATION.
                '#################################################

        End Select


    End Sub

End Class

