Imports CAMS_ADMIN
Imports CAMS_BL
Imports System.Data
Imports System.Text

Public Class frmGrantOffices
    Inherits CAMSBasePage

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object
    Protected WithEvents txtGrantOffice As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtAbbrev As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtAddress As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPostcode As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnDelete As System.Web.UI.WebControls.Button
    Protected WithEvents hdAction As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents pnlTA As System.Web.UI.WebControls.Panel
    Protected WithEvents pnlHA As System.Web.UI.WebControls.Panel
    Protected WithEvents dlTA As System.Web.UI.WebControls.DataList
    Protected WithEvents dlHA As System.Web.UI.WebControls.DataList
    Protected WithEvents lblMsgTA As System.Web.UI.WebControls.Label
    Protected WithEvents lblMsgHA As System.Web.UI.WebControls.Label
    Protected WithEvents lblTotalRecords As System.Web.UI.WebControls.Label
    Protected WithEvents dgResults As System.Web.UI.WebControls.DataGrid
    Protected WithEvents PagingBar1 As PACNET.WebControls.PagingBar
    Protected WithEvents pnlResults As System.Web.UI.WebControls.Panel
    Protected WithEvents lblMsgNoResults As System.Web.UI.WebControls.Label
    Protected WithEvents pnlNoResults As System.Web.UI.WebControls.Panel
    Protected WithEvents lblValAbbrev As System.Web.UI.WebControls.Label
    Protected WithEvents hdRowId As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hdEvent As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents lblTotalPages As System.Web.UI.WebControls.Label
    Protected WithEvents txtRecordsPerPage As System.Web.UI.WebControls.TextBox
    Protected WithEvents imgBtnRefresh As System.Web.UI.WebControls.ImageButton
    Protected WithEvents mnuCams As Menu

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Const FIRST_PAGE As Integer = 1

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Access Validation to page
        If Not Me.IsPostBack Then
            Dim oEC_User As EC_User = Me.GetUserFromSession

            If Not oEC_User Is Nothing Then
                If Me.HasAccessTo(Me.GetControlID("frmGrantOffices.aspx"), oEC_User.AccessGroup) = False Then
                    Me.RedirectToMsgPage(Constants.CONST_ERROR_ACCESSDENIED_TOPAGE)
                End If
            End If

        End If
        'End Access Validation

        'Menu
        mnuCams.CurrentGroup = Constants.MENU_MAINTENANCE_ID
        mnuCams.CurrentItem = Constants.MENU_MAINTENANCE_GRANTOFFICE_ID
        'End menu

        'Attributes for some controls
        txtRecordsPerPage.Attributes.Add("onKeyPress", "fnOnlyDigits(event,'decNo')")
        lblValAbbrev.Visible = False

        If txtRecordsPerPage.Text.Trim.Equals(String.Empty) OrElse Convert.ToInt32(txtRecordsPerPage.Text) < 1 Then
            txtRecordsPerPage.Text = "100"
        End If
        'End attributes

        'Initial values
        If Not Me.IsPostBack Then
            LoadHA()
            LoadTA()
            hdAction.Value = "I" 'setting as default action, I = Insert
            RefreshResults(FIRST_PAGE, txtRecordsPerPage.Text)
        End If
        'End Initial values

        'Postback
        If IsPostBack Then
            If hdEvent.Value = "save" Then
                Save()
            ElseIf hdEvent.Value = "selrow" Then
                SelectRow(Convert.ToInt32(hdRowId.Value))
                ShowItem(Convert.ToInt32(hdRowId.Value))
            ElseIf hdEvent.Value = "cancel" Then
                SetCancel()
            ElseIf hdEvent.Value = "add" Then
                btnAdd_Click()
            End If

        End If
        'End postback

        'Added by Raul Callupe
        If Me.IsPostBack = False Then
            Dim stbOutput As New StringBuilder
            stbOutput.Append("<script language='Javascript'>")
            stbOutput.Append("var pag = window.parent.frames(0);")
            stbOutput.Append("pag.document.all.lblPath.innerHTML='Maintenance/Grant Offices'")
            stbOutput.Append("</script>")
            Response.Write(stbOutput.ToString)
        End If
        'End Added

    End Sub

#Region "Refresh datagrid"

    Private Sub setNoRecordsFounds(ByVal bValue As Boolean)
        pnlNoResults.Visible = bValue
        pnlResults.Visible = Not bValue
    End Sub

    Private Sub RefreshResults(ByVal nPage As Integer, ByVal nRecordsPerPage As Integer)
        Dim oCC_GrantOffice As New CC_GrantOffice
        Dim dsResults As DataSet

        Try
            dsResults = oCC_GrantOffice.GetGrantOffices(nPage, txtRecordsPerPage.Text)

            If Not dsResults Is Nothing Then
                If dsResults.Tables(0).Rows.Count = 0 Then
                    setNoRecordsFounds(True)
                ElseIf dsResults.Tables(0).Rows(0)("record_count") < Convert.ToInt32(txtRecordsPerPage.Text) Then
                    PagingBar1.TotalNPages = FIRST_PAGE
                Else
                    Dim dDec = dsResults.Tables(0).Rows(0)("record_count") / Convert.ToInt32(txtRecordsPerPage.Text)
                    Dim nEnt = Decimal.Round(dDec, 0)
                    Dim nPages As Integer

                    If dDec > nEnt Then
                        nPages = nEnt + 1
                    Else
                        nPages = nEnt
                    End If
                    PagingBar1.TotalNPages = nPages
                End If

                If dsResults.Tables(0).Rows.Count > 0 Then
                    dgResults.CurrentPageIndex = 0
                    dgResults.DataSource = dsResults
                    dgResults.DataBind()

                    PagingBar1.PagesDisplayed = Convert.ToInt32(txtRecordsPerPage.Text)
                    PagingBar1.CurrentPage = nPage
                    lblTotalRecords.Text = dsResults.Tables(0).Rows(0)("record_count").ToString()
                    lblTotalPages.Text = PagingBar1.TotalNPages

                    setNoRecordsFounds(False)
                Else
                    setNoRecordsFounds(True)
                End If
            Else
                setNoRecordsFounds(True)
            End If

        Catch ex As Exception
            dsResults = Nothing
            setNoRecordsFounds(True)
        End Try

    End Sub

#End Region

#Region "Loading housing and technical Advisors"

    'Technical Advisor
    Private Sub LoadTA()
        Dim oCC_User As New CC_User
        Dim dsTA As DataSet

        Try
            dsTA = oCC_User.GetUsersByAccessGroup(Constants.CONST_ACCESSGROUP_TA)

            If Not dsTA Is Nothing Then

                If dsTA.Tables(0).Rows.Count > 0 Then
                    dlTA.DataSource = dsTA
                    dlTA.DataBind()
                Else
                    dlTA.Visible = False
                    lblMsgTA.Visible = True
                    lblMsgTA.Text = "No Technical Advisors available"
                End If

            End If

        Catch ex As Exception
            dlTA.Visible = False
            lblMsgTA.Visible = True
            lblMsgTA.Text = "It could not load list of technical advisors."
        End Try

    End Sub

    'Housing Advisor
    Private Sub LoadHA()
        Dim oCC_User As New CC_User
        Dim dsHA As DataSet

        Try
            dsHA = oCC_User.GetUsersByAccessGroup(Constants.CONST_ACCESSGROUP_HA)

            If Not dsHA Is Nothing Then

                If dsHA.Tables(0).Rows.Count > 0 Then
                    dlHA.DataSource = dsHA
                    dlHA.DataBind()
                Else
                    dlHA.Visible = False
                    lblMsgHA.Visible = True
                    lblMsgHA.Text = "No Housing Advisors available"
                End If

            End If

        Catch ex As Exception
            dlHA.Visible = False
            lblMsgHA.Visible = True
            lblMsgHA.Text = "It could not load list of housing advisors."
        End Try

    End Sub

    Private Sub dlTA_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlTA.ItemDataBound
        Dim chk As CheckBox = CType(e.Item.FindControl("chkTA"), CheckBox)
        Dim hdID As HtmlInputHidden = CType(e.Item.FindControl("hdTAID"), HtmlInputHidden)
        Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)

        If Not chk Is Nothing And Not hdID Is Nothing Then
            If Not drv Is Nothing Then
                hdID.Value = drv("USERID")
                chk.Text = drv("FULLNAME")
            End If
        End If

    End Sub

    Private Sub dlHA_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlHA.ItemDataBound
        Dim chk As CheckBox = CType(e.Item.FindControl("chkHA"), CheckBox)
        Dim hdID As HtmlInputHidden = CType(e.Item.FindControl("hdHAID"), HtmlInputHidden)
        Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)

        If Not chk Is Nothing Then
            If Not drv Is Nothing Then
                hdID.Value = drv("USERID")
                chk.Text = drv("FULLNAME")
            End If
        End If
    End Sub

