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.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
Imports CharterDotCom.CommonEntities.Library.Common
Imports CharterDotCom.WebSite.Library

Partial Class Controls_ManageLogin
    Inherits System.Web.UI.UserControl

    Public strPlaceholderQuestion As String = "Choose One..."
    Public strPlaceholderPassword1 As String = String.Empty
    Public strPlaceholderPassword2 As String = String.Empty

    ' issue 28415
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim _account As IAccount = AccountManager.Instance.GetAccount()

        Call SetValidatorsOnPage(_account)
        Call PreloadDataToPage(_account)
    End Sub

    Protected Sub SetValidatorsOnPage(ByVal _account As IAccount)
        Dim groupID As String = ""
        ltrMessageUPP.Text = ""
        ltrMessageUPP.ForeColor = Drawing.Color.Black

        ltrMessageOAS.Text = ""
        ltrMessageOAS.ForeColor = Drawing.Color.Black

        lblErrorOAS.Text = ""
        lblErrorUPP.Text = ""

        ltrMessageCode.Text = ""
        ltrMessageCode.ForeColor = Drawing.Color.Black
        lblErrorCode.Text = ""

        groupID = Me.ID & "OAS"
        vldAnswerRequired.ValidationGroup = groupID
        vldEmailRegEx.ValidationGroup = groupID
        vldEmailRequired.ValidationGroup = groupID
        vldQuestion.ValidationGroup = groupID
        btnSaveOAS.ValidationGroup = groupID

        groupID = Me.ID & "UPP"
        vldUserNameRequired.ValidationGroup = groupID
        vldCurrentPasswordRequired.ValidationGroup = groupID
        vldPwdRequired.ValidationGroup = groupID
        revLength.ValidationGroup = groupID
        revLowercase.ValidationGroup = groupID
        revNumber.ValidationGroup = groupID
        revUppercase.ValidationGroup = groupID
        VldtxtPassword2Required.ValidationGroup = groupID
        btnSaveUPP.ValidationGroup = groupID

        groupID = Me.ID & "CODE"
        vldSecurityCodeRequired.ValidationGroup = groupID
        vldSecurityCodeNumeric.ValidationGroup = groupID
        vldRetypeSecurityCodeRequired.ValidationGroup = groupID
        vldRetypeSecurityCodeNumeric.ValidationGroup = groupID
        vldCodeCompare.ValidationGroup = groupID
        btnSaveCode.ValidationGroup = groupID

        If _account IsNot Nothing AndAlso _
        _account.CSGcustomerID IsNot Nothing AndAlso _
        _account.OSSProvidedAccountNumber IsNot Nothing Then
            '########################################################################
            'MyAccount Security Code Update Sriman Kanuri March 2010
            'Hide New Security code boxes panel invisible on first load
            'on clicking View code, we set the panel to be visible
            'also, we only want to show code update result if the update is succesful
            'so we set that label hidden on load
            'check if both CustomerId and Account number are available
            '(this could happen if for any reason EAI web service to retrieve account number and customer 
            'statements fails on login page)
            'if not we can get security code or update the security code
            'so show only the cms panel that the customerID is not available
            '########################################################################
            Me.pnlNewcode.Visible = False
            Me.spnrequired.Visible = False
        End If

    End Sub

    Private Sub PreloadDataToPage(ByVal _account As IAccount)

        If Not IsPostBack Then
            If Not (_account Is Nothing) Then
                '##########################################################
                'INSERT THE VAULE OF 'CHOOSE ONE' IN THE QUESTION LIST.
                '##########################################################
                If _account.Person Is Nothing OrElse String.IsNullOrEmpty(_account.Person.ContactEmailAddress) Then
                    '#########################################################
                    'ADD THE DEFAULT QUESTION TO THE LIST AS A STARTING PLACE 
                    'IN PREPARATION OF USER NEEDING TO UPDATE THE QUESTION.
                    '#########################################################
                    ddlQuestion.Items.Add(strPlaceholderQuestion)
                End If

                '####################################################################################
                'MODIFICATION   ROD COPELAND    MARCH 20, 2008  ISSUE ID 2976
                'CHANGE ADDED TO INSERT THE VAULE OF 'CHOOSE ONE' IN THE QUESTION LIST.
                'THE SECURITY QUESTIONS USED FOR ALL USERS WAS FIRST COLLECTED 
                'IN THE SIGN IN PROCESS/BLACCOUNTMANAGER.
                '#######################################################################
                Dim tempQuestions As List(Of String) = AccountManager.Instance.GetSecurityQAWithoutAccount()
                If tempQuestions IsNot Nothing Then
                    For Each strQuestion As String In tempQuestions
                        ddlQuestion.Items.Add(strQuestion)
                    Next
                End If

                '##############################
                'LOAD CONTACT EMAIL TO PAGE.
                '##############################
                If Not (_account.Person Is Nothing) Then
                    If Not (_account.Person.ContactEmailAddress Is Nothing) Then
                        txtEmail.Text = _account.Person.ContactEmailAddress
                        SetAsUpdatePage("account_settings_page")
                    Else
                        SetAsUpdatePage("additional_info_page")
                    End If
                Else
                    SetAsUpdatePage("additional_info_page")
                End If

                '##############################
                'LOAD LOGIN ID TO PAGE.
                '##############################
                If Not (_account.LoginID Is Nothing) Then
                    txtUserName.Text = _account.LoginID
                End If

                '##############################
                'LOAD SECURITY QUESTION TO PAGE.
                '##############################
                If Not String.IsNullOrEmpty(_account.SecurityQuestion) Then
                    ddlQuestion.SelectedValue = _account.SecurityQuestion
                Else
                    SetAsUpdatePage("additional_info_page")
                End If

                '##############################
                'LOAD SECURITY ANSWER TO PAGE.
                '##############################
                If Not String.IsNullOrEmpty(_account.SecurityAnswer) Then
                    txtAnswer.Text = _account.SecurityAnswer
                Else
                    SetAsUpdatePage("additional_info_page")
                End If
            End If
        End If
    End Sub

    Private Sub SetAsUpdatePage(ByVal strPageStatusType As String)

        If Not IsPostBack Then
            Select Case strPageStatusType.ToLower()
                Case "additional_info_page"
                    Me.NormalInstructions.Visible = False
                    Me.lblOASIntroText.Text = ContentManager.Instance.GetContent("myaccount:myprofile:additionalinfoneeded", 1, OwnerType.Other)
                    Me.pnlNormalInstructions.Visible = True
                    Me.pnlSecuritycodeIntro.Visible = True
                    Me.btnSaveOAS.Focus()

                Case "account_settings_page"
                    Me.NormalInstructions.Visible = True
                    Me.lblOASIntroText.Text = "<p>You may also change your Security question/answer and preferred contact email address.</p>"
                    Me.pnlNormalInstructions.Visible = True
                    Me.pnlSecuritycodeIntro.Visible = True
                    Me.txtUserName.Focus()

                Case Else
                    Me.NormalInstructions.Visible = True
                    Me.lblOASIntroText.Text = "<p>You may also change your Security question/answer and preferred contact email address.</p>"
                    Me.pnlNormalInstructions.Visible = True
                    Me.pnlSecuritycodeIntro.Visible = True
                    Me.txtUserName.Focus()

            End Select
        End If

    End Sub

    Private Sub SetAsUpdatePageDefault()

        Me.NormalInstructions.Visible = True
        Me.lblOASIntroText.Text = "<p>You may also change your Security question/answer and preferred contact email address.</p>"
        Me.pnlNormalInstructions.Visible = True
        Me.pnlSecuritycodeIntro.Visible = True
        Me.txtUserName.Focus()

    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
        Else
            Return False
        End If

    End Function

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

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

    End Function

    Protected Sub btnSaveUPP_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSaveUPP.Click
        Dim _account As IAccount
        Dim _succeeded As Boolean
        Dim sb As StringBuilder
        Dim question As String = String.Empty
        Dim email As String = String.Empty

        If Not (Page.IsValid) Then
            Return
        End If
        _account = AccountManager.Instance.GetAccount()

        _succeeded = False
        sb = New StringBuilder()

        If (Not (_account Is Nothing)) AndAlso _
           (Not (_account.LoginID Is Nothing)) Then
            '#######################################################################
            'MODIFICATION   ROD COPELAND    MARCH 20, 2008  ISSUE ID 2877
            'THE BUSINESS ASKED FOR THE PAGE TO SHOW A DEFAULT VALUE IN THE PASSWORD 
            'FIELD RATHER THAN A BLANK TEXT BOX.  SO BE IT. IF IT EXISTS HERE, 
            'JUST STRIP IT OUT.
            '#######################################################################
            If txtPassword.Text.Trim().ToLower() = strPlaceholderPassword1.Trim().ToLower() And strPlaceholderPassword1.Trim().ToLower() <> String.Empty Then
                '#########################################
                'STRIP THE DEFAULT VALUE FROM THE FIELD.
                '#########################################
                txtPassword.Text = txtPassword.Text.Replace(strPlaceholderPassword1, String.Empty)
            End If
            If txtPassword2.Text.Trim().ToLower() = strPlaceholderPassword2.Trim().ToLower() And strPlaceholderPassword2.Trim().ToLower() <> String.Empty Then
                '#########################################
                'STRIP THE DEFAULT VALUE FROM THE FIELD.
                '#########################################
                txtPassword2.Text = txtPassword2.Text.Replace(strPlaceholderPassword2, String.Empty)
            End If

            '########################################################################
            'MODIFICATION   MARK SNYDER    JUNE 18, 2008  ISSUE ID 3634
            'VALIDATE THE CURRENT LOGIN ID/PASSWORD COMBINATION BEFORE PROCEEDING WITH
            'A PASSWORD CHANGE.
            '########################################################################
            If txtPassword.Text.Trim() <> "" Then
                If txtCurrentPassword.Text.Trim() = "" Then
                    lblErrorUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " Current password is required when changing password." & "</div>"
                    lblErrorUPP.Visible = True
                    Exit Sub
                Else
                    If (AccountManager.Instance.ValidateMyAccountIDandPW_NO_SIGN_IN(_account.LoginID, txtCurrentPassword.Text) Is Nothing) Then
                        lblErrorUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " Current password does not match the password on file." & "</div>"
                        lblErrorUPP.Visible = True
                        Exit Sub
                    End If
                End If
            End If

            If Not (_account.LoginID.Trim().ToLower() = txtUserName.Text.Trim().ToLower() _
            And txtPassword.Text.Trim() = "") Then
                If ValidateUsername(txtUserName.Text.Trim()) = True Then
                    If ValidatePassword(txtPassword.Text.Trim()) = True Then
                        lblErrorUPP.Visible = False
                        '####################################################################
                        'CHECK THAT ACCOUNT OBJECT LOGIN ID HAS A VALUE TO COMPARE TO.
                        'CHECK THAT THE FIELD DOES NOT HAVE A EMPTY STRING FOR A VALUE.
                        'CHECK THAT LOGIN ID TEXT FIELD MATCHES THE ACCOUNT OBJECT LOGIN ID.
                        '####################################################################
                        If Not (_account.LoginID Is Nothing) Then
                            If txtUserName.Text.Trim().Length() > 0 Then
                                If txtUserName.Text.Trim().ToLower() <> _account.LoginID.Trim().ToLower() Then

                                    _succeeded = AccountManager.Instance.ChangeAccountUserID(txtUserName.Text.Trim().ToLower())
                                    If _succeeded Then
                                        sb.Append("New Username saved successfully. ")
                                    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.
                                        '##################################################################################
                                        ltrMessageUPP.ForeColor = Drawing.Color.Red
                                        Select Case True
                                            Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                                sb.Append(AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                                AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                            Case Else
                                                sb.Append("Failed to save New Username. ")
                                        End Select
                                    End If
                                End If
                            End If
                        End If

                        '##############################################################
                        'CHECK THAT THE NEW PASSWORD MATCHES THE RETYPED NEW PASSWORD.
                        'CHECK THAT THE FIELD DOES NOT HAVE A EMPTY STRING FOR A VALUE
                        '##############################################################
                        If txtPassword.Text().Trim() = txtPassword2.Text().Trim() Then
                            If txtPassword.Text.Trim().Length > 0 Then
                                _succeeded = AccountManager.Instance.ChangeAccountPassword(txtPassword.Text)
                                If _succeeded Then
                                    sb.Append("New Password saved successfully. ")
                                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.
                                    '##################################################################################
                                    ltrMessageUPP.ForeColor = Drawing.Color.Red
                                    Select Case True
                                        Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                            sb.Append("" & AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                            AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                        Case Else
                                            sb.Append("Failed to save New Password. Password should be at least 8 characters. ")
                                    End Select
                                End If
                            End If
                        Else
                            ltrMessageUPP.ForeColor = Drawing.Color.Red
                            sb.Append("Repeat New Password does not match New Password. ")
                        End If
                    Else
                        lblErrorUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " <b>Password</b> fields do not allow \(back slash) or &quot;(quotes)." & "</div>"
                        lblErrorUPP.Visible = True
                    End If
                Else
                    lblErrorUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " The only special characters allowed for <b>Username</b> are .(dot), -(dash) or _(underscore)." & "</div>"
                    lblErrorUPP.Visible = True
                End If
            Else
                lblErrorUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " No change entered. Please update the fields you would like to change and then click Save.<br/><br/>" & "</div>"
                lblErrorUPP.Visible = True
            End If
        End If

        If sb.Length = 0 Then
            ltrMessageUPP.Visible = False
            Return
        End If

        If _succeeded Then
            ltrMessageUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/sup_icon_successChange.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
        Else
            ltrMessageUPP.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
        End If

        ltrMessageUPP.Visible = True

    End Sub

    Protected Sub btnSaveOAS_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSaveOAS.Click
        Dim _account As IAccount
        Dim _succeeded As Boolean
        Dim sb As StringBuilder
        Dim question As String = String.Empty
        Dim email As String = String.Empty

        ltrMessageOAS.Text = ""
        ltrMessageOAS.ForeColor = Drawing.Color.Black

        lblErrorOAS.Text = ""

        If Page.IsValid Then
            _account = AccountManager.Instance.GetAccount()

            _succeeded = False
            sb = New StringBuilder()
            If Not (_account Is Nothing) Then
                If Not (_account.LoginID Is Nothing) Then
                    If Not (ddlQuestion Is Nothing) Then
                        If Not (ddlQuestion.Items Is Nothing) Then
                            '#######################################################################
                            'MODIFICATION   ROD COPELAND    MARCH 20, 2008  ISSUE ID 2976
                            'NOW THAT THE VALUE OF 'CHOOSE ONE...' IS IN THE QUESTION LIST, WE NEED TO 
                            'EXCLUDE THAT AS AN OPTION TO SET WHEN MODIFYING A MEMBER SERVICE ACCOUNT.
                            '#######################################################################
                            If ddlQuestion.SelectedItem.ToString().Trim().ToLower() = strPlaceholderQuestion.Trim().ToLower() Then
                                ltrMessageOAS.ForeColor = Drawing.Color.Red
                                ltrMessageOAS.Text = "Select a Security Question from the list.<br/>"
                                ltrMessageOAS.Visible = True
                                Exit Sub
                            Else
                                question = ddlQuestion.SelectedItem.ToString().ToLower()
                            End If
                        End If
                    End If '4

                    If Not (_account.Person Is Nothing) Then
                        If Not (_account.Person.ContactEmailAddress Is Nothing) Then
                            email = _account.Person.ContactEmailAddress
                        End If
                    End If

                    Dim accountSQ As String = _account.SecurityQuestion
                    If accountSQ Is Nothing Then
                        accountSQ = ""
                    Else
                        accountSQ = accountSQ.Trim().ToLower()
                    End If
                    Dim accountSA As String = _account.SecurityAnswer
                    If accountSA Is Nothing Then
                        accountSA = ""
                    Else
                        accountSA = accountSA.Trim().ToLower()
                    End If

                    If Not (question.ToLower() = accountSQ.ToLower() And txtAnswer.Text.Trim().ToLower() = accountSA.ToLower() And email = txtEmail.Text.Trim().ToLower()) Then


                        '##############################################################
                        'CHECK THAT QUESTION LIST HAS AT LEAST ONE ITEM IN IT.
                        'CHECK THAT ANSWER TEXT HAS A VALUE.
                        'CHECK THAT QUESTION TEXT IS DIFF THAN ACCOUNT QUESTION VALUE OR
                        'CHECK THAT ANSWER TEXT IS DIFF THAN ACCOUNT ANSWER VALUE.
                        '##############################################################
                        If Not (ddlQuestion Is Nothing) Then
                            If Not (ddlQuestion.Items Is Nothing) Then
                                If (ddlQuestion.Items.Count > 0) Then
                                    If (txtAnswer.Text.Trim().Length() > 0) Then
                                        '12
                                        If ddlQuestion.SelectedItem.Text.Trim().ToLower() <> accountSQ Or txtAnswer.Text.Trim().ToLower() <> accountSA Then
                                            _succeeded = AccountManager.Instance.ChangeSecurityQA(ddlQuestion.SelectedItem.Text, txtAnswer.Text)
                                            If _succeeded Then

                                                lblErrorOAS.Text = ""
                                                ltrMessageOAS.Text = ""

                                                sb.Append("Security Question and Answer has been successfully updated. ")
                                            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.
                                                '##################################################################################
                                                ltrMessageOAS.ForeColor = Drawing.Color.Red
                                                Select Case True
                                                    Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                                        sb.Append("" & AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                                        AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                                    Case Else
                                                        sb.Append("Failed to save New Security Question/Answer. ")
                                                End Select
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If
                        '#######################################################################
                        'CHECK THAT EMAIL TEXT HAS A VALUE.
                        'CHECK THAT ACCOUNT CONTACT EMAIL HAS A VALUE AND THEN COMPARE THE TWO.
                        '#######################################################################
                        If (txtEmail.Text.Trim().Length() > 0) Then
                            If Not (_account Is Nothing) Then
                                If Not (_account.Person Is Nothing) Then

                                    '#############################################
                                    'ROD COPELAND   6/30/2010   ISSUE ID 9647
                                    '#############################################
                                    If String.IsNullOrEmpty(_account.Person.ContactEmailAddress) AndAlso Not String.IsNullOrEmpty(txtEmail.Text) Then
                                        '##########################################################################################
                                        'NO CURRENT CONTACT EMAIL IN OSS, SO JUST TAKE WHAT THEY GAVE US AND UPDATE OSS WITH IT.
                                        '##########################################################################################
                                        _succeeded = AccountManager.Instance.ChangeContactEMailAddress(txtEmail.Text.Trim().ToLower())
                                        If _succeeded Then
                                            If sb.Length <= 0 Then
                                                sb.Append("Your Contact Email address has been successfully updated.")
                                            Else
                                                sb.Append("</br>Your Contact Email address has been successfully updated.")
                                            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.
                                            '##################################################################################
                                            ltrMessageOAS.ForeColor = Drawing.Color.Red
                                            Select Case True
                                                Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                                    sb.Append("" & AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                                    AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                                Case Else
                                                    sb.Append("Failed to save Contact Email. ")
                                            End Select
                                        End If
                                    Else
                                        '##########################################################################################
                                        'WE HAVE A CURRENT CONTACT EMAIL IN OSS, MAKE SURE WHAT THEY HAVE PROVIDED US IN TXTEMAIL 
                                        'IS DIFFERENT FROM CONTACT EMAIL IN OSS.
                                        '##########################################################################################
                                        If (Not String.IsNullOrEmpty(txtEmail.Text) AndAlso Not String.IsNullOrEmpty(_account.Person.ContactEmailAddress)) _
                                        AndAlso (txtEmail.Text.Trim() <> _account.Person.ContactEmailAddress.Trim()) Then
                                            _succeeded = AccountManager.Instance.ChangeContactEMailAddress(txtEmail.Text.Trim().ToLower())
                                            If _succeeded Then
                                                If sb.Length <= 0 Then
                                                    sb.Append("Your Contact Email address has been successfully updated.")
                                                Else
                                                    sb.Append("</br>Your Contact Email address has been successfully updated.")
                                                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.
                                                '##################################################################################
                                                ltrMessageOAS.ForeColor = Drawing.Color.Red
                                                Select Case True
                                                    Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                                        sb.Append("" & AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                                        AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                                    Case Else
                                                        sb.Append("Failed to save Contact Email. ")
                                                End Select
                                            End If
                                        Else
                                            '#######################################################################################
                                            'THE USE IS TRYING TO CHANGE THE CONTACT EMAIL TO THE SAME ADDRESS AS WHAT IS ON FILE, 
                                            'NO NEED TO MAKE THE WEBSERVICE CALL.
                                            '#######################################################################################
                                            If sb.Length <= 0 Then
                                                lblErrorOAS.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " No change entered for Contact Email. Please update Contact Email and then click Save.<br/><br/>" & "</div>"
                                                lblErrorOAS.Visible = True
                                            End If

                                        End If
                                    End If
                                End If
                            End If
                        End If
                    Else
                        lblErrorOAS.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " No change entered. Please update the fields you would like to change and then click Save.<br/><br/>" & "</div>"
                        lblErrorOAS.Visible = True
                    End If
                End If
            End If

            If sb.Length > 0 Then
                If _succeeded Then
                    ltrMessageOAS.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/sup_icon_successChange.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
                    SetAsUpdatePageDefault()
                Else
                    ltrMessageOAS.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
                End If
            Else
                ltrMessageOAS.Visible = False
            End If
        End If

        btnSaveOAS.Focus()

    End Sub

    Protected Sub lbViewCode_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbViewCode.Click

        Dim accountNumber As String
        Dim CPNISecuritycode As String
        Dim sb As StringBuilder
        'Retrieve the account from session only at first click of the view
        'subsequently user just want to toggle between Hide code and View Code
        If Not (lbViewCode.Text.Trim.ToUpper.Contains("VIEW")) Then
            ToggleFields()
            Return
        End If

        sb = New StringBuilder()
        Dim _account As IAccount = AccountManager.Instance.GetAccount()
        Dim CSGcustomerID As String
        If Not _account Is Nothing Then
            'check if the Security code is already available for this account
            'fetch only if it is not available. This avoids unnecessary calls to web service
            'if the user clicks on View or Change code
            If _account.CPNISecurityCode Is Nothing Then

                'if the customerID is available pass to the backend to get
                'CPNI security code
                'if the customerID or AccountNumber is NOthing, this would be
                'caught during the login sequence and it will set the panel to pnlCustomerIDAvailable
                'we don't need to do any thing here.
                If Not (_account.CSGcustomerID Is Nothing) Then
                    CSGcustomerID = _account.CSGcustomerID
                    If Not (_account.OSSProvidedAccountNumber Is Nothing) Then
                        accountNumber = _account.OSSProvidedAccountNumber
                        CPNISecuritycode = AccountManager.Instance.GetCPNISecurityCode(accountNumber, CSGcustomerID)
                        'display security code and show the update fields
                        If Not (CPNISecuritycode Is Nothing) Then
                            lblSecurityCode.Text = CPNISecuritycode
                            ToggleFields()
                        Else
                            ltrMessageCode.ForeColor = Drawing.Color.Red
                            Select Case True
                                Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                    sb.Append("" & AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                    AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                Case Else
                                    sb.Append("Failed to retrieve  Security Code.")
                            End Select

                        End If
                    Else
                        sb.Append("Failed to retrieve user account number and Security Code. ")
                    End If
                Else
                    sb.Append("Unable to retrieve your security code at this time.  Please call 1-888-438-2427 to update your security code.")
                End If

                'If getCPNISecurityCode fails, set the error messages with appropriate value
                If sb.Length > 0 Then
                    ltrMessageCode.ForeColor = Drawing.Color.Red
                    ltrMessageCode.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
                    Me.pnlSecuritycodeIntro.Visible = True
                    Me.ltrMessageCode.Visible = True
                End If
            Else
                'just fetch the value from session and display the value
                'display security code and show the update fields
                lblSecurityCode.Text = _account.CPNISecurityCode
                ToggleFields()
            End If
        End If
    End Sub

    Private Sub ToggleFields()
        'This procedure is toggles between View and Hide
        'if View code is clicked, it alters it to hide code
        If lbViewCode.Text.ToUpper.Contains("VIEW") Then
            lbViewCode.Text = "Hide Code"
            Me.pnlNewcode.Visible = True
            Me.tdlblSC.InnerHtml = "<font color='red'>*</font>Security Code&nbsp;"
            Me.lnkCMS.Visible = False
            Me.spnrequired.Visible = True

        ElseIf lbViewCode.Text.ToUpper.Contains("HIDE") Then
            lbViewCode.Text = "View Code"
            Me.tdlblSC.InnerHtml = "<font color='red'>*</font>Security Code&nbsp;"
            lblSecurityCode.Text = "****"
            Me.lnkCMS.Visible = False
        End If
    End Sub

    Protected Sub btnSaveCode_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSaveCode.Click
        Dim _account As IAccount = AccountManager.Instance.GetAccount()
        Dim CSGcustomerID As String
        Dim accountNumber As String
        Dim CPNISecuritycodeUpdate As Boolean

        Dim _succeeded As Boolean
        Dim sb As StringBuilder

        'Retrieve the account from session
        ltrMessageCode.Text = ""
        ltrMessageCode.ForeColor = Drawing.Color.Black

        lblErrorCode.Text = ""

        If Not (Page.IsValid) Then
            Return
        End If

        _account = AccountManager.Instance.GetAccount()

        _succeeded = False
        sb = New StringBuilder()

        ''if nothing entered prompt with error message

        If Not (Me.txtNewCode.Text.Trim = String.Empty AndAlso Me.txtRetypeNewCode.Text.Trim = String.Empty) Then
            'validate security code here
            '####################################################################
            'Check the length  of security code .
            'check if the numbers in the security are sequential
            'check if the numbers are all the same
            'any of this check fails, exit and pass the error message to error summary
            '####################################################################
            Dim validationCheck As Boolean = False
            If ValidateSecurityCodeLength(Me.txtNewCode.Text.Trim) Then
                If ValidateSecurityCodeSequence(Me.txtNewCode.Text.Trim) Then
                    If ValidateSecurityCodePattern(Me.txtNewCode.Text.Trim) Then
                        validationCheck = True
                    Else
                        'all numbers in code are the same number 
                        sb.Append("Security Code must be exactly 4 digits and can not be the same number.<br/>")

                    End If
                Else
                    'number is sequential
                    sb.Append("Security Code must be exactly 4 digits and can not be sequential.<br/>")

                End If
            Else
                'length is smaller
                sb.Append("Security Code must be exactly 4 digits with no special characters and no alpha.<br/>")
            End If

            'if the security code passed the checks
            'Do same check for REtyped Security code value
            If validationCheck = True Then
                If ValidateSecurityCodeLength(Me.txtRetypeNewCode.Text.Trim) Then
                    If ValidateSecurityCodeSequence(Me.txtRetypeNewCode.Text.Trim) Then
                        If ValidateSecurityCodePattern(Me.txtRetypeNewCode.Text.Trim) Then
                        Else
                            'all numbers in code are the same number 
                            sb.Append("Retype Security Code must be exactly 4 digits and can not be the same number.<br/>")
                        End If

                    Else
                        'number is sequential
                        sb.Append("Retype Security Code must be exactly 4 digits and can not be sequential.<br/>")
                    End If
                Else
                    'length is smaller
                    sb.Append("Security Code must be exactly 4 digits with no special characters and no alpha.<br/>")
                End If
            End If

            ''if both security codes passed the check 
            'update
            If validationCheck = True Then
                'if every thing checks update the code
                If Not _account Is Nothing Then
                    'if the customerID is available pass to the backend to get
                    'CPNI security code
                    '####################################################################
                    'CHECK THAT CSG customerID  HAS A VALUE.
                    '####################################################################
                    If Not (_account.CSGcustomerID Is Nothing) Then
                        CSGcustomerID = _account.CSGcustomerID
                        If Not (_account.OSSProvidedAccountNumber Is Nothing) Then
                            accountNumber = _account.OSSProvidedAccountNumber
                            CPNISecuritycodeUpdate = AccountManager.Instance.UpdateCPNISecurityCode(accountNumber, CSGcustomerID, txtNewCode.Text.Trim())
                            'display security code and show the update fields
                            If CPNISecuritycodeUpdate Then
                                lblSecurityCode.Text = txtNewCode.Text.Trim()
                                lbViewCode.Text = "Hide Code"
                                sb.Append(" Your Security code has been successfully updated.")
                            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.
                                '##################################################################################
                                ltrMessageCode.ForeColor = Drawing.Color.Red
                                Select Case True
                                    Case Not AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage Is Nothing
                                        sb.Append("" & AccountManager.Instance.GetLastCCOMDisplayFriendlyExceptionMessage & " ")
                                        AccountManager.Instance.ClearCCOMDisplayFriendlyExceptionMessage()
                                    Case Else
                                        sb.Append("Failed to save New Security Code.")
                                End Select
                            End If
                        Else
                            ltrMessageCode.ForeColor = Drawing.Color.Red
                            sb.Append("Failed to retrieve account number.")
                        End If
                    End If
                End If
            End If
        Else
            Me.lblErrorCode.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & " No change were made to your Security Code.<br/><br/>" & "</div>"
            Me.lblErrorCode.Visible = True
        End If

        If sb.Length > 0 Then
            If CPNISecuritycodeUpdate Then
                ltrMessageCode.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/sup_icon_successChange.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
                Me.pnlNewcode.Visible = True
            Else
                ltrMessageCode.ForeColor = Drawing.Color.Red
                ltrMessageCode.Text = "<div class=""ValidationSummary"">" & "<img src='../Images/error-icon_small.ccom' /> " & String.Format("{0}", sb.ToString()) & "</div>"
                Me.txtNewCode.Focus()
            End If
            Me.pnlSecuritycodeIntro.Visible = True
            Me.ltrMessageCode.Visible = True
        Else
            Me.ltrMessageCode.Visible = False
        End If

    End Sub

    Private Function ValidateSecurityCodeLength(ByVal strTemp As String) As Boolean
        If strTemp IsNot Nothing AndAlso strTemp.Trim().Length = 4 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Function ValidateSecurityCodePattern(ByVal strTemp As String) As Boolean
        '#####################
        'This method is to check if numbers are same like 1111 or 2222 etc
        '#############################

        If strTemp IsNot Nothing Then
            'check if all of the 4 numbers are the same
            If CInt(strTemp.Substring(0, 1)) = CInt(strTemp.Substring(1, 1)) AndAlso _
                CInt(strTemp.Substring(1, 1)) = CInt(strTemp.Substring(2, 1)) AndAlso _
                CInt(strTemp.Substring(2, 1)) = CInt(strTemp.Substring(3, 1)) Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If

    End Function

    Private Function ValidateSecurityCodeSequence(ByVal strTemp As String) As Boolean
        '#####################
        'This method is to check if numbers are sequential, ascending or descending
        '#############################

        If strTemp IsNot Nothing Then
            'check first if first number is greater than second one
            'if so, check for descending order
            'if not check for ascending order
            If CInt(strTemp.Substring(0, 1)) > CInt(strTemp.Substring(1, 1)) Then
                If CInt(strTemp.Substring(0, 1)) - 1 = CInt(strTemp.Substring(1, 1)) AndAlso _
                CInt(strTemp.Substring(1, 1)) - 1 = CInt(strTemp.Substring(2, 1)) AndAlso _
                CInt(strTemp.Substring(2, 1)) - 1 = CInt(strTemp.Substring(3, 1)) Then
                    Return False
                Else
                    Return True
                End If
            Else
                If CInt(strTemp.Substring(0, 1)) + 1 = CInt(strTemp.Substring(1, 1)) AndAlso _
               CInt(strTemp.Substring(1, 1)) + 1 = CInt(strTemp.Substring(2, 1)) AndAlso _
               CInt(strTemp.Substring(2, 1)) + 1 = CInt(strTemp.Substring(3, 1)) Then
                    Return False
                Else
                    Return True
                End If
            End If
        Else
            Return True
        End If

    End Function

    Protected Sub btnResetCode_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnResetCode.Click
        lbViewCode.Text = "View Code"
        Me.pnlNewcode.Visible = True
        Me.tdlblSC.InnerHtml = "<font color='red'>*</font>Security Code&nbsp;"
        Me.lblSecurityCode.Text = "****"
        Me.spnrequired.Visible = True
        Me.txtNewCode.Text = ""
        Me.txtRetypeNewCode.Text = ""
        Me.lblErrorCode.Text = ""
        Me.ltrMessageCode.Text = ""
    End Sub

    Protected Sub btnResetOAS_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnResetOAS.Click
        Dim _account As IAccount = AccountManager.Instance.GetAccount()

        '#######################################################
        'ROD COPELAND   ISSUE ID 9647   8/3/2010
        'RESET THE OTHER ACCOUNT SETTINGS SECTION OF THE PAGE.
        '#######################################################
        If _account IsNot Nothing Then
            ddlQuestion.SelectedIndex = 0
            txtAnswer.Text = ""
            txtEmail.Text = ""
            If Not String.IsNullOrEmpty(_account.SecurityQuestion) Then
                ddlQuestion.SelectedValue = _account.SecurityQuestion
            End If

            If Not String.IsNullOrEmpty(_account.SecurityAnswer) Then
                txtAnswer.Text = _account.SecurityAnswer
            End If

            If _account.Person IsNot Nothing AndAlso Not String.IsNullOrEmpty(_account.Person.ContactEmailAddress) Then
                txtEmail.Text = _account.Person.ContactEmailAddress
            End If
        End If

        btnSaveOAS.Focus()
    End Sub
End Class