'Option Explicit On 
'Option Strict On

Imports System.Data
Imports System.Data.SqlClient

Public Class MgrLinks1
    Inherits System.Web.UI.Page
    Protected WithEvents DA_ChildLinks As System.Data.SqlClient.SqlDataAdapter
    Protected WithEvents DsViewChildPages1 As AllSaints.dsViewChildPages
    Protected WithEvents cmdGetChildPages As System.Data.SqlClient.SqlCommand
    Protected WithEvents DG_Links As System.Web.UI.WebControls.DataGrid
    Protected WithEvents pnlError As System.Web.UI.WebControls.Panel
    Protected WithEvents lblError As System.Web.UI.WebControls.Label
    Protected WithEvents delselected As System.Web.UI.WebControls.Button
    Protected WithEvents A1 As System.Web.UI.HtmlControls.HtmlAnchor
    Protected WithEvents SqlConn As System.Data.SqlClient.SqlConnection
    Dim resetBtnScriptCb As String
    Protected WithEvents DsViewChildPagesS1 As AllSaints.dsViewChildPagesS
    Dim resetBtnScriptCb1 As String
    Dim PageID As Integer
    Protected WithEvents DsViewChildPagesS2 As AllSaints.dsViewChildPagesS
    Dim PageDT As DataTable

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.DA_ChildLinks = New System.Data.SqlClient.SqlDataAdapter
Me.cmdGetChildPages = New System.Data.SqlClient.SqlCommand
Me.SqlConn = New System.Data.SqlClient.SqlConnection
Me.DsViewChildPages1 = New AllSaints.dsViewChildPages
Me.DsViewChildPagesS1 = New AllSaints.dsViewChildPagesS
Me.DsViewChildPagesS2 = New AllSaints.dsViewChildPagesS
CType(Me.DsViewChildPages1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.DsViewChildPagesS1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.DsViewChildPagesS2, System.ComponentModel.ISupportInitialize).BeginInit()
'
'DA_ChildLinks
'
Me.DA_ChildLinks.MissingSchemaAction = System.Data.MissingSchemaAction.Error
Me.DA_ChildLinks.SelectCommand = Me.cmdGetChildPages
Me.DA_ChildLinks.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "GetChildPages", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("ID", "ID"), New System.Data.Common.DataColumnMapping("PageName", "PageName"), New System.Data.Common.DataColumnMapping("Body", "Body"), New System.Data.Common.DataColumnMapping("BodyHeading", "BodyHeading"), New System.Data.Common.DataColumnMapping("TopPicture", "TopPicture"), New System.Data.Common.DataColumnMapping("RightPicture", "RightPicture"), New System.Data.Common.DataColumnMapping("ParentID", "ParentID"), New System.Data.Common.DataColumnMapping("RightPicDesc", "RightPicDesc"), New System.Data.Common.DataColumnMapping("PageType", "PageType"), New System.Data.Common.DataColumnMapping("CanDelete", "CanDelete")})})
'
'cmdGetChildPages
'
Me.cmdGetChildPages.CommandText = "[GetChildPages]"
Me.cmdGetChildPages.CommandType = System.Data.CommandType.StoredProcedure
Me.cmdGetChildPages.Connection = Me.SqlConn
Me.cmdGetChildPages.Parameters.Add(New System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, False, CType(10, Byte), CType(0, Byte), "", System.Data.DataRowVersion.Current, Nothing))
Me.cmdGetChildPages.Parameters.Add(New System.Data.SqlClient.SqlParameter("@PageID", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, False, CType(10, Byte), CType(0, Byte), "", System.Data.DataRowVersion.Current, Nothing))
'
'SqlConn
'
Me.SqlConn.ConnectionString = "data source=localhost;initial catalog=Online_allsaints;persist security info=Fals" & _
"e;user id=sa;workstation id=GALAXY;packet size=4096"
'
'DsViewChildPages1
'
Me.DsViewChildPages1.DataSetName = "dsViewChildPages"
Me.DsViewChildPages1.Locale = New System.Globalization.CultureInfo("en-US")
'
'DsViewChildPagesS1
'
Me.DsViewChildPagesS1.DataSetName = "dsViewChildPagesS"
Me.DsViewChildPagesS1.Locale = New System.Globalization.CultureInfo("en-US")
'
'DsViewChildPagesS2
'
Me.DsViewChildPagesS2.DataSetName = "dsViewChildPagesS"
Me.DsViewChildPagesS2.Locale = New System.Globalization.CultureInfo("en-US")
CType(Me.DsViewChildPages1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.DsViewChildPagesS1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.DsViewChildPagesS2, System.ComponentModel.ISupportInitialize).EndInit()

    End Sub

    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()
        If SqlConn.State = ConnectionState.Closed Then SqlConn.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If SqlConn.State = ConnectionState.Closed Then SqlConn.ConnectionString = ConfigurationSettings.AppSettings("sConnection")

        'store the page id in viewstate as to reterive it in page postbacks

        Dim str1 As String = Request("ID").ToString
        PageID = CType(Request("ID"), Integer)

        ViewState("PageID") = Request("ID").ToString

        Dim str2 As String = Request("ID").ToString

        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString

        Dim str3 As String = Request("ID").ToString

        DA_ChildLinks.Fill(DsViewChildPagesS2)
        PageDT = DsViewChildPagesS2.Tables(0)

        If Not Page.IsPostBack Then

            DA_ChildLinks.Fill(DsViewChildPagesS1)

            'Response.Write(DsViewChildPagesS1.Tables(0).Rows.Count)

            'Response.Write(DsViewChildPagesS1.Tables(0).Rows.Count)
            'Response.End()

            'Response.Write(DsViewChildPagesS1.Tables(0).Rows(0)("ID"))
            'Response.Write(DsViewChildPagesS1.Tables(0).Columns.Count)
            'Response.End()

            '<TESTLINES>
            DG_Links.DataSource = DsViewChildPagesS1.Tables(0)

            'Check column order
            SetDefaultColumnOrder(DsViewChildPagesS1.Tables(0))
            '</TESTLINES>
            'DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0))
            DG_Links.DataBind()
        End If

    End Sub

    Private Sub SetDefaultColumnOrder(ByVal Dt As DataTable)

        If Not (Dt Is Nothing) And Dt.Rows.Count > 0 And (Dt.Rows(0)("ColumnOrder") Is Nothing Or Dt.Rows(0)("ColumnOrder") = 0) Then
            Dim order As Integer
            order = 1
            For Each row As DataRow In Dt.Rows
                'row.Item("ColumnOrder")
                Try
                    Dim cmd As New SqlCommand
                    Dim query As String = ""

                    query = "update as_Pages set ColumnOrder=" & order & " where ID = " & CType(row.Item("ID"), Int32)

                    If (query <> "") Then
                        If SqlConn.State = ConnectionState.Closed Then
                            SqlConn.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
                        End If

                        With cmd
                            .CommandText = query
                            .CommandType = CommandType.Text
                            If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                            .Connection = SqlConn
                            .ExecuteNonQuery()
                        End With

                        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()

                    End If
                Catch ex As Exception
                    If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
                End Try
                order = order + 1
            Next row
        End If

    End Sub

    Private Sub UpdateUpColumnOrder(ByVal id As Integer)

        If Not (PageDT Is Nothing) And PageDT.Rows.Count > 0 Then

            Dim order As Integer
            Dim IDorder As Integer
            Dim IDOld As Integer
            Dim IDCurrent As Integer

            order = 1
            IDorder = 1
            IDCurrent = 1

            For Each row As DataRow In PageDT.Rows
                order = IDorder
                IDorder = CType(row.Item("ColumnOrder"), Integer)

                IDOld = IDCurrent
                IDCurrent = CType(row.Item("ID"), Integer)

                If IDCurrent = id Then
                    Exit For
                End If
            Next row

            'Response.Write(IDOld & " - ")
            'Response.Write(IDCurrent)

            If IDOld <> IDCurrent Then
                Try
                    Dim cmd As New SqlCommand
                    Dim query As String = ""

                    query = "update as_Pages set ColumnOrder=" & order & " where ID = " & IDCurrent & "; update as_Pages set ColumnOrder=" & IDorder & " where ID = " & IDOld

                    If (query <> "") Then
                        If SqlConn.State = ConnectionState.Closed Then
                            SqlConn.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
                        End If

                        With cmd
                            .CommandText = query
                            .CommandType = CommandType.Text
                            If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                            .Connection = SqlConn
                            .ExecuteNonQuery()
                        End With

                        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()

                    End If
                Catch ex As Exception
                    If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
                End Try

            End If

        End If

    End Sub

    Private Sub UpdateDownColumnOrder(ByVal id As Integer)

        If Not (PageDT Is Nothing) And PageDT.Rows.Count > 0 Then

            Dim order As Integer
            Dim orderNew As Integer
            Dim IDNew As Integer
            Dim IDCurrent As Integer

            orderNew = 1
            IDNew = 1

            For Each row As DataRow In PageDT.Rows

                order = orderNew
                orderNew = CType(row.Item("ColumnOrder"), Integer)

                IDCurrent = IDNew
                IDNew = CType(row.Item("ID"), Integer)

                If IDCurrent = id Then
                    Exit For
                End If

            Next row

            'Response.Write(IDOld & " - ")
            'Response.Write(IDCurrent)

            If IDNew <> id Then
                Try
                    Dim cmd As New SqlCommand
                    Dim query As String = ""

                    query = "update as_Pages set ColumnOrder=" & orderNew & " where ID = " & IDCurrent & "; update as_Pages set ColumnOrder=" & order & " where ID = " & IDNew

                    If (query <> "") Then
                        If SqlConn.State = ConnectionState.Closed Then
                            SqlConn.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
                        End If

                        With cmd
                            .CommandText = query
                            .CommandType = CommandType.Text
                            If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                            .Connection = SqlConn
                            .ExecuteNonQuery()
                        End With

                        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()

                    End If
                Catch ex As Exception
                    If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
                End Try

            End If

        End If

    End Sub

    Private Sub DG_Links_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DG_Links.ItemCreated

        If e.Item.ItemType = ListItemType.Pager Then
            If DsViewChildPagesS1.Tables(0).Rows.Count < DG_Links.PageSize Then
                e.Item.Visible = False
            End If
        End If

    End Sub
    Private Sub DG_Links_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DG_Links.ItemCommand

        Select Case e.CommandName.Trim
            Case "Insert"
                InserNewRow(source, e)
            Case "Delete"
                DeleteRow(source, e)
            Case "MoveUp"
                Dim cmd As New SqlCommand
                With cmd
                    .CommandText = "SELECT TOP 1 ID FROM(as_Pages) WHERE (ID<" & e.CommandArgument.ToString & ") AND (ParentID=" & ViewState("PageID").ToString & ")"
                    .CommandType = CommandType.Text
                    .Connection = SqlConn
                    If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                    Dim oRtn As Object = .ExecuteScalar()
                    If Not IsDBNull(oRtn) Then
                        Dim upPageID As Integer = CType(oRtn.ToString, Integer)
                        .CommandText = "SELECT TOP 1 ID FROM(as_Pages) WHERE (ID<" & e.CommandArgument.ToString & ") AND (ParentID=" & ViewState("PageID").ToString & ")"

                    End If
                End With
                DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
                DA_ChildLinks.Fill(DsViewChildPagesS1)
                Dim dv As DataView = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)

            Case "MoveDown"
                DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
                DA_ChildLinks.Fill(DsViewChildPagesS1)
                Dim dv As DataView = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
            Case "Up"
                UpdateUpColumnOrder(CType(e.CommandArgument, Integer))
                Response.Redirect(CType(Request.Url.AbsoluteUri, String))
            Case "Down"
                UpdateDownColumnOrder(CType(e.CommandArgument, Integer))
                Response.Redirect(CType(Request.Url.AbsoluteUri, String))

        End Select


        '<SAQIB ADDED LINES>
        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
        '<SAQIB ADDED LINES/>
    End Sub
    '******************************************************************************
    Private Sub DG_Links_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DG_Links.PageIndexChanged

        DG_Links.CurrentPageIndex = e.NewPageIndex
        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()

    End Sub
    '******************************************************************************
    Private Sub DG_Links_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DG_Links.SortCommand

        DG_Links.EditItemIndex = -1
        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        ViewState("SortBy") = e.SortExpression
        If CType(ViewState("Direction"), String) = "" Then
            ViewState("Direction") = " ASC "
        ElseIf CType(ViewState("Direction"), String).Trim = "ASC" Then
            ViewState("Direction") = " DESC "
        Else
            ViewState("Direction") = " ASC "
        End If
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", e.SortExpression & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()

    End Sub
    Private Sub delselected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delselected.Click

        Dim dgi As DataGridItem

        For Each dgi In DG_Links.Items

            If dgi.ItemType = ListItemType.Item Or dgi.ItemType = ListItemType.AlternatingItem Then

                Dim cb As CheckBox = CType(dgi.Cells(0).Controls(1), CheckBox)

                If cb.Checked Then

                    Dim cmd As New SqlCommand
                    With cmd
                        .Connection = SqlConn
                        .CommandType = CommandType.Text
                        .Connection = SqlConn
                        If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                        'if any child records exits then donot delete the parent
                        .CommandText = "Select count(*) from as_Pages where ParentID=" & CType(cb.ToolTip.ToString, Integer)
                        Try
                            Dim ChildCount As Object = .ExecuteScalar()
                            If Not IsDBNull(ChildCount) And CType(ChildCount.ToString, Integer) > 0 Then
                                pnlError.Visible = True
                                lblError.Text = "Some of the pages cannot be deleted, as they have one or more child page records!"
                                'donot delete this page as it has child records
                            Else
                                'delete the record now
                                .CommandText = "Delete from as_Pages where ID=" & CType(cb.ToolTip.ToString, Integer)
                                .ExecuteNonQuery()
                            End If
                        Catch ex As Exception
                            Dim sError As String = ""
                        End Try

                    End With
                End If
            End If
        Next

        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()

        '<SAQIB ADDED LINES>
        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
        '<SAQIB ADDED LINES/>

    End Sub
    Private Sub DG_Links_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DG_Links.EditCommand

        DG_Links.EditItemIndex = e.Item.ItemIndex
        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()
        DG_Links.ShowFooter = False

    End Sub
    Private Sub DG_Links_CancelCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DG_Links.CancelCommand

        DG_Links.EditItemIndex = -1
        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()
        DG_Links.ShowFooter = True
    End Sub
    Private Sub DG_Links_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DG_Links.UpdateCommand

        Dim cmd As New SqlCommand
        Dim id As Integer

        With cmd

            .Connection = SqlConn
            .CommandType = CommandType.Text
            .Connection = SqlConn
            If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
            Dim samewindow As Integer = 0
            If CType(e.Item.Cells(1).FindControl("chkNewWindow"), CheckBox).Checked = True Then
                samewindow = 1
            End If

            Dim includeMenu As Integer = 0
            If CType(e.Item.Cells(1).FindControl("chkNewMenu"), CheckBox).Checked = True Then
                includeMenu = 1
            End If

            Dim url As String = CType(e.Item.Cells(1).FindControl("txtEditURL"), TextBox).Text
            url = url.ToLower
            url = url.Replace("http://", "")
            If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
            .CommandText = "update as_pages set pagename='" & CType(e.Item.Cells(1).FindControl("txtLinkName"), TextBox).Text & _
                           "', url='" & url & _
                           "', external_link ='" & CType(e.Item.Cells(1).FindControl("drpType"), DropDownList).SelectedValue & _
                           "', samewindow ='" & samewindow & _
                           "', menuItem ='" & includeMenu & _
                           "' where id = " & Integer.Parse(DG_Links.DataKeys(e.Item.ItemIndex)) & ""
            .ExecuteNonQuery()
        End With

        DG_Links.EditItemIndex = -1
        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()
        '<SAQIB ADDED LINES>
        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
        '<SAQIB ADDED LINES/>
        DG_Links.ShowFooter = True

    End Sub

    Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload
        '<SAQIB ADDED LINES>
        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
        '<SAQIB ADDED LINES/>
    End Sub
    Private Sub InserNewRow(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
        Dim dg As DataGridItem

        Dim sPageName As String = CType(e.Item.FindControl("txtNewLinkName"), TextBox).Text
        Dim sUrl As String = CType(e.Item.FindControl("txtNewURL"), TextBox).Text
        Dim bNewWindow As Boolean = CType(e.Item.FindControl("chkWindow"), CheckBox).Checked

        Dim bNewMenu As Boolean = CType(e.Item.FindControl("chkMenu"), CheckBox).Checked

        Dim sType As String = CType(e.Item.FindControl("drpNewType"), DropDownList).SelectedValue
        sUrl = sUrl.ToLower
        sUrl = sUrl.Replace("http://", "")
        Dim cmd As New SqlCommand
        Dim eClassPages As Boolean = False
        Dim iPageID As Integer = CType(ViewState("PageID").ToString.Trim, Integer)

        If ((sUrl = "" Or sUrl = "Enter URL Here...") And sType = "External") Then
            Exit Sub
        End If
        If (sUrl = "") Then
            sUrl = "-"
        End If
        With cmd
            .CommandType = CommandType.Text
            .Connection = SqlConn
            'now check if the managing/adding new link is under the TeachereClassRooms
            'then set the eClassRooms=true as new link created will be an eClass
            Try
                If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                .CommandText = "select Count(*) from as_Pages where ParentID=" & iPageID & " and PageType='Class'"
                If CType(.ExecuteScalar(), Integer) > 0 Then eClassPages = True
            Catch ex As Exception
                eClassPages = False
            End Try

            .CommandText = "Insert into as_Pages (PageName,Body,BodyHeading,TopPicture,RightPicture,RightPicDesc,ParentID,PageType,CanDelete,URL,samewindow,external_link,menuitem,ColumnOrder) " & _
             " values(@PageName,@Body,@BodyHeading,@TopPicture,@RightPicture,@RightPicDesc,@ParentID,@PageType,@CanDelete,@url,@samewindow,@external_link,@menuitem,@colOrder)"
            .Parameters.Add("@PageName", SqlDbType.VarChar, 2048)
            .Parameters("@PageName").Value = sPageName

            .Parameters.Add("@Body", SqlDbType.Text)
            .Parameters("@Body").Value = ""

            .Parameters.Add("@BodyHeading", SqlDbType.VarChar, 2048)
            .Parameters("@BodyHeading").Value = ""

            .Parameters.Add("@TopPicture", SqlDbType.VarChar, 1024)
            .Parameters("@TopPicture").Value = ""

            .Parameters.Add("@RightPicture", SqlDbType.VarChar, 1024)
            .Parameters("@RightPicture").Value = ""

            .Parameters.Add("@RightPicDesc", SqlDbType.VarChar, 2048)
            .Parameters("@RightPicDesc").Value = ""

            .Parameters.Add("@ParentID", SqlDbType.Int, 4)
            .Parameters("@ParentID").Value = iPageID

            .Parameters.Add("@PageType", SqlDbType.VarChar, 50)
            If eClassPages Then
                .Parameters("@PageType").Value = "Class"
            Else
                .Parameters("@PageType").Value = "Page"
            End If

            .Parameters.Add("@CanDelete", SqlDbType.Bit)
            .Parameters("@CanDelete").Value = 1

            .Parameters.Add("@URL", SqlDbType.VarChar, 2048)
            .Parameters("@url").Value = sUrl

            .Parameters.Add("@samewindow", SqlDbType.Bit)
            .Parameters("@samewindow").Value = bNewWindow


            .Parameters.Add("@external_link", SqlDbType.VarChar, 50)
            .Parameters("@external_link").Value = sType

            .Parameters.Add("@menuitem", SqlDbType.Bit)
            .Parameters("@menuitem").Value = bNewMenu

            .Parameters.Add("@colOrder", SqlDbType.Int)
            .Parameters("@colOrder").Value = 0

            '<TEST LINES>
            Dim str As String = cmd.CommandText.ToString()
            '<TEST LINES>
            Try
                If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                .ExecuteNonQuery()
            Catch ex As Exception
                Response.Write(ex.ToString())
            End Try
        End With

        '*****************************************************
        '*****************************************************
        '*****************************************************
        '<START OF CODE ADDED/WRITTEN ON 4-02-2004 BY SAQIB>
        Dim er As String
        Dim chk As String
        Dim ch As Int32
        '<TEST LINES>
        If Session("Links") = "Top" Then

            With cmd
                .CommandType = CommandType.Text
                .Connection = SqlConn
                'now check if the managing/adding new link is under the TeachereClassRooms
                'then set the eClassRooms=true as new link created will be an eClass
                Try
                    If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                    .CommandText = "select Count(*) from as_Pages where ParentID=" & iPageID & " and PageType='Class'"
                    If CType(.ExecuteScalar(), Integer) > 0 Then eClassPages = True
                Catch ex As Exception
                    eClassPages = False
                End Try

                Try
                    If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                    .CommandText = "select MAX (ID) from as_Pages where ParentID = " & iPageID
                    ch = Convert.ToInt32(cmd.ExecuteScalar())

                Catch ex As Exception
                    er = ex.ToString()
                    eClassPages = False
                End Try

                .CommandText = "Insert into as_Pages (PageName,Body,BodyHeading,TopPicture,RightPicture,RightPicDesc,ParentID,PageType,CanDelete,URL,samewindow,external_link,menuitem) " & _
             " values(@PageName,@Body,@BodyHeading,@TopPicture,@RightPicture,@RightPicDesc,@ParentID,@PageType,@CanDelete,@url,@samewindow,@external_link,@menuitem)"
                .Parameters.Add("@PageName2", SqlDbType.VarChar, 2048)
                .Parameters("@PageName2").Value = "Overview"

                .Parameters.Add("@Body2", SqlDbType.Text)
                .Parameters("@Body2").Value = ""

                .Parameters.Add("@BodyHeading2", SqlDbType.VarChar, 2048)
                .Parameters("@BodyHeading2").Value = ""

                .Parameters.Add("@TopPicture2", SqlDbType.VarChar, 1024)
                .Parameters("@TopPicture2").Value = ""

                .Parameters.Add("@RightPicture2", SqlDbType.VarChar, 1024)
                .Parameters("@RightPicture2").Value = ""

                .Parameters.Add("@RightPicDesc2", SqlDbType.VarChar, 2048)
                .Parameters("@RightPicDesc2").Value = ""

                .Parameters.Add("@ParentID2", SqlDbType.Int, 4)
                .Parameters("@ParentID2").Value = ch

                .Parameters.Add("@PageType2", SqlDbType.VarChar, 50)
                If eClassPages Then
                    .Parameters("@PageType2").Value = "Class"
                Else
                    .Parameters("@PageType2").Value = "Page"
                End If

                .Parameters.Add("@CanDelete2", SqlDbType.Bit)
                .Parameters("@CanDelete2").Value = 1

                .Parameters.Add("@URL", SqlDbType.VarChar, 2048)
                .Parameters("@url").Value = sUrl

                .Parameters.Add("@samewindow", SqlDbType.Bit)
                .Parameters("@samewindow").Value = bNewWindow


                .Parameters.Add("@external_link", SqlDbType.VarChar, 50)
                .Parameters("@external_link").Value = sType

                .Parameters.Add("@menuitem", SqlDbType.Bit)
                .Parameters("@menuitem").Value = bNewMenu

                '<TEST LINES>
                Dim str As String = cmd.CommandText.ToString()
                '<TEST LINES>
                Try
                    If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()
                    .ExecuteNonQuery()
                Catch ex As Exception
                    str = ex.ToString()
                End Try
            End With


        End If
        '<TEST LINES>
        '*****************************************************
        '*****************************************************
        '*****************************************************
        '<END OF CODE ADDED/WRITTEN ON 4-02-2004 BY SAQIB>

        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()

        'txtaddnew.Text = ""
        'txtaddnew.Visible = False
        'txtURL.Text = "Enter URL Here..."
        'chkexternal.Visible = False
        'txtURL.Visible = False
        'createnew.Visible = True
        'externallink.Visible = True
        'delselected.Visible = True
        'btnsave.Visible = False
        'btncancel.Visible = False

        '<SAQIB ADDED LINES>
        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
        '<SAQIB ADDED LINES/>

    End Sub
    Private Sub DeleteRow(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
        Dim cmd As New SqlCommand
        Dim id As Integer

        With cmd

            .Connection = SqlConn
            .CommandType = CommandType.Text
            .Connection = SqlConn
            If SqlConn.State = ConnectionState.Closed Then SqlConn.Open()

            .CommandText = "delete from as_pages where id = " & Integer.Parse(DG_Links.DataKeys(e.Item.ItemIndex)) & ""
            .ExecuteNonQuery()
        End With

        DG_Links.EditItemIndex = -1
        DA_ChildLinks.SelectCommand.Parameters("@PageID").Value = ViewState("PageID").ToString
        DA_ChildLinks.Fill(DsViewChildPagesS1)
        DG_Links.DataSource = New DataView(DsViewChildPagesS1.Tables(0), "", CType(ViewState("SortBy"), String) & CType(ViewState("Direction"), String), DataViewRowState.CurrentRows)
        DG_Links.DataBind()
        '<SAQIB ADDED LINES>
        If SqlConn.State = ConnectionState.Open Then SqlConn.Close()
        '<SAQIB ADDED LINES/>
    End Sub
    Private Sub DG_Links_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DG_Links.ItemDataBound
        If (e.Item.ItemType = ListItemType.Footer) Then
            'Cells is Zero Based
            '1 is the column number where we want to add the hyperlink
            Dim drp As DropDownList = CType(e.Item.FindControl("drpNewType"), DropDownList)
            Dim txt As TextBox = CType(e.Item.FindControl("txtNewURL"), TextBox)
            Dim a As String = drp.ClientID
            Dim b As String = txt.ClientID
            drp.Attributes.Add("onChange", "if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else {" & b & ".disabled = false; }")
            txt.Attributes.Add("onFocus", "if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else { " & b & ".disabled = false; }")
            resetBtnScriptCb1 = "<Script Language='JavaScript'> if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else {" & b & ".disabled = false; }" & _
                                " if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else { " & b & ".disabled = false; } </script>"
            'Page.RegisterClientScriptBlock("resetbtnControlScript", resetBtnScriptCb)
        End If

        If (e.Item.ItemType = ListItemType.EditItem) Then
            'Cells is Zero Based
            '1 is the column number where we want to add the hyperlink
            Dim drp As DropDownList = CType(e.Item.FindControl("drpType"), DropDownList)
            Dim txt As TextBox = CType(e.Item.FindControl("txtEditURL"), TextBox)
            Dim a As String = drp.ClientID
            Dim b As String = txt.ClientID
            drp.Attributes.Add("onChange", "if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else {" & b & ".disabled = false; }")
            txt.Attributes.Add("onFocus", "if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else { " & b & ".disabled = false; }")


            resetBtnScriptCb = "<Script Language='JavaScript'> if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else {" & b & ".disabled = false; }" & _
                                " if(" & a & ".value == 'Internal'){ " & b & ".disabled = true;} else { " & b & ".disabled = false; } </script>"
        End If

    End Sub

    Private Sub Page_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.DataBinding

    End Sub
End Class
