Imports System.Data.SqlClient

Public Class DocumentEdit
    Inherits System.Web.UI.Page

    Property contractId As Int64
    Property itemContext As String
    Property docID As Int64
    Property ItemID As Int64


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        contractId = Logic.Conversion.ToInteger(Request.Params("cid"))
        Master.CurrentClient.VerifyContractAccess(contractId)
        'see if loaded from another page
        itemContext = Logic.Conversion.ToString(Request.Params("ctx"))
        docID = Logic.Conversion.ToInteger(Request.Params("docID"))
        ItemID = Logic.Conversion.ToInteger(Request.Params("id"))

        If Not Page.IsPostBack Then
            LoadCatagories()

            'load the document
            If docID > 0 Then
                LoadDoc(docID)
            End If
        End If

        Dim perms = Master.CurrentClient.Permissions
        If Not perms.Contains("View Document Edit Page") Then Throw New HttpException(403, "Forbidden")

    End Sub

    Private Sub LoadCatagories()
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim perms = Master.CurrentClient.Permissions

        Try
            ddlCategory.Items.Clear()
            ddlCategory.Items.Add(New ListItem("", 0))
            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT id,Name FROM DocumentCatagoriesNew ORDER BY Name"
            DR = cmd.ExecuteReader
            While DR.Read
                If perms.Contains("Upload Documents - " & DR("Name")) Then
                    ddlCategory.Items.Add(New ListItem(DR("Name"), DR("ID")))
                End If
            End While
            DR.Close()
        Catch ex As Exception
            'add an error redirect here. 
        Finally
            connection.Close()
        End Try
    End Sub


    Private Sub LoadSubCategorys(CatagoryId As Int64)

        'Load all sub catagories listed in DocumentManagerSubCatagories
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)

        If Not ddlCategory.SelectedItem.Value = "" Then
            Try
                ddlSubCategory.Items.Clear()

                connection.Open()

                ddlSubCategory.Items.Add(New ListItem("", 0))

                cmd.Connection = connection
                cmd.CommandText = "SELECT Id , Name FROM DocumentsSubCategory Where CategoryId = @CatagoryId ORDER BY Name,ID"
                cmd.Parameters.Add(New SqlClient.SqlParameter("@CatagoryId", SqlDbType.BigInt)).Value = CatagoryId
                DR = cmd.ExecuteReader
                While DR.Read
                    ddlSubCategory.Items.Add(New ListItem(DR("Name"), DR("ID")))
                End While
                DR.Close()

            Catch ex As Exception
                'Write in an catch exception here

            Finally
                connection.Close()
            End Try
        Else
            'Un hide the message please select a catagory firs warning message'
            'Or unhide the DDLSubCategory'
        End If

    End Sub

    Private Sub LoadAccidents(ContractID As Int64) ' going to setup to be done with active clients only.
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim DR As System.Data.SqlClient.SqlDataReader
        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT AccidentDate, DriverName,CityState,ID FROM Accident where ContractID = @ContractId   ORDER BY AccidentDate DESC,DriverName,ID"
            cmd.Parameters.Add(New SqlParameter("@ContractId", SqlDbType.BigInt)).Value = ContractID
            DR = cmd.ExecuteReader()

            While DR.Read
                ddlExtra.Items.Add(New ListItem(Format(DR("AccidentDate"), "MM/dd/yyyy") + ", " + DR("DriverName") + ", " + DR("CityState"), DR("ID")))
            End While
            DR.Close()
        Catch ex As Exception
            'Me.HandleException("An Error Occurred while Loading Accidents", ex)
        Finally
            connection.Close()
        End Try


    End Sub
    Private Sub LoadDrugTest(ContractID As Int64) ' going to setup to be done with active clients only.
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim DR As System.Data.SqlClient.SqlDataReader
        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "  SELECT TestDate ,DriverName , DrugAlcoholTestType.Name as TestTypeName, DrugAlcoholTest.ID as TestID FROM DrugAlcoholTest left join DrugAlcoholTestType on TestTypeID = DrugAlcoholTestType.ID where ContractID = @ContractId  ORDER BY TestDate DESC,DriverName,DrugAlcoholTest.ID"
            cmd.Parameters.Add(New SqlParameter("@ContractId", SqlDbType.BigInt)).Value = ContractID
            DR = cmd.ExecuteReader()
            While DR.Read
                ddlExtra.Items.Add(New ListItem(Format(DR("TestDate"), "MM/dd/yyyy") + ", " + DR("DriverName") + ", " + DR("TestTypeName"), DR("TestID")))
            End While
            DR.Close()
        Catch ex As Exception
            'Me.HandleException("An Error Occurred while Loading DrugTest", ex)
        Finally
            connection.Close()
        End Try
    End Sub
    Private Sub LoadRoadSideInspections(ContractID As Int64) ' going to setup to be done with active clients only.
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim DR As System.Data.SqlClient.SqlDataReader
        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT InspectionDate, DriverName , Vehicle1Desc , RoadsideInspection.ID as RoadSideInspectionID, Jurisdiction FROM RoadsideInspection where RoadsideInspection.ContractID = @ContractId ORDER BY InspectionDate DESC,DriverName,RoadsideInspection.ID"
            cmd.Parameters.Add(New SqlParameter("@ContractId", SqlDbType.BigInt)).Value = ContractID
            DR = cmd.ExecuteReader()
            While DR.Read
                ddlExtra.Items.Add(New ListItem(Format(DR("InspectionDate"), "MM/dd/yyyy") + ",  " + DR("DriverName") + ", " + DR("Vehicle1Desc") + ", " + DR("RoadSideInspectionID").ToString() + ", " + DR("Jurisdiction"), DR("RoadSideInspectionID")))
            End While
            DR.Close()
        Catch ex As Exception
            'Me.HandleException("An Error Occurred while Loading DrugTest", ex)
        Finally
            connection.Close()
        End Try
    End Sub
    Private Sub LoadRegistrationDocs(ContractID As Int64) ' going to setup to be done with active clients only.
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim DR As System.Data.SqlClient.SqlDataReader
        Try
            ddlExtra.Items.Add(New ListItem("", 0))
            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "  select RegistrationDoc.ID as RegistrationDocID, RegistrationDocType.Name as RegistrationDocName from RegistrationDoc left join RegistrationDocType on TypeID = RegistrationDocType.ID where ContractID = @ContractId ORDER BY RegistrationDocType.Name,RegistrationDoc.ID"
            cmd.Parameters.Add(New SqlParameter("@ContractId", SqlDbType.BigInt)).Value = ContractID
            DR = cmd.ExecuteReader()
            While DR.Read
                ddlExtra.Items.Add(New ListItem(DR("RegistrationDocName") + ", " + DR("RegistrationDocID").ToString(), DR("RegistrationDocID")))
            End While
            DR.Close()
        Catch ex As Exception
            'Me.HandleException("An Error Occurred while Loading RegistrationDocs", ex)
        Finally
            connection.Close()
        End Try

    End Sub
    Private Sub LoadDrivers(ContractId As Int64)
        'Load all of the drivers by the Contract Id
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)

        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT ID, LastName, FirstName, MiddleName FROM Driver where ContractID = @contractID AND ISNULL(Driver.Terminated,0)=0 Order by LastName,FIrstName,MiddleName,Driver.ID"
            cmd.Parameters.Add(New SqlClient.SqlParameter("@contractID", SqlDbType.BigInt)).Value = ContractId
            DR = cmd.ExecuteReader
            While DR.Read
                ddlExtra.Items.Add(New ListItem(DR("LastName") + ", " + DR("FirstName") + " " + DR("MiddleName"), DR("ID")))
            End While
            DR.Close()

        Catch ex As Exception
            'Write in an catch exception here
            ' Me.HandleException("An Error Occurred while Loading Drivers", ex)
        Finally
            connection.Close()
        End Try

    End Sub
    Private Sub LoadTraining(ContractId As Int64)
        'Load all of the drivers by the Contract Id
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)

        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "  SELECT DriverName, TrainingTopic.Name as TrainingTopic, SpecificTopic , TrainingDate, Training.ID  FROM Training left join TrainingTopic on TopicID = TrainingTopic.ID where ContractID = @contractID ORDER BY TrainingTopic.Name,DriverName"
            cmd.Parameters.Add(New SqlClient.SqlParameter("@contractID", SqlDbType.BigInt)).Value = ContractId
            DR = cmd.ExecuteReader
            While DR.Read
                ddlExtra.Items.Add(New ListItem(DR("TrainingTopic") + " - " + DR("DriverName") + " - " + DR("SpecificTopic") + ", " + Format(DR("TrainingDate"), "MM/dd/yyyy") + " " + DR("ID").ToString(), DR("ID")))
            End While
            DR.Close()

        Catch ex As Exception
            'Write in an catch exception here
            ' Me.HandleException("An Error Occurred while Loading Drivers", ex)
        Finally
            connection.Close()
        End Try

    End Sub
    Private Sub LoadVehicles(ContractId As Int64)
        'Load all of the Vehicals by the Contract Id
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)

        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT ID ,ContractID ,Unit,UnitYear,Make,Model,VIN FROM Vehicle Where ContractID=@contractId AND ISNULL(Vehicle.NotInService,0)=0 ORDER BY Unit"
            cmd.Parameters.Add(New SqlClient.SqlParameter("@contractID", SqlDbType.BigInt)).Value = ContractId
            DR = cmd.ExecuteReader
            While DR.Read
                ddlExtra.Items.Add(New ListItem(DR("Unit") & " - " & DR("UnitYear") & " (Make: " & DR("Make") & ") (Model:" & DR("Model") & ")", DR("ID")))
            End While
            DR.Close()

        Catch ex As Exception
            'Write in an catch exception here
            'Me.HandleException("An Error Occurred while Loading vehicals", ex)
        Finally
            connection.Close()
        End Try

    End Sub
    Private Sub LoadClientContact(ContractId As Int64)
        'Load all of the Vehicals by the Contract Id
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)

        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT CustomerContact.ID ,CustomerContact.ContractID,CustomerContactType.Name AS ContactType,ISNULL(Employee.LastName,'')+','+ISNULL(Employee.FirstName,'') AS EmployeeName,CustomerContact.StartTime,CustomerContact.EndTime,CustomerContact.ShortDescription FROM CustomerContact LEFT JOIN CustomerContactType ON CustomerContact.ContactTypeID=CustomerContactType.ID LEFT JOIN Employee ON CustomerContact.EmployeeID=Employee.ID Where ContractID=@contractId ORDER BY CustomerContactType.Name,CustomerContact.StartTime,ISNULL(Employee.LastName,'')+','+ISNULL(Employee.FirstName,''),CustomerContact.ID"
            cmd.Parameters.Add(New SqlClient.SqlParameter("@contractID", SqlDbType.BigInt)).Value = ContractId
            DR = cmd.ExecuteReader
            While DR.Read
                ddlExtra.Items.Add(New ListItem(DR("ContactType") & " - " & DR("EmployeeName") & " - " & Format(DR("StartTime"), "MM/dd/yyyy") & " - " & DR("ShortDescription"), DR("ID")))
            End While
            DR.Close()

        Catch ex As Exception
            'Write in an catch exception here
            'Me.HandleException("An Error Occurred while Loading Client Contacts", ex)
        Finally
            connection.Close()
        End Try

    End Sub
    Private Sub LoadContractNote(ContractId As Int64)
        'Load all of the Vehicals by the Contract Id
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)

        Try
            ddlExtra.Items.Add(New ListItem("", 0))

            connection.Open()
            cmd.Connection = connection
            cmd.CommandText = "SELECT ContractNote.ID ,ContractNote.ContractID,NoteDate,LEFT(CAST(Note AS VARCHAR),50) AS Note FROM ContractNote Where ContractID=@contractId ORDER BY NoteDate,ID"
            cmd.Parameters.Add(New SqlClient.SqlParameter("@contractID", SqlDbType.BigInt)).Value = ContractId
            DR = cmd.ExecuteReader
            While DR.Read
                ddlExtra.Items.Add(New ListItem(Format(DR("NoteDate"), "MM/dd/yyyy") & " - " & DR("Note"), DR("ID")))
            End While
            DR.Close()

        Catch ex As Exception
            'Write in an catch exception here
            'Me.HandleException("An Error Occurred while Loading Contract Notes", ex)
        Finally
            connection.Close()
        End Try

    End Sub

    Protected Sub ClearForm()
        ddlCategory.SelectedIndex = -1
        ddlSubCategory.SelectedIndex = -1
        ddlExtra.SelectedIndex = -1
        txtDocName.Text = ""
        txtNotes.Text = ""

        txtCategoryOrig.Text = ""
        txtExtraOrig.Text = ""
        txtSubCategoryOrig.Text = ""
        txtDocNameOrig.Text = ""
        txtNotesOrig.Text = ""


    End Sub
    Protected Sub LoadDoc(ByVal DocID As Int64)
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim Sql As String
        Dim cmd As New SqlCommand
        Dim DR As SqlDataReader
        Dim CatID As Int64 = 0
        Dim ItemID As Int64 = 0
        Dim SubCatID As Int64 = 0
        Dim DocName As String = ""
        Dim Notes As String = ""

        Try
            ClearForm()

            If DocID > 0 Then
                connection.Open()
                cmd.Connection = connection
                Sql = "SELECT CategoryID,ISNULL(ItemID,0) AS ItemID,ISNULL(SubCategoryID,0) AS SubCategoryID,ISNULL(DocName,'') AS DocName,ISNULL(UploadNotes,'') AS UploadNotes FROM DocumentsNew WHERE ID=@DocID"
                cmd.CommandText = Sql

                cmd.Parameters.Add(New SqlParameter("@DocID", SqlDbType.BigInt)).Value = DocID
                DR = cmd.ExecuteReader
                If DR.Read Then
                    CatID = DR("CategoryID")
                    ItemID = DR("ItemID")
                    SubCatID = DR("SubCategoryID")
                    DocName = DR("DocName")
                    Notes = DR("UploadNotes")
                End If
                DR.Close()

                ddlCategory.SelectedValue = CatID
                LoadDropDowns(CatID)

                txtCategoryOrig.Text = ddlCategory.SelectedItem.Text
                If ItemID <> 0 Then
                    ddlExtra.SelectedValue = ItemID
                    txtExtraOrig.Text = ddlExtra.SelectedItem.Text
                End If
                If SubCatID <> 0 Then
                    ddlSubCategory.SelectedValue = SubCatID
                    txtSubCategoryOrig.Text = ddlSubCategory.SelectedItem.Text
                End If
                txtDocName.Text = DocName
                txtNotes.Text = Notes

                txtDocNameOrig.Text = txtDocName.Text
                txtNotesOrig.Text = txtNotes.Text

            Else
                'MessageBox.Show("Please select a Contract, Category, And file before the documents can be saved.")
            End If
        Catch ex As Exception
            'Me.HandleException("An Error Occurred while saving ", ex)
        Finally
            connection.Close()
            btnSave.Enabled = True
        End Try

    End Sub

    Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim Sql As String
        Dim SqlDoc As String
        Dim sqlLog As String = ""
        Dim cmd As New SqlCommand
        Dim cmdDoc As New SqlCommand
        Dim cmdLog As New SqlCommand
        Dim DR As SqlDataReader

        Dim FilesReady As Boolean = False
        Try
            btnSave.Enabled = False

            If contractId > 0 And docID > 0 And ddlCategory.SelectedIndex > 0 Then
                connection.Open()
                cmd.Connection = connection
                Sql = "UPDATE DocumentsNew SET ItemID=@ItemID,CategoryID=@CategoryID,SubCategoryId=@SubCategoryId,DocName=@DocName,EditedDate=GETDATE(),EditedBy=@EnteredBy,UploadNotes=@UploadNotes WHERE id=@DocID"
                cmd.CommandText = Sql

                cmd.Parameters.Add(New SqlParameter("@DocID", SqlDbType.BigInt)).Value = docID
                cmd.Parameters.Add(New SqlParameter("@CategoryID", SqlDbType.BigInt)).Value = ddlCategory.SelectedItem.Value
                If ddlSubCategory.SelectedIndex >= 0 Then
                    cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@SubCategoryId", SqlDbType.BigInt)).Value = ddlSubCategory.SelectedItem.Value
                Else
                    cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@SubCategoryId", SqlDbType.BigInt)).Value = 0 'DBNull.Value
                End If
                If ddlExtra.SelectedIndex >= 0 Then
                    cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@ItemID", SqlDbType.BigInt)).Value = ddlExtra.SelectedItem.Value
                Else
                    cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@ItemID", SqlDbType.BigInt)).Value = 0
                End If
                cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@DocName", SqlDbType.VarChar)).Value = txtDocName.Text
                cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@EnteredBy", SqlDbType.VarChar)).Value = Master.CurrentClient.username
                cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@UploadNotes", SqlDbType.VarChar)).Value = txtNotes.Text
                cmd.ExecuteNonQuery()

                'move to new database if category change
                If ddlCategory.SelectedItem.Text <> txtCategoryOrig.Text Then
                    Dim connectionDoc As New SqlConnection(Logic.Database.DocumentMannagerConnectionString(ddlCategory.SelectedItem.Text))
                    Dim connectionDocOrig As New SqlConnection(Logic.Database.DocumentMannagerConnectionString(txtCategoryOrig.Text))
                    connectionDoc.Open()
                    connectionDocOrig.Open()

                    cmd.Connection = connectionDocOrig
                    cmdDoc.Connection = connectionDoc

                    cmd.CommandText = "SELECT * FROM Documents WHERE DocumentID=@DocID"
                    DR = cmd.ExecuteReader
                    If DR.Read Then
                        cmdDoc.Parameters.Add(New System.Data.SqlClient.SqlParameter("@DocumentID", SqlDbType.BigInt)).Value = DR("DocumentID")
                        cmdDoc.Parameters.Add(New System.Data.SqlClient.SqlParameter("@DocBlob", SqlDbType.VarBinary)).Value = DR("DocBlob")
                        cmdDoc.Parameters.Add(New System.Data.SqlClient.SqlParameter("@DocSize", SqlDbType.BigInt)).Value = DR("DocSize")
                        cmdDoc.Parameters.Add(New System.Data.SqlClient.SqlParameter("@FileType", SqlDbType.VarChar)).Value = DR("FileType")
                    End If
                    DR.Close()

                    SqlDoc = "INSERT INTO Documents (DocumentID,DocBlob,DocSize,FileType) VALUES (@DocumentID,@DocBlob,@DocSize,@FileType)"
                    cmdDoc.CommandText = SqlDoc
                    cmdDoc.ExecuteNonQuery()
                    connectionDoc.Close()
                    connectionDocOrig.Close()
                End If


                'log
                Dim Edits As String = ""
                Edits += IIf(txtCategoryOrig.Text <> ddlCategory.SelectedItem.Text, "Category: " & txtCategoryOrig.Text & " --> " & ddlCategory.SelectedItem.Text & vbCrLf, "")
                If ddlSubCategory.SelectedIndex >= 0 Then
                    Edits += IIf(txtSubCategoryOrig.Text <> ddlSubCategory.SelectedItem.Text, "Doc Type: " & txtSubCategoryOrig.Text & " --> " & ddlSubCategory.SelectedItem.Text & vbCrLf, "")
                End If
                If ddlExtra.SelectedIndex >= 0 Then
                    Edits += IIf(txtExtraOrig.Text <> ddlExtra.SelectedItem.Text, "Item: " & txtExtraOrig.Text & " --> " & ddlExtra.SelectedItem.Text & vbCrLf, "")
                End If
                Edits += IIf(txtNotesOrig.Text <> txtNotes.Text, "Notes: " & txtNotesOrig.Text & " --> " & txtNotes.Text & vbCrLf, "")
                Edits += IIf(txtDocNameOrig.Text <> txtDocName.Text, "File Name: " & txtDocNameOrig.Text & " --> " & txtDocName.Text & vbCrLf, "")

                cmdLog.Connection = connection
                sqlLog = "INSERT INTO DocumentsNewLog (ContractId,DocumentID,EditDate,EditBy,EditSource,EditAction,OrigCategory,OrigSubCategory,OrigItem,OrigNotes,OrigDocName) "
                sqlLog += " VALUES (@ContractId,@DocumentID,GETDATE(),@EditBy,@EditSource,@EditAction,@OrigCategory,@OrigSubCategory,@OrigItem,@OrigNotes,@OrigDocName)"
                cmdLog.CommandText = sqlLog
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@ContractId", SqlDbType.BigInt)).Value = contractId
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@DocumentID", SqlDbType.BigInt)).Value = docID
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@EditBy", SqlDbType.VarChar)).Value = Master.CurrentClient.username
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@EditSource", SqlDbType.VarChar)).Value = "PORTAL"
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@EditAction", SqlDbType.VarChar)).Value = Edits
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@OrigCategory", SqlDbType.VarChar)).Value = txtCategoryOrig.Text
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@OrigSubCategory", SqlDbType.VarChar)).Value = txtSubCategoryOrig.Text
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@OrigItem", SqlDbType.VarChar)).Value = txtExtraOrig.Text
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@OrigNotes", SqlDbType.VarChar)).Value = txtNotesOrig.Text
                cmdLog.Parameters.Add(New System.Data.SqlClient.SqlParameter("@OrigDocName", SqlDbType.VarChar)).Value = txtDocNameOrig.Text
                cmdLog.ExecuteNonQuery()

                If itemContext = "uncat" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=uncat&id=0&cid=" & contractId)
                ElseIf itemContext = "Driver" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "DrugAlcoholTest" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                    'Response.Redirect("DrugAlcoholTests.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "Vehicle" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "Training" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "RoadsideInspection" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "Accident" Then
                    Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "DriverEdit" Then
                    Response.Redirect("EditDriver.aspx?id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "VehicleEdit" Then
                    Response.Redirect("EditVehicle.aspx?id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "TrainingEdit" Then
                    Response.Redirect("EditTraining.aspx?id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "RoadsideInspectionEdit" Then
                    Response.Redirect("EditRoadsideInspection.aspx?id=" & ItemID & "&cid=" & contractId)
                ElseIf itemContext = "AccidentEdit" Then
                    Response.Redirect("EditAccident.aspx?id=" & ItemID & "&cid=" & contractId)
                End If
                'Response.Redirect("DocumentsNew.aspx?ctx=uncat&id=0&cid=" & contractId)
            Else
                'MessageBox.Show("Please select a Contract, Category, And file before the documents can be saved.")
            End If
        Catch ex As Exception
            'Me.HandleException("An Error Occurred while saving ", ex)
        Finally
            connection.Close()
            btnSave.Enabled = True
        End Try
    End Sub

    Private Sub ddlCategory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlCategory.SelectedIndexChanged
        If ddlCategory.SelectedIndex >= 0 Then
            LoadDropDowns(ddlCategory.SelectedItem.Value)
        End If
    End Sub

    Private Sub LoadDropDowns(ByVal CatID As Int64)
        ddlExtra.SelectedIndex = -1
        ddlExtra.Items.Clear()

        If CatID >= 0 Then
            LoadSubCategorys(CatID)

            Select Case CatID
                Case 1
                    LoadAccidents(contractId)
                Case 3
                    LoadDrivers(contractId)
                Case 4
                    LoadDrugTest(contractId)
                Case 6
                    LoadRegistrationDocs(contractId)
                Case 7
                    LoadRoadSideInspections(contractId)
                Case 8
                    LoadTraining(contractId)
                Case 9
                    LoadVehicles(contractId)
                Case 10
                    LoadClientContact(contractId)
                Case 11
                    LoadContractNote(contractId)
            End Select
        End If

    End Sub

    Protected Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        If itemContext = "uncat" Then
            Response.Redirect("DocumentsNew.aspx?ctx=uncat&id=0&cid=" & contractId)
        ElseIf itemContext = "other" Then
            Response.Redirect("DocumentsNew.aspx?ctx=other&id=0&cid=" & contractId)
        ElseIf itemContext = "Driver" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "DriverDPQ" Then
            Response.Redirect("Recruiting.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "DrugAlcoholTest" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
            'Response.Redirect("DrugAlcoholTests.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "Vehicle" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "Training" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "RoadsideInspection" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "Accident" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "DriverEdit" Then
            Response.Redirect("EditDriver.aspx?id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "VehicleEdit" Then
            Response.Redirect("EditVehicle.aspx?id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "TrainingEdit" Then
            Response.Redirect("EditTraining.aspx?id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "RoadsideInspectionEdit" Then
            Response.Redirect("EditRoadsideInspection.aspx?id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "AccidentEdit" Then
            Response.Redirect("EditAccident.aspx?id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "RegistrationDoc" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)
        ElseIf itemContext = "CompanyPolicies" Then
            Response.Redirect("DocumentsNew.aspx?ctx=" & itemContext & "&id=" & ItemID & "&cid=" & contractId)

        End If

    End Sub

End Class