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 CharterDotCom.WebSite.Library.BLCommon
Imports System.Collections.Generic
Imports Utilities

Partial Class Controls_CustomerIdentification
    Inherits System.Web.UI.UserControl

    Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnContinue.Click

        lblError.Text = String.Empty
        If rblIdentify.SelectedValue.Equals("new") Then
            ' new customer
            AccountManager.Instance.ChangeCustomerStatus(UserStatus.Localized.ToString)
            If Request.QueryString(QueryStringName.TargetPage) Is Nothing OrElse Request.QueryString(QueryStringName.TargetPage).Equals(String.Empty) Then
                Response.Redirect("Loading.aspx?" & QueryStringName.Destination & "=AllOffers.aspx")
            Else
                Response.Redirect(Server.UrlDecode("Loading.aspx?" & QueryStringName.Destination & "=" & Request.QueryString(QueryStringName.TargetPage) & Querystring.BuildFeatureChoiceQueryString(Request.QueryString)))
            End If
        Else
            ' existing customer

            '10/15/2007 Brad Miller - Remove Acct# and SSN fields
            If txtName.Text.Equals(String.Empty) Then
                ' none of the credentials are entered so treat as new customer
                ' DB - removing this.  This is just an experiment to see what happens
                ' when we make the customer enter something.  Not the prettiest solution,
                ' but it is a quick fix
                AccountManager.Instance.ChangeCustomerStatus(UserStatus.Localized.ToString)
                Dim destination As String = Request.QueryString(QueryStringName.TargetPage) & Querystring.BuildFeatureChoiceQueryString(Request.QueryString)
                If destination Is Nothing OrElse destination.Equals(String.Empty) Then
                    Response.Redirect("Loading.aspx?" & QueryStringName.Destination & "=AllOffers.aspx")
                Else
                    Response.Redirect(Server.UrlDecode("Loading.aspx?" & QueryStringName.Destination & "=" & destination))
                End If
                '
                ' All are empty, populate error label
            Else
                ' sign in
                If ValidateUsername(txtName.Text.Trim()) = True Then
                    If ValidatePassword(txtPassword.Text.Trim()) = True Then
                        lblError.Text = ""
                        If txtPassword.Text.Equals(String.Empty) Then
                            lblPasswordRequired.Visible = True
                        Else

                            '###################################################################################
                            'ROD COPELAND JAN 23, 2007
                            'RIGHT NOW THE ValidateMyAccountIDandPW_NO_SIGN_IN METHOD IS RETURNING THE ACCOUNT 
                            'NUMBER BACK IF THE MEMBER SERVICE ID AND PW ARE VALID. IF THEY ARE INVALID THEN 
                            'THE VALUE OF NOTHING IS RETURNED.  AT SOME POINT WHEN THE BUSINESS REQUIRES THAT 
                            'WHEN A PERSON VALIDATES THE MEMBER SERVICES ID AND PW HERE, WE MAY NEED TO 
                            'EVENTUALLY ALTER THE SIGN METHOD TO RETURN AN ACCOUNT NUMBER. ANOTHER POSSIBILITY 
                            'IS TO HAVE ANOTHER SIGNIN METHOD (USED JUST FOR THE ORDER FLOW SIGNIN ONLY, NOT 
                            'THE NORMAL LOGIN.ASPX) CREATED THAT HAS A DIFF SIGNITURE AND RETURN OBJECT.  
                            'INTERNALLY, THAT SIGN IN METHOD WOULD AUTHENTICATE AND GET THE ACCOUNT NUMBER 
                            'BACK AND THEN PASS THE ACCOUNT NUMBER INTO ValidateUser(String.Empty, lAccountNumber.Trim(), 0) 
                            'TO VALIDATE THE USER ACTUALLY IS THE CURRENT USER LIVING AT THE ADDRESS THEY 
                            'TRIED TO LOCALIZE AT. 
                            '###################################################################################
                            Dim lTempAccount As IAccount = AccountManager.Instance.GetAccount()
                            Dim lAccountNumber As String = ""

                            '#########################################################
                            'DEFAULT THE AFFILATE ID TO THE CHARTERDOT COM AFFILIATE IN 
                            'THE EVENT THE AFFILIATE ID IS NOT PASSED FROM THE AFFLIATE 
                            'FLOW. KEEP IN MIND THIS PAGE IS VISIBILE FROM THE AFFILIATE 
                            'FLOW AND NORMAL FLOW SO SIGN IN SHOULD BE ABLE TO HANDLE 
                            'BOTH.
                            '#########################################################
                            Dim lAffiliateID As Integer = CharterDotCom.CommonEntities.Library.Common.m_CHARTER_AFFLIATE_ID
                            If Not (lTempAccount Is Nothing) Then
                                If lTempAccount.AffliateID <> CharterDotCom.CommonEntities.Library.Common.m_CHARTER_AFFLIATE_ID Then
                                    If lTempAccount.AffliateID > 0 Then
                                        lAffiliateID = lTempAccount.AffliateID
                                    End If
                                End If
                            End If

                            If AccountManager.Instance.SignIn(txtName.Text.ToLower(), txtPassword.Text, lAffiliateID) Then
                                '####################################
                                'SET THE FORMS AUTHENTICATION
                                '####################################
                                Dim cookie As HttpCookie
                                Dim ticket As FormsAuthenticationTicket
                                Dim encryptedText As String
                                Dim roleName As String = "member"
                                ' issue 26553
                                Dim accountInfo As IAccount

                                ticket = New FormsAuthenticationTicket(1, txtName.Text.ToLower(), DateTime.Now, DateTime.Now.AddMinutes(60), False, roleName)
                                encryptedText = FormsAuthentication.Encrypt(ticket)
                                cookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedText)
                                Response.Cookies.Add(cookie)

                                ' issue 26553
                                accountInfo = AccountManager.Instance.GetAccount()
                                CookieHandler.StoreCookies(txtName.Text, accountInfo.OSSProvidedAccountNumber, _
                                                           Response, Server, _
                                                           Application("COOKIE_DOMAIN"))

                                Dim lAccount As IAccount = AccountManager.Instance.GetAccount()
                                If Not (lAccount Is Nothing) Then
                                    If Not (lAccount.Bill Is Nothing) Then
                                        If (lAccount.Bill.Count() > 0) Then
                                            '###################################################
                                            'REMOVE THE STATEMENT CODE FROM THE ACCOUNT NUMBER 
                                            '###################################################
                                            lAccountNumber = lAccount.Bill(0).AccountNumber
                                        End If
                                    End If
                                End If

                                If IsNumeric(lAccountNumber.Trim()) Then
                                    '######################################################################################
                                    'AT THIS POINT THE USER WOULD HAVE SUCCESSFULLY LOGGED INTO THE MYACCOUNT AREA, 
                                    'WE NOW NEED TO VALIDATE THEY ARE THE CORRECT LOGIN FOR THIS ADDRESS BY MATCHING 
                                    'THE ACCOUNT NUMBER TO THE SERVICEABILITY RESPONSE ACCCOUNT NUMBER.
                                    '######################################################################################
                                    lblError.Text = AccountManager.Instance.ValidateUser(lAccountNumber.Trim())

                                    If lblError.Text.Trim() <> "" Then
                                        '#######################################################################
                                        'THE USER FAILED TO MATCH THE ACCOUNT NUMBER FROM THE MYACCOUNT TO THE 
                                        'ACCOUNT NUMBER FOUND IN SERVICEABILITIY.  JUST SIGN THEM OUT AGAIN.
                                        '#######################################################################
                                        AccountManager.Instance.SignOut()
                                        FormsAuthentication.SignOut()

                                        ' issue 26553
                                        CookieHandler.ClearCookies(Response, _
                                                        Request, _
                                                        Application("COOKIE_DOMAIN"))

                                        AccountManager.Instance.UpdateAccountObj(lTempAccount)
                                        AccountManager.Instance.ChangeCustomerStatus(UserStatus.Localized.ToString)
                                    End If
                                End If

                            Else
                                '##################################################################################
                                '##########     E R R O R   C O D E   M A P P I N G    S O L U T I O N      #######
                                '#################          MODIFIED BY ROD COPELAND, 5/2/2007     ################ 
                                '##################################################################################
                                'WRITE THE (IDEALLY) CHARTER FRIENDLY ERROR MESSAGES TO THE PAGE.  
                                'THESE MESSAGES ARE MANAGED IN THE CHARTERDOTCOM.ADMIN.ERROR_CODE_MAPPING TABLE.
                                'THE UNDERLYING LOGIC WILL DISPLAY THE DATASOURCE ERROR MESSAGE IF A 
                                'CHARTERDOTCOM FRIENDLY ERROR MESSAGE IS NOT PRESENT ON THE RECORD.
                                'THERE MAY BE MORE THAN ONE ERROR MESSAGE THAT COMES BACK, DISPLAY 
                                'ACCORDINGLY.
                                '##################################################################################
                                Select Case True
                                    Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                        lblError.Text = AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage
                                        AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                    Case Else
                                        lblError.Text = "Sorry, we're unable to take your request at this time."
                                End Select
                                '##################################################################################
                            End If
                        End If
                    Else
                        lblError.Text = "<b>Password</b> fields do not allow \(back slash) or &quot;(quotes)."
                    End If
                Else
                    lblError.Text = "The only special characters allowed for <b>Username</b> are .(dot), -(dash) or _(underscore)."
                End If
            End If
            If lblError.Text.Equals(String.Empty) Then
                Dim destination As String = Request.QueryString(QueryStringName.TargetPage)
                If destination Is Nothing OrElse destination.Equals(String.Empty) Then
                    Response.Redirect("Loading.aspx?" & QueryStringName.Destination & "=AllOffers.aspx")
                Else
                    Response.Redirect(Server.UrlDecode("Loading.aspx?" & QueryStringName.Destination & "=" & destination))
                End If
            End If
        End If
    End Sub

    Private Function ValidateUsername(ByVal strTemp As String) As Boolean
        Dim strRegExp As String = ""

        If strTemp IsNot Nothing Then
            strRegExp = "^[a-zA-Z0-9._-]+$"
            Return Regex.IsMatch(strTemp, strRegExp)
        Else
            Return True
        End If

    End Function

    Private Function ValidatePassword(ByVal strTemp As String) As Boolean
        If strTemp IsNot Nothing Then
            If strTemp.IndexOf("\") > 0 OrElse strTemp.IndexOf("""") > 0 Then
                Return False
            Else
                Return True
            End If
        End If
    End Function

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If Not IsPostBack Then
            btnContinue.ValidationGroup = "CustomerIdentity"
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblPasswordRequired.Visible = False
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        If rblIdentify.SelectedValue.Equals("exist") Then
            tblExisting.Visible = True
        Else
            tblExisting.Visible = False
        End If
        If lblError.Text.Equals(String.Empty) Then
            lblError.Visible = False
        Else
            lblError.Visible = True
        End If
    End Sub

End Class