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.CommonEntities.Library.Common
Imports CharterDotCom.WebSite.Library
Imports System.Net

Partial Class Controls_AffiliateFinishOrder
  Inherits System.Web.UI.UserControl
  Private _hbxOrderID As String
  Private _email As String
  Private _phone As String
  Private _name 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

  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

  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
        Dim canChat As String = HttpContext.Current.Application(ApplicationKey.EnableChat)
        Dim _account As IAccount
        Dim _cart As ICart
        Dim promoDisclaimer As String = ""


        '########################################################
        ' Jonathan Parks   9/7/08    Issue #4524
        '########################################################
        ' added the following code to get the PromotionDisclaimer
        '########################################################

        _cart = AffliateCatalogManager.Instance.GetCatalog().Cart

        For Each cartItem As ICartItem In _cart.CartItems.Values
            If promoDisclaimer.Length > 0 Then
                promoDisclaimer &= "<br /><br />"
            End If
            promoDisclaimer &= cartItem.PromotionDisclaimer
        Next

        If promoDisclaimer.Length = 0 Then
            'Get the disclaimer from the ServicePlan
            For Each planItem As ICartItem In AffliateCatalogManager.Instance.GetCatalog().ServicePlans.Values
                If _cart.CartItems.ContainsKey(planItem.ID) Then
                    If promoDisclaimer.Length > 0 Then
                        promoDisclaimer &= "<br /><br />"
                    End If
                    promoDisclaimer &= planItem.PromotionDisclaimer
                End If
            Next
        End If

        ltrDisclaimer.Text = promoDisclaimer

        '########################################################


        ChatContent = "A Customer Care Representative will Chat with you in just a moment."
        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)

            If OrderComplete Then

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

                vendorType = AccountManager.Instance.GetAccount().BillingVendorType

                If vendorType = BillingVendorType.CSG Then
                    ddlCardIssuer.Items.Add(New ListItem("American Express", 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
            End If

            pnlFirstMonthPayment.Visible = False
            pnlRegisterNow.Visible = False

            If OrderComplete Then
                btnGetReceipt_Click(Nothing, Nothing)
                HBXInformation()
                pnlThankYou.Visible = True
                pnlAlmostFinished.Visible = True

                ' 9/2007 jbm - Add for G2B 4.1
                _account = AccountManager.Instance.GetAccount()
                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
                    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 If
    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
    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, IAffiliateOrder.IAffiliateAppointment) = Nothing
    Dim _appointment As KeyValuePair(Of ScheduleType, IAffiliateOrder.IAffiliateAppointment) = Nothing
    Dim result As IConfirmation = Nothing
        Dim sb As StringBuilder
        Dim followUpMessage As StringBuilder
        Dim dm As DateTime

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

    If _person IsNot Nothing Then
      _name = _person.FirstName ' & " " & _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
        AffiliateOrderManager.Instance.GetConfirmationInfo(_confirmations)

    If _confirmations IsNot Nothing Then
            sb = New StringBuilder()
            followUpMessage = 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 & ","
                '######################################
                ' Jonathan Parks  9/4/08  Issue #4524
                '######################################
                'Added the following code to get the follow up message
                '######################################
                followUpMessage.Append(_confirmation.Value.Message)
                If _confirmations.Count > 1 Then
                    followUpMessage.Append("<br /><br />")
                End If
      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

            ltrConfirmations.Text = sb.ToString()
            ltrFollowUpMessage.Text = followUpMessage.ToString()

      ' send an email message

      AffiliateOrderManager.Instance.SendOrderConfirmationEmail()
    End If

    ' render appointements

    AffiliateOrderManager.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("</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 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 = AffliateCatalogManager.Instance.GetCatalog()

    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 & "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 & 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
        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 & "service,"
              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 & "service,"
                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
      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 & "service,"
            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 & "service,"
              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

  Private Function 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 & "&phone=" & _phone & "&mail=" & lblEmailAddress.Text & "&Prompt=Yes&AutoLogin=1';")
            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 Function

    Private Function 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("var chaturl;")
            sb.Append("chaturl = '../Visitors/chatlive.aspx?Chattype=SALES';")
            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 Function
End Class