#End Region

#Region "Controls' events"

    Private Sub btnAdd_Click()
        txtGrantOffice.Text = String.Empty
        txtAbbrev.Text = String.Empty
        txtPostcode.Text = String.Empty
        txtAddress.Text = String.Empty
        lblValAbbrev.Visible = False
        'setting actions
        hdEvent.Value = ""
        hdAction.Value = "I"
        hdRowId.Value = ""
        'Loading advisors
        LoadHA()
        LoadTA()
    End Sub

    Private Sub SetCancel()
        Me.RedirectToHome()
    End Sub

#End Region

#Region "Save"

    Private Sub Save()
        If hdAction.Value.Equals("I") Then
            Insert()
        ElseIf hdAction.Value.Equals("U") Then
            Update()
        ElseIf hdAction.Value.Equals("D") Then
            Delete()
        End If

    End Sub

    Private Sub Insert()
        Dim oEC_GO As EC_GrantOffice = SetProperties()
        Dim oCC_GO As New CC_GrantOffice
        Dim strMsg As String

        If Not oEC_GO Is Nothing Then
            If oCC_GO.SaveGrantOffice(oEC_GO, strMsg) Then
                Me.btnAdd_Click()
                RefreshResults(FIRST_PAGE, Convert.ToInt32(txtRecordsPerPage.Text))
            Else
                If strMsg = "EXISTS" Then
                    lblValAbbrev.Text = "Already exists in database"
                    lblValAbbrev.Visible = True
                End If
            End If

        End If

    End Sub

    Private Sub Update()
        Dim oEC_GO As EC_GrantOffice = SetProperties()
        Dim oCC_GO As New CC_GrantOffice
        Dim strMsg As String

        If Not oEC_GO Is Nothing Then
            If oCC_GO.UpdateGrantOffice(oEC_GO, strMsg) = False Then
                If strMsg = "NOEXISTS" Then
                    lblValAbbrev.Text = "Doesn't exist in database"
                    lblValAbbrev.Visible = True
                End If
            Else
                RefreshResults(FIRST_PAGE, Convert.ToInt32(txtRecordsPerPage.Text))

                If hdRowId.Value.Trim.Equals(String.Empty) = False Then
                    SelectRow(Convert.ToInt32(hdRowId.Value))
                    ShowItem(Convert.ToInt32(hdRowId.Value))
                End If
            End If

        End If
    End Sub

    Private Sub Delete()
        Dim oEC_GO As EC_GrantOffice = SetProperties()
        Dim oCC_GO As New CC_GrantOffice
        Dim strMsg As String

        If Not oEC_GO Is Nothing Then
            If oCC_GO.DeleteGrantOffice(oEC_GO, strMsg) Then
                Me.btnAdd_Click()
                RefreshResults(FIRST_PAGE, Convert.ToInt32(txtRecordsPerPage.Text))
            Else
                If strMsg = "NOEXISTS" Then
                    lblValAbbrev.Text = "Doesn't exist in database"
                    lblValAbbrev.Visible = True
                End If
            End If

        End If
    End Sub

    Private Function SetProperties() As EC_GrantOffice
        Dim oEC_GO As New EC_GrantOffice
        Dim oEC_Advisors() As EC_GrantOffice_Advisor = SetPropertiesAdvisors()
        Dim oEC_User As EC_User = Me.GetUserFromSession

        With oEC_GO
            .GrantOfficeID = txtAbbrev.Text.Trim.ToUpper
            .Name = txtGrantOffice.Text.Trim.ToUpper
            .Address = txtAddress.Text.Trim
            .Postcode = txtPostcode.Text.Trim.ToUpper
            .Advisors = oEC_Advisors

            If Not oEC_User Is Nothing Then
                .AddedBy = oEC_User.Login
                .ChangedBy = oEC_User.Login
            End If
        End With

        Return oEC_GO

    End Function

    Private Function SetPropertiesAdvisors() As EC_GrantOffice_Advisor()
        Dim oEC_Advisors() As EC_GrantOffice_Advisor

        Dim chk As CheckBox
        Dim hdID As HtmlInputHidden

        For i As Integer = 0 To dlHA.Items.Count - 1
            chk = CType(dlHA.Items(i).FindControl("chkHA"), CheckBox)
            hdID = CType(dlHA.Items(i).FindControl("hdHAID"), HtmlInputHidden)

            If Not chk Is Nothing Then
                If chk.Checked Then
                    If oEC_Advisors Is Nothing Then
                        ReDim Preserve oEC_Advisors(0)
                        oEC_Advisors(0) = New EC_GrantOffice_Advisor
                    Else
                        ReDim Preserve oEC_Advisors(oEC_Advisors.Length)
                        oEC_Advisors(oEC_Advisors.Length - 1) = New EC_GrantOffice_Advisor
                    End If

                    If Not oEC_Advisors Is Nothing AndAlso Not oEC_Advisors.Length = 0 Then
                        oEC_Advisors(oEC_Advisors.GetUpperBound(0)).UserID = hdID.Value.Trim
                        oEC_Advisors(oEC_Advisors.GetUpperBound(0)).AccessGroup = Constants.CONST_ACCESSGROUP_HA
                    End If
                End If

            End If

        Next

        For i As Integer = 0 To dlTA.Items.Count - 1
            chk = CType(dlTA.Items(i).FindControl("chkTA"), CheckBox)
            hdID = CType(dlTA.Items(i).FindControl("hdTAID"), HtmlInputHidden)

            If Not chk Is Nothing Then
                If chk.Checked Then
                    If oEC_Advisors Is Nothing Then
                        ReDim Preserve oEC_Advisors(0)
                        oEC_Advisors(0) = New EC_GrantOffice_Advisor
                    Else
                        ReDim Preserve oEC_Advisors(oEC_Advisors.Length)
                        oEC_Advisors(oEC_Advisors.Length - 1) = New EC_GrantOffice_Advisor
                    End If

                    If Not oEC_Advisors Is Nothing AndAlso Not oEC_Advisors.Length = 0 Then
                        oEC_Advisors(oEC_Advisors.GetUpperBound(0)).UserID = hdID.Value.Trim
                        oEC_Advisors(oEC_Advisors.GetUpperBound(0)).AccessGroup = Constants.CONST_ACCESSGROUP_TA
                    End If
                End If

            End If

        Next

        Return oEC_Advisors
    End Function

