Imports System.Collections.Generic
Imports System.Text
Imports CharterDotCom.CommonEntities.Library
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 System.Net

Public Delegate Sub ConfirmationNumberGeneratedHandler(ByVal confirmationNumber As String)

Partial Class Controls_FinishOrder
    Inherits System.Web.UI.UserControl

    Private _hbxOrderID As String = ""
    Private _email As String = ""
    Private _phone As String = ""
    Private _name As String = ""
    Private _lname As String = ""
    Private _noschedule As Boolean = True
    Private _chatcontent As String = ""

    Private _HBXInfo_pr As String = ""
    Private _HBXInfo_ca As String = ""
    Private _HBXInfo_pc As String = ""
    Private _HBXInfo_qn As String = ""
    Private _HBXInfo_st As String = ""
    Private _HBXInfo_sp As Decimal = 0
    Private _HBXInfo_sr As Integer = 1
    Private _HBXInfo_oi As String = ""
    Private _HBXInfo_sk As String = ""
    Private _HBXInfo_po As String = ""
    Private _HBXInfo_ds As Decimal = 0
    Private _HBXInfo_ci As String
    Private _HBXInfo_sy As String = ""
    Private _HBXInfo_sa As String = ""
    Private _HBXInfo_sz As String = ""
    Private _HBXInfo_so As String = "US"
    Private _HBXInfo_Attr1 As String = ""

    Private CategoriesInCart As List(Of Category)
    Private _confirmationNum As String = ""
    Public Event onconfirmationNumber As ConfirmationNumberGeneratedHandler


    Public Property OrderComplete() As Boolean
        Get
            If ViewState(Me.ID & "_OrderComplete") Is Nothing Then
                Return False
            Else
                Return CType(ViewState(Me.ID & "_OrderComplete"), Boolean)
            End If
        End Get

        Set(ByVal value As Boolean)
            ViewState(Me.ID & "_OrderComplete") = value
        End Set
    End Property

    Public Property ChatContent() As String
        Get
            Return _chatcontent
        End Get
        Set(ByVal value As String)
            _chatcontent = value
        End Set
    End Property
    Dim _account As IAccount                            'added
    Public Property Account() As IAccount   'added
        Get
            Return _account
        End Get
        Set(ByVal value As IAccount)
            _account = value
        End Set
    End Property

    Public ReadOnly Property ConfirmationNumber()
        Get
            Return Me._confirmationNum
        End Get
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim vendorType As BillingVendorType
        Dim currYear As Integer
        Dim i As Integer
        ChatContent = "A Customer Care Representative will Chat with you in just a moment.  If a chat window is not presented automatically, please click on the Chat Live Now! button."
        Dim canChat As String = HttpContext.Current.Application(ApplicationKey.EnableChat)


        If Not Page.IsPostBack Then
            'ltrContent.Text = String.Format("ControlID:{0};OwnerID:{1};OwnerTypeID:{2}", "RegisterNow", 1, OwnerType.Other)	'ContentManager.Instance.GetContent("RegisterNow", 1, OwnerType.Other)
            ltrContent.Text = ContentManager.Instance.GetContent("RegisterNow", 1, OwnerType.Other)


            '##########################
            'HIDE EVERYTHING INITIALLY
            '##########################
            pnlFirstMonthPayment.Visible = False
            pnlRegisterNow.Visible = False
            pnlAlmostFinished.Visible = False
            pnlThankYou.Visible = False
            pnlELOA_Host.Visible = False
            pnlELOA_Port.Visible = False

            If OrderComplete Then
                lblAmountDueBA.Text = String.Format("{0:C}", CatalogManager.Instance.GetCatalog().Cart.GrandTotal)
                lblAmountDueCC.Text = String.Format("{0:C}", CatalogManager.Instance.GetCatalog().Cart.GrandTotal)

                vendorType = _account.BillingVendorType                                                              'added
                'vendorType = AccountManager.Instance.GetAccount().BillingVendorType  'commntd

                If vendorType = BillingVendorType.CSG Then
                    ddlCardIssuer.Items.Add(New ListItem("American Exptess", 1))
                    ddlCardIssuer.Items.Add(New ListItem("Discover", 2))
                    ddlCardIssuer.Items.Add(New ListItem("MasterCard", 3))
                    ddlCardIssuer.Items.Add(New ListItem("Visa", 4))
                ElseIf vendorType = BillingVendorType.ICOM Then
                    ddlCardIssuer.Items.Add(New ListItem("Debit", 5))
                    ddlCardIssuer.Items.Add(New ListItem("Discover", 2))
                    ddlCardIssuer.Items.Add(New ListItem("MasterCard", 3))
                    ddlCardIssuer.Items.Add(New ListItem("Visa", 4))
                End If

                currYear = DateTime.Now.Year

                For i = 0 To 11
                    ddlExpirationYear.Items.Add(New ListItem(currYear + i, currYear + i))
                Next


                btnGetReceipt_Click(Nothing, Nothing)
                CategoriesInCart = New List(Of Category)
                HBXInformation()

                ''##########################################################
                ''IF THEY HAVE A TELEPHONY ORDER THEN SHOW THE ELOA DETAILS.
                ''THE VALUE IN Session("SelectedTelephony") ORIGINATE IN THE 
                ''CHOOSEOPTIONS.ASPX.VB PAGE CURRENTLY.
                ''##########################################################
                'If Not (Session("SelectedTelephony") Is Nothing) Then
                '    If CType(Session("SelectedTelephony"), Boolean) = True Then
                '        Call ShowTelephonyDisclaimer()
                '    End If
                'Else
                ''################################################
                ''THIS FLOW WILL BE ORDERS THAT DO NOT HAVE TELEPHONY 
                ''PRODUCTS IN THEIR SHOPPING CART
                ''################################################
                pnlThankYou.Visible = True

                ltrThankYouGift.Text = HttpContext.Current.Application(ApplicationKey.ThankYouGift)
                ltrThankYouDisclaimer.Text = HttpContext.Current.Application(ApplicationKey.ThankYouDisclaimer)

                ' 9/2007 jwg - Add for G2B 4.1
                If (_account IsNot Nothing) Then
                    ' use the account.Eligibility to populate new fields
                    If (_account.Eligibility IsNot Nothing) Then
                        If (_account.Eligibility.AccountNumber IsNot Nothing) Then
                            Me.ltrElig.Text &= "<B>Account Number:</B> " & _account.Eligibility.AccountNumber & "<BR/>"
                        End If
                        If (_account.Eligibility.DepositAmountFieldSpecified) Then
                            Me.ltrElig.Text &= "<B>Deposit Amount: </B>" & _account.Eligibility.DepositAmountField.ToString("C") & "<BR/>"
                        End If
                    End If
                End If

                If _noschedule Then
                    pnlAlmostFinished.Visible = True
                    If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                        '#################################################################
                        'ROD COPELAND 7/13/2007  M O D I F I C A T I O N  FOR STEPH BOONE
                        'DETERMINE IF THIS IS A DROP SHIP CONDITION
                        '#################################################################
                        If Not (_account Is Nothing) Then
                            Select Case _account.last_WS_ResponseCode
                                Case 0 'SUCCESS 
                                    ChatComplete()
                                Case 280 'SUCCESS AS A DROP SHIP MODEM
                                    '######################################################################
                                    'ROD COPELAND 7/13/2007  M O D I F I C A T I O N
                                    'NO NEED FOR A CHAT SESSION PER STEPHANIE BOONE AS PART OF DROP SHIP
                                    '######################################################################

                                Case Else 'A PROBLEM
                                    ChatComplete()
                            End Select
                        End If
                    End If
                Else
                    pnlAlmostFinished.Visible = False
                End If
                'End If
            Else
                ''##########################################################
                ''IF THEY HAVE A TELEPHONY ORDER THEN SHOW THE ELOA DETAILS.
                ''THE VALUE Session("SelectedTelephony") ORIGINATE IN THE 
                ''CHOOSEOPTIONS.ASPX.VB PAGE CURRENTLY.
                ''##########################################################
                'If Not (Session("SelectedTelephony") Is Nothing) Then
                '    If CType(Session("SelectedTelephony"), Boolean) = True Then
                '        Call ShowTelephonyDisclaimer()
                '    End If
                'Else
                '################################################
                'THIS FLOW WILL BE ORDERS THAT DO NOT HAVE TELEPHONY 
                'PRODUCTS IN THEIR SHOPPING CART
                '################################################
                '#########################################################
                'THIS WILL BE NON TELEPHONY ORDERS THAT ARE NOT COMPLETE.
                'OR HAVE NOT STARTED IF A PERSON FINDS A WAY TO DROP INTO 
                'THIS PAGE DIRECTLY SOME HOW.
                '#########################################################
                pnlThankYou.Visible = False
                pnlAlmostFinished.Visible = True
                If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                    ChatInComplete()
                End If
                'End If

            End If
        End If

        '#########################################################
        'MODIFICATION   ROD COPELAND    OCT 6, 2009 ISSUE ID 5382
        '#########################################################
        CatalogManager.Instance.ClearCatalog()

    End Sub
    Private Sub ShowTelephonyDisclaimer()
        pnlELOA_Host.Visible = True
        txtDate.Text = Now.Date()

        If Not (Session("Exist_Phone_Number_To_Port_Over-Telephony_Order") Is Nothing) Then
            pnlELOA_Port.Visible = True

            '#########################################################
            'POPULATE THE TELEPHONE NUMBER LABEL TO SHOW ON THE PAGE, 
            'THIS SHOULD BE THE NUMBER BEING PORTED.
            '#########################################################
            If Not (_account Is Nothing) Then
                If Not (_account.Person Is Nothing) Then
                    If Not (_account.Person.FirstName Is Nothing) Then
                        If Not (_account.Address Is Nothing) Then
                            ltrName.Text = "<b>" & _account.Person.FirstName & " " & _account.Person.LastName & "</b><br/><b>" & _account.Address.Street1 & " </b><br/> <b>" & _account.Address.City & ", " & _account.Address.State & " " & _account.Address.Zip & "</b><br/><br/><b>Telephone Number:</b> " & Session("Exist_Phone_Number_To_Port_Over-Telephony_Order") & "<br/><br/>"
                        End If
                    End If
                End If
            End If
        End If

        '##############################################################################
        'DISPLAY THE CORRECT HEADER, CUSTOMER WANTS TO PORT THEIR NUMBER OVER TO THE 
        'NEW PLAN OR THIS IS A COMPLETLY NEW CUSTOMER AND THAT CUSTOMER WANTS A NEW 
        'NUMBER, DISPLAY THE CORRECT HEADING BASED ON THE REQUEST THE CUSTOMER IS 
        'MAKING.
        '##############################################################################
        Select Case pnlELOA_Port.Visible
            Case True
                pnlELOA_Port_Title.Visible = True
                pnlELOA_Host_Title.Visible = False
            Case False
                pnlELOA_Port_Title.Visible = False
                pnlELOA_Host_Title.Visible = True
            Case Else
                pnlELOA_Port_Title.Visible = True
                pnlELOA_Host_Title.Visible = False
        End Select
    End Sub

    Protected Sub rblFirstMonthPayment_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblFirstMonthPayment.SelectedIndexChanged
        Select Case rblFirstMonthPayment.SelectedIndex
            Case 0
                pnlBankAccountInfo.Visible = False
                pnlCreditCardInfo.Visible = False
                btnGetReceipt.Text = "Continue & Get Receipt"
            Case 1
                pnlBankAccountInfo.Visible = True
                pnlCreditCardInfo.Visible = False
                btnGetReceipt.Text = "Submit Payment & Get Receipt"
            Case 2
                pnlBankAccountInfo.Visible = False
                pnlCreditCardInfo.Visible = True
                btnGetReceipt.Text = "Submit Payment & Get Receipt"
        End Select
    End Sub

    Protected Sub btnGetReceipt_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetReceipt.Click
        Dim _accountType As BankAccountType
        Dim _cardType As CreditCardType
        'Dim _account As IAccount							'commntd
        Dim _person As IAccount.IMember = Nothing
        Dim _emails As List(Of IAccount.IMember.IEmail)
        Dim _email As IAccount.IMember.IEmail
        Dim _confirmations As Dictionary(Of String, IConfirmation) = Nothing
        Dim _confirmation As KeyValuePair(Of String, IConfirmation) = Nothing
        Dim _appointments As Dictionary(Of ScheduleType, IOrder.IAppointment) = Nothing
        Dim _appointment As KeyValuePair(Of ScheduleType, IOrder.IAppointment) = Nothing
        Dim result As IConfirmation = Nothing
        Dim sb As StringBuilder
        Dim dm As DateTime

        'If Page.IsValid Then
        'Select Case rblFirstMonthPayment.SelectedIndex
        '	Case 0
        '		' do nothing
        '	Case 1
        '		Select Case ddlAccountType.SelectedIndex
        '			Case 1
        '				_accountType = BankAccountType.Checking
        '			Case 2
        '				_accountType = BankAccountType.Savings
        '		End Select

        '		result = AccountManager.Instance.PayByBankAccount(CType(lblAmountDueBA.Text, Decimal), txtInstitution.Text, txtRoutingNumber.Text, txtAccountNumber.Text, _accountType)
        '	Case 2
        '		Select Case ddlCardIssuer.SelectedIndex
        '			Case 1
        '				' TODO: _cardType = CreditCardType
        '			Case 2
        '				_cardType = CreditCardType.Discover
        '			Case 3
        '				_cardType = CreditCardType.Master
        '			Case 4
        '				_cardType = CreditCardType.Visa
        '			Case 5
        '				_cardType = CreditCardType.Debit
        '		End Select

        '		result = AccountManager.Instance.PayByCreditCard(CType(lblAmountDueCC.Text, Decimal), txtNameOnCard.Text, _cardType, txtCardNumber.Text, New DateTime(CType(ddlExpirationYear.SelectedValue, Integer), CType(ddlExpirationMonth.SelectedValue, Integer), 1))
        'End Select

        'If (rblFirstMonthPayment.SelectedIndex = 0) Or result IsNot Nothing Then
        ' render email address

        ' _account = AccountManager.Instance.GetAccount()    'commntd
        _person = _account.Person
        If _account IsNot Nothing Then
            _phone = _account.Phone
        End If

        If _person IsNot Nothing Then
            _name = _person.FirstName ' & " " & _person.LastName
            _lname = _person.LastName
            If Not _person.Email Is Nothing Then
                _emails = _person.Email

                For Each _email In _emails
                    If _email.IsPrimary Then
                        lblEmailAddress.Text = "A confirmation e-mail has been sent to  " & _email.MailID

                        Exit For
                    End If
                Next
            End If
        End If

        ' render confirmations

        OrderManager.Instance.GetConfirmationInfo(_confirmations)

        If _confirmations IsNot Nothing Then
            sb = New StringBuilder()
            For Each _confirmation In _confirmations
                sb.AppendFormat("<li>{0}: <span style='font-weight:bold'>{1}</span></li>", _confirmation.Key, _confirmation.Value.Number)
                _hbxOrderID = _hbxOrderID & _confirmation.Value.Number & ","
                Me._confirmationNum = String.Format("{0}", _confirmation.Value.Number)
                RaiseEvent onconfirmationNumber(Me._confirmationNum)
            Next

            If _confirmations.Count > 1 Then
                sb.Insert(0, "Confirmation Numbers:<br /><ul>")
                sb.Append("</ul>")
            Else
                sb.Insert(0, "Confirmation Number:<br /><ul>")
                sb.Append("</ul>")
            End If


            ltlFinishOrderAlmostFinished.Text = ContentManager.Instance.GetContent("FinishOrder:AlmostFinished", 1, OwnerType.Other)
            ltlFinishOrderAlmostFinished.Text = ltlFinishOrderAlmostFinished.Text.Replace("{{ltlChatNow}}", "<input type=""image"" name=""ctl00$cphCenter$ucFinishOrder$btnChatNow"" id=""ctl00_cphCenter_ucFinishOrder_btnChatNow"" src=""../images/RED_confirmation/chat.jpg"" onclick=""javascript:window.open('../Visitors/chatlive.aspx?Chattype=SALES&orderID=" & Me._confirmationNum & "&user=" & _name & "&lname=" & _lname & "&phone=" & _phone & "&mail=" & Replace(lblEmailAddress.Text, "A confirmation e-mail has been sent to ", "") & "','chat','width=550,height=660,left=50,top=15');"" />")

            'btnChatNow.Attributes.Add("onClick", "javascript:window.open('../Visitors/chatlive.aspx?Chattype=SALES&orderID=" & Me._confirmationNum & "&user=" & _name & "&lname=" & _lname & "&phone=" & _phone & "&mail=" & Replace(lblEmailAddress.Text, "A confirmation e-mail has been sent to ", "") & "','chat','width=550,height=660,left=50,top=15');")

            ltrConfirmations.Text = sb.ToString()

            ' send an email message

            OrderManager.Instance.SendOrderConfirmationEmail()
        End If

        ' render appointements

        OrderManager.Instance.GetAppointments(_appointments)

        If _appointments IsNot Nothing Then
            sb = New StringBuilder()

            For Each _appointment In _appointments
                _noschedule = False
                Select Case _appointment.Key
                    Case ScheduleType.All
                        sb.Append("<li>Bundle: ")
                    Case ScheduleType.Cable
                        sb.Append("<li>Cable TV: ")
                    Case ScheduleType.CableAndHSD
                        sb.Append("<li>Cable TV and High-Speed Internet:")
                    Case ScheduleType.CableAndTelephone
                        sb.Append("<li>Cable TV and Telephone: ")
                    Case ScheduleType.HSD
                        sb.Append("<li>High-Speed Internet: ")
                    Case ScheduleType.HSDAndTelephone
                        sb.Append("<li>High-Speed Internet and Telephone: ")
                    Case ScheduleType.Telephone
                        sb.Append("<li>Telephone: ")
                End Select

                dm = CType(_appointment.Value.InstallDate, DateTime)

                Dim startTime As String
                Dim endTime As String
                startTime = _appointment.Value.StartTime
                endTime = _appointment.Value.EndTime
                Try
                    startTime = Convert.ToDateTime("1/1/2006 " & startTime).ToShortTimeString
                    endTime = Convert.ToDateTime("1/1/2006 " & endTime).ToShortTimeString
                Catch ex As Exception

                End Try
                sb.AppendFormat("<span style='font-weight:bold'>{0} between {1} and {2}</span></li>", dm.ToShortDateString(), startTime, endTime)
            Next

            If _appointments.Count > 1 Then
                sb.Insert(0, "Installation Appointments:<br /><ul>")
                sb.Append("</ul>")
            ElseIf _appointments.Count = 1 Then
                sb.Insert(0, "Installation Appointment:<br /><ul>")
                sb.Append("</ul>")
            End If

            ltrAppointments.Text = sb.ToString()
        End If

        '	pnlFirstMonthPayment.Visible = False
        '	pnlThankYou.Visible = True
        '	pnlRegisterNow.Visible = True
        'Else
        '	pnlFirstMonthPayment.Visible = False
        '	pnlAlmostFinished.Visible = True
        'End If
        'End If
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        Page.ClientScript.RegisterStartupScript(Me.GetType, "HBXORDERSCRIPT", GenerateHBXPageScript())
    End Sub

    Private Function GenerateHBXPageScript() As String
        Try
            Dim strTemp As New StringBuilder()
            If Len(_hbxOrderID) > 0 Then
                _hbxOrderID = Left(_hbxOrderID, Len(_hbxOrderID) - 1)
            End If
            If Len(_HBXInfo_pr) > 0 Then
                _HBXInfo_pr = Left(_HBXInfo_pr, Len(_HBXInfo_pr) - 1)
            End If
            If Len(_HBXInfo_ca) > 0 Then
                _HBXInfo_ca = Left(_HBXInfo_ca, Len(_HBXInfo_ca) - 1)
            End If
            If Len(_HBXInfo_pc) > 0 Then
                _HBXInfo_pc = Left(_HBXInfo_pc, Len(_HBXInfo_pc) - 1)
            End If
            If Len(_HBXInfo_qn) > 0 Then
                _HBXInfo_qn = Left(_HBXInfo_qn, Len(_HBXInfo_qn) - 1)
            End If
            If Len(_HBXInfo_st) > 0 Then
                _HBXInfo_st = Left(_HBXInfo_st, Len(_HBXInfo_st) - 1)
                _HBXInfo_st = Replace(_HBXInfo_st, vbCrLf.Chars(1), "")
                _HBXInfo_st = Replace(Replace(Replace(_HBXInfo_st, "@", ""), "$", ""), "'", "''")
            End If
            If Len(_HBXInfo_po) > 0 Then
                _HBXInfo_po = Left(_HBXInfo_po, Len(_HBXInfo_po) - 1)
                _HBXInfo_po = Replace(Replace(Replace(_HBXInfo_po, "@", ""), "$", ""), "'", "''")
            End If
            If Len(_HBXInfo_sk) > 0 Then
                _HBXInfo_sk = Left(_HBXInfo_sk, Len(_HBXInfo_sk) - 1)
            End If
            strTemp.AppendLine("<script type=""text/javascript"">")
            strTemp.AppendLine("var utag_data = {")
            strTemp.AppendLine("page_level2:         'step 6 - finish and receipt',")
            strTemp.AppendLine("page_level1:        '/orderflow'")
            strTemp.AppendLine("}")
            strTemp.AppendLine("</script>")
            strTemp.AppendLine("<script type=""text/javascript"" src=""//tealium.hs.llnwd.net/o43/utag/charter/main/prod/utag.js""></script>")

            'strTemp.AppendLine("<SCRIPT>")
            'strTemp.AppendLine("var hbxObj = new Object();")
            'strTemp.AppendLine("hbxObj.pn ='step 6 - finish and receipt';")
            'strTemp.AppendLine("hbxObj.mlc = '/orderflow';")
            'strTemp.AppendLine("hbxObj.pr = '" & Trim(_HBXInfo_pr) & "';")
            'strTemp.AppendLine("hbxObj.ca = '" & Trim(_HBXInfo_ca) & "';")
            'strTemp.AppendLine("hbxObj.pc = '" & Trim(_HBXInfo_pc) & "';")
            'strTemp.AppendLine("hbxObj.qn = '" & Trim(_HBXInfo_qn) & "';")
            'strTemp.AppendLine("hbxObj.st = '" & Trim(_HBXInfo_st) & "';")
            'strTemp.AppendLine("hbxObj.sp = " & _HBXInfo_sp & ";")
            'strTemp.AppendLine("hbxObj.sr = 1;")
            'strTemp.AppendLine("hbxObj.oi = '" & _hbxOrderID & "';")
            'strTemp.AppendLine("hbxObj.sk = '" & Trim(_HBXInfo_sk) & "';")
            'strTemp.AppendLine("hbxObj.po = '" & Trim(_HBXInfo_po) & "';")
            'strTemp.AppendLine("hbxObj.ds = " & _HBXInfo_ds & ";")
            'strTemp.AppendLine("hbxObj.ci = '';")
            'strTemp.AppendLine("hbxObj.sz = '" & Trim(_HBXInfo_sz) & "';")
            'strTemp.AppendLine("hbxObj.sa = '" & Trim(_HBXInfo_sa) & "';")
            'strTemp.AppendLine("hbxObj.sy = '" & Trim(_HBXInfo_sy) & "';")
            'strTemp.AppendLine("hbxObj.so = 'US';")
            'strTemp.AppendLine("hbxObj['ord.attr1'] = '" & Trim(_HBXInfo_Attr1) & "';")
            'strTemp.AppendLine("</script>")
            'strTemp.AppendLine("<script language=""javascript"" type=""text/javascript"" src=""../Scripts/hbx_pagecode.js""></script>")
            'strTemp.AppendLine("<script language=""javascript"" type=""text/javascript"" src=""../Scripts/hbx_order.js""></script>")
            Return strTemp.ToString
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Sub ChatComplete()
        Dim sb As New StringBuilder()
        If Len(_hbxOrderID) > 0 Then
            _hbxOrderID = Left(_hbxOrderID, Len(_hbxOrderID) - 1)
        End If
        Try
            sb.Append("<script type=""text/javascript"" language=""javascript"">")
            sb.Append("{")
            sb.Append("var chaturl;")
            sb.Append("chaturl = '../Visitors/chatlive.aspx?Chattype=SALES&orderID=" & _hbxOrderID & "&user=" & _name & "&lname=" & _lname & "&phone=" & _phone & "&mail=" & Replace(lblEmailAddress.Text, "A confirmation e-mail has been sent to ", "") & "';")
            sb.Append("eval(""javascript:window.open('../Visitors/chatlive.aspx?Chattype=SALES&orderID=" & _hbxOrderID & "&user=" & _name & "&lname=" & _lname & "&phone=" & _phone & "&mail=" & Replace(lblEmailAddress.Text, "A confirmation e-mail has been sent to ", "") & "','chat','width=550,height=660,left=50,top=15')"")")
            sb.Append("}")
            sb.Append("</script>")
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "CHATSCRIPT", sb.ToString())
        Catch ex As Exception
            Throw ex
        Finally
            sb = Nothing
        End Try
    End Sub

    Private Sub ChatInComplete()
        Dim sb As New StringBuilder()
        If Len(_hbxOrderID) > 0 Then
            _hbxOrderID = Left(_hbxOrderID, Len(_hbxOrderID) - 1)
        End If
        Try
            sb.Append("<script type=""text/javascript"" language=""javascript"">")
            sb.Append("{")
            sb.Append("eval(""javascript:window.open('../Visitors/chatlive.aspx?Chattype=SALES','chat','width=550,height=660,left=50,top=15');"")")
            sb.Append("}")
            sb.Append("</script>")
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "CHATSCRIPT", sb.ToString())
        Catch ex As Exception
            Throw ex
        Finally
            sb = Nothing
        End Try
    End Sub

    Private Sub HBXInformation()
        Dim _catalog As ICatalog = Nothing
        Dim _cart As ICart = Nothing
        Dim _items As Dictionary(Of String, ICartItem)
        Dim _item As KeyValuePair(Of String, ICartItem)
        Dim sb As StringBuilder

        _catalog = CatalogManager.Instance.GetCatalog()

        If Not _account.Address Is Nothing Then
            _HBXInfo_sy = _account.Address.City
            _HBXInfo_sa = _account.Address.State
            _HBXInfo_sz = _account.Address.Zip

            If Not HttpContext.Current.Request.Cookies("hhs") Is Nothing Then
                If HttpContext.Current.Request.Cookies("hhs").Value.ToString() = "1" Then
                    _HBXInfo_Attr1 = "Existing Service Customer"
                Else
                    _HBXInfo_Attr1 = "No Service Customer"
                End If
            Else
                _HBXInfo_Attr1 = "No Service Customer"
            End If

        End If

        If _catalog IsNot Nothing Then
            _cart = _catalog.Cart
            _items = _cart.CartItems
            sb = New StringBuilder()

            For Each _item In _items
                _HBXInfo_pr = _HBXInfo_pr & Replace(_item.Value.Name, ",", "") & ","
                _HBXInfo_ca = _HBXInfo_ca & Replace(_item.Value.Type.ToString, ",", "") & ","
                '_HBXInfo_ca = _HBXInfo_ca & "service,"
                _HBXInfo_pc = _HBXInfo_pc & _item.Value.ListPrice & ","
                _HBXInfo_qn = _HBXInfo_qn & "1,"
                _HBXInfo_st = _HBXInfo_st & _item.Value.InstallDescription
                _HBXInfo_sp = _HBXInfo_sp + _item.Value.InstallPrice
                _HBXInfo_sk = _HBXInfo_sk & CStr(_item.Value.ID).Substring(1) & ","
                _HBXInfo_po = _HBXInfo_po & Replace(_item.Value.Name, ",", "") & ":" & CType(_item.Value, ICartItem).PromotionName & ","

                _HBXInfo_ds = _HBXInfo_ds + (_item.Value.ListPrice - _item.Value.Price)
                AppendChoices(_item.Value)
            Next
        End If
    End Sub

    Private Sub AppendChoices(ByVal item As ICartItem)
        If item.Type = ItemType.Bundle Then
            'bundle
            For Each sp As ISubCartItem In item.Children.Values
                If Not CategoriesInCart.Contains(sp.Category) Then CategoriesInCart.Add(sp.Category)
                For Each f As ISubCartItem In sp.Children.Values
                    If f.Children Is Nothing AndAlso f.Children.Count = 0 Then
                        If f.IsSelected AndAlso f.FeatureType = FeatureType.IsCustomization Then
                            _HBXInfo_pr = _HBXInfo_pr & Replace(f.Name, ",", "") & ","
                            _HBXInfo_sk = _HBXInfo_sk & CStr(f.ID).Substring(1) & ","

                            If f.PriceFrequency = BLPriceFrequency.Monthly Then
                                _HBXInfo_ca = _HBXInfo_ca & Replace(f.Type.ToString, ",", "") & ","
                            Else
                                _HBXInfo_ca = _HBXInfo_ca & "installation,"
                            End If
                            _HBXInfo_pc = _HBXInfo_pc & f.ListPrice & ","
                            _HBXInfo_qn = _HBXInfo_qn & "1,"
                            _HBXInfo_ds = _HBXInfo_ds + (f.ListPrice - f.Price)
                        End If
                    Else
                        For Each c As ISubCartItem In f.Children.Values
                            If c.IsSelected AndAlso Not c.PriceFrequency = BLPriceFrequency.OneTime Then
                                _HBXInfo_pr = _HBXInfo_pr & Replace(c.Name, ",", "") & ","
                                _HBXInfo_sk = _HBXInfo_sk & CStr(c.ID).Substring(3) & ","

                                If c.PriceFrequency = BLPriceFrequency.Monthly Then
                                    _HBXInfo_ca = _HBXInfo_ca & Replace(f.Type.ToString, ",", "") & ","
                                Else
                                    _HBXInfo_ca = _HBXInfo_ca & "installation,"
                                End If
                                _HBXInfo_pc = _HBXInfo_pc & c.ListPrice & ","
                                _HBXInfo_qn = _HBXInfo_qn & "1,"
                                _HBXInfo_ds = _HBXInfo_ds + (c.ListPrice - c.Price)
                            End If
                        Next
                    End If
                Next
            Next
        Else
            ' service plan
            If Not CategoriesInCart.Contains(item.Category) Then CategoriesInCart.Add(item.Category)
            For Each f As ISubCartItem In item.Children.Values
                If f.Children Is Nothing AndAlso f.Children.Count = 0 Then
                    If f.IsSelected AndAlso f.FeatureType = FeatureType.IsCustomization Then
                        _HBXInfo_pr = _HBXInfo_pr & Replace(f.Name, ",", "") & ","
                        _HBXInfo_sk = _HBXInfo_sk & CStr(f.ID).Substring(1) & ","

                        If f.PriceFrequency = BLPriceFrequency.Monthly Then
                            _HBXInfo_ca = _HBXInfo_ca & Replace(f.Type.ToString, ",", "") & ","
                        Else
                            _HBXInfo_ca = _HBXInfo_ca & "installation,"
                        End If
                        _HBXInfo_pc = _HBXInfo_pc & f.ListPrice & ","
                        _HBXInfo_qn = _HBXInfo_qn & "1,"
                        _HBXInfo_ds = _HBXInfo_ds + (f.ListPrice - f.Price)
                    End If
                Else
                    For Each c As ISubCartItem In f.Children.Values
                        If c.IsSelected AndAlso Not c.PriceFrequency = BLPriceFrequency.OneTime Then
                            _HBXInfo_pr = _HBXInfo_pr & Replace(c.Name, ",", "") & ","
                            _HBXInfo_sk = _HBXInfo_sk & CStr(c.ID).Substring(3) & ","

                            If c.PriceFrequency = BLPriceFrequency.Monthly Then
                                _HBXInfo_ca = _HBXInfo_ca & Replace(f.Type.ToString, ",", "") & ","
                            Else
                                _HBXInfo_ca = _HBXInfo_ca & "installation,"
                            End If
                            _HBXInfo_pc = _HBXInfo_pc & c.ListPrice & ","
                            _HBXInfo_qn = _HBXInfo_qn & "1,"
                            _HBXInfo_ds = _HBXInfo_ds + (c.ListPrice - c.Price)
                        End If
                    Next
                End If
            Next
        End If
    End Sub

    Protected Sub btnAccept_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAccept.Click

        Dim userIDField As String = "CHARTER_ELOA"
        Dim passwordField As String = "ELOA_4370"
        Dim eLOANameField As String = "TestELOA"
        Dim versionField As String = "1"
        Dim dNISField As String = "9990018550"
        Dim telephoneNbrField As String = _account.Phone
        Dim firstNameField As String = _account.Person.FirstName
        Dim lastNameField As String = _account.Person.LastName
        Dim affiliateIDField As String = _account.AffliateID
        Dim affiliateNameField As String = "Charter.com Website"
        Dim affiliateTypeField As String = "dotcom"
        Dim decisionMakerField As String = "Y"
        Dim securityTypeField As String = "MaidenName"
        Dim securityValueField As String = txtMothersname.Text
        Dim localField As String = ""
        Dim localTollField As String = ""
        Dim longDistanceField As String = ""
        Dim e911Field As String = ""
        Dim statusField As String = "V"
        Dim reasonCodeField As String = ""
        Dim wTNsField(0) As String



        '#####################################
        'BUILD ELOA VALUES TO SEND TO MANAGER
        '#####################################
        If chkAccept911Services.Checked = True Then
            e911Field = "Y"
        Else
            e911Field = "N"
        End If
        'If chkInternationServiceProvider.Checked = True Then

        'Else

        'End If
        If chkLocalServiceProvider.Checked = True Then
            localField = "Y"
        Else
            localField = "N"
        End If
        If chkLocalTollServiceProvider.Checked = True Then
            localTollField = "Y"
        Else
            localTollField = "N"
        End If
        If chkLongDistanceServiceProvider.Checked = True Then
            longDistanceField = "Y"
        Else
            longDistanceField = "N"
        End If


        '##########################################################
        'SEND THE ELOA INFORMATION AND FORWARD ON TO THE NEXT PAGE
        '##########################################################
        Dim ELOAIsValid As Boolean = OrderManager.Instance.SendELOA(userIDField, passwordField, eLOANameField, versionField, dNISField, telephoneNbrField, firstNameField, lastNameField, affiliateIDField, affiliateNameField, affiliateTypeField, decisionMakerField, securityTypeField, securityValueField, localField, localTollField, longDistanceField, e911Field, statusField, reasonCodeField, wTNsField)




        '#########################
        'MOVE ON TO THE NEXT STEP
        '#########################
        pnlELOA_Host.Visible = False

        Dim canChat As String = HttpContext.Current.Application(ApplicationKey.EnableChat)
        If OrderComplete Then
            If ELOAIsValid = True Then
                '########################################################
                'CONTINUE THE NORMAL FLOW TO POTENTIALLY LEAVE THIS PAGE.
                '########################################################
                btnGetReceipt_Click(Nothing, Nothing)
                HBXInformation()
                pnlThankYou.Visible = True

                If _noschedule Then
                    pnlAlmostFinished.Visible = True
                    If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                        ChatComplete()
                    End If
                Else
                    pnlAlmostFinished.Visible = False
                End If
            Else
                '###################################################
                'JUST SHOW THE ALMOST FINISHED AND THANK YOU PANELS
                '###################################################
                btnGetReceipt_Click(Nothing, Nothing)
                HBXInformation()

                pnlThankYou.Visible = True
                pnlAlmostFinished.Visible = True

                If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                    ChatComplete()
                End If
            End If




        Else
            pnlThankYou.Visible = False
            pnlAlmostFinished.Visible = True
            If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                ChatInComplete()
            End If
        End If


    End Sub

    Protected Sub btnDecline_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDecline.Click

        Dim userIDField As String = "CHARTER_ELOA"
        Dim passwordField As String = "ELOA_4370"
        Dim eLOANameField As String = "TestELOA"
        Dim versionField As String = "1"
        Dim dNISField As String = "9990018550"
        Dim telephoneNbrField As String = _account.Phone
        Dim firstNameField As String = _account.Person.FirstName
        Dim lastNameField As String = _account.Person.LastName
        Dim affiliateIDField As String = _account.AffliateID
        Dim affiliateNameField As String = "Charter.com Website"
        Dim affiliateTypeField As String = "dotcom"
        Dim decisionMakerField As String = "Y"
        Dim securityTypeField As String = "MaidenName"
        Dim securityValueField As String = txtMothersname.Text
        Dim localField As String = ""
        Dim localTollField As String = ""
        Dim longDistanceField As String = ""
        Dim e911Field As String = ""
        Dim statusField As String = "V"
        Dim reasonCodeField As String = ""
        Dim wTNsField(0) As String



        '#####################################
        'BUILD ELOA VALUES TO SEND TO MANAGER
        '#####################################

        e911Field = "N"
        localField = "N"
        localTollField = "N"
        longDistanceField = "N"

        '##########################################################
        'SEND THE ELOA INFORMATION AND FORWARD ON TO THE NEXT PAGE
        '##########################################################
        Dim ELOAIsValid As Boolean = OrderManager.Instance.SendELOA(userIDField, passwordField, eLOANameField, versionField, dNISField, telephoneNbrField, firstNameField, lastNameField, affiliateIDField, affiliateNameField, affiliateTypeField, decisionMakerField, securityTypeField, securityValueField, localField, localTollField, longDistanceField, e911Field, statusField, reasonCodeField, wTNsField)

        '#########################
        'MOVE ON TO THE NEXT STEP
        '#########################
        pnlELOA_Host.Visible = False

        Dim canChat As String = HttpContext.Current.Application(ApplicationKey.EnableChat)
        If OrderComplete Then
            If ELOAIsValid = True Then
                '########################################################
                'CONTINUE THE NORMAL FLOW TO POTENTIALLY LEAVE THIS PAGE.
                '########################################################
                btnGetReceipt_Click(Nothing, Nothing)
                HBXInformation()
                pnlThankYou.Visible = True

                If _noschedule Then
                    pnlAlmostFinished.Visible = True
                    If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                        ChatComplete()
                    End If
                Else
                    pnlAlmostFinished.Visible = False
                End If
            Else
                '###################################################
                'JUST SHOW THE ALMOST FINISHED AND THANK YOU PANELS
                '###################################################
                btnGetReceipt_Click(Nothing, Nothing)
                HBXInformation()

                pnlThankYou.Visible = True
                pnlAlmostFinished.Visible = True

                If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                    ChatComplete()
                End If
            End If

        Else
            pnlThankYou.Visible = False
            pnlAlmostFinished.Visible = True
            If canChat IsNot Nothing AndAlso canChat.ToLower() = "true" Then
                ChatInComplete()
            End If
        End If
    End Sub

    
End Class