#End Region

#Region "Common methods"

    Private Sub dgResults_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgResults.ItemDataBound
        If e.Item.ItemType <> ListItemType.Header Then
            e.Item.Cells(0).Text = "<a href=""#"" onclick=""fnSelRow(" & e.Item.ItemIndex.ToString & ")""><img src=""../images/view.gif"" border=0></a>"
        End If

    End Sub

    Private Sub SelectRow(ByVal rowID As Integer)

        Try
            If dgResults.Items.Count > 0 Then
                'Setting the action as an updating
                hdAction.Value = "U"

                For i As Integer = 0 To dgResults.Items.Count - 1
                    If i Mod 2 = 0 Then
                        dgResults.Items(i).CssClass = "PAGE_GRID_ITEM"
                    Else
                        dgResults.Items(i).CssClass = "PAGE_GRID_ALTERNATING"
                    End If
                Next

                dgResults.Items(rowID).CssClass = "PAGE_GRID_ITEM_SELECTED"
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub ShowItem(ByVal rowID As Integer)
        Dim strItemID As String

        Try
            If dgResults.Items.Count > 0 Then

                strItemID = dgResults.Items(rowID).Cells(2).Text.Trim

                If strItemID.Equals(String.Empty) = False Then
                    LoadItem(strItemID)
                End If
            End If
        Catch ex As Exception

        End Try

    End Sub

    'load grant office
    Private Sub LoadItem(ByVal goID As String)
        Dim oCC_GO As New CC_GrantOffice
        Dim oEC_GO As EC_GrantOffice = oCC_GO.GetGrantOfficeByID(goID)

        If Not oEC_GO Is Nothing Then
            With oEC_GO
                txtGrantOffice.Text = .Name
                txtAbbrev.Text = .GrantOfficeID
                txtAddress.Text = .Address
                txtPostcode.Text = .Postcode
                SelectCheckboxes(.Advisors)
            End With
        End If
    End Sub

    Private Sub SelectCheckboxes(ByVal oEC_Advisors() As EC_GrantOffice_Advisor)
        'Getting advisors
        LoadHA()
        LoadTA()

        If oEC_Advisors Is Nothing Then Exit Sub

        Dim chk As CheckBox
        Dim hdID As HtmlInputHidden

        'Housing advisor
        For i As Integer = 0 To dlHA.Items.Count - 1
            chk = CType(dlHA.Items(i).FindControl("chkHA"), CheckBox)
            hdID = CType(dlHA.Items(i).FindControl("hdHAID"), HtmlInputHidden)

            If Not chk Is Nothing AndAlso Not hdID Is Nothing Then
                For j As Integer = 0 To oEC_Advisors.Length - 1
                    If oEC_Advisors(j).UserID = hdID.Value Then
                        chk.Checked = True
                        Exit For
                    End If
                Next
            End If

        Next

        'Technical advisor
        For i As Integer = 0 To dlTA.Items.Count - 1
            chk = CType(dlTA.Items(i).FindControl("chkTA"), CheckBox)
            hdID = CType(dlTA.Items(i).FindControl("hdTAID"), HtmlInputHidden)

            If Not chk Is Nothing AndAlso Not hdID Is Nothing Then
                For j As Integer = 0 To oEC_Advisors.Length - 1
                    If oEC_Advisors(j).UserID = hdID.Value Then
                        chk.Checked = True
                        Exit For
                    End If
                Next
            End If

        Next

    End Sub

#End Region

#Region "Pagination"

    Private Sub txtRecordsPerPage_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtRecordsPerPage.TextChanged
        PagingBar1.CurrentPage = FIRST_PAGE
        PagingBar1.TotalNPages = FIRST_PAGE
        PagingBar1.PagesDisplayed = txtRecordsPerPage.Text
        RefreshResults(FIRST_PAGE, txtRecordsPerPage.Text)
    End Sub

    Private Sub PagingBar1_ChangePage(ByVal sender As Object, ByVal e As PACNET.WebControls.ChangePageEventArgs) Handles PagingBar1.ChangePage
        RefreshResults(e.SelectedPage, txtRecordsPerPage.Text)
    End Sub

#End Region

End Class

