Imports System.Collections.Generic
Imports System.Configuration
Imports System.Xml
Imports System.Data.SqlClient
Imports System.Data
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Enumerations


Partial Class Edit
    Inherits AdminPage

    Private Const CONFIGURATION_USER_CONTROL_IDS As String = "UserControlIDs"
    Dim metaTable As DAL.HtmlMetaDataTable


  Private Sub AddContentItem(ByVal userControlID As String, ByVal ownerType As OwnerType, ByVal ownerID As String, _
          ByVal versionText As String)

    'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

    Dim contentID As Integer = 0
    Dim versions As List(Of ContentSchema.VERSION) = Nothing
    Dim versionID As Integer = 0
    Dim schedules As List(Of ContentSchema.SCHEDULE) = Nothing

    ' add the content item
    contentID = CMSContentManager.Instance.GetContentID(userControlID, ownerID, ownerType.ToString)
    If contentID = 0 Then
      Dim versionAdded As Boolean = CMSContentManager.Instance.AddVersion(userControlID, ownerID, ownerType, contentID, "Original", versionText)
      contentID = CMSContentManager.Instance.GetContentID(userControlID, ownerID, ownerType.ToString)
      If contentID = 0 Then

        ' error condition; failed to add version
        Dim ex As Exception = New Exception("AddVersion method call failed")
        Throw ex
      End If
    End If

    ' the content item might actually be old, so check for any versions
        Dim tempVersions() As CMS.VERSION
        tempVersions = CMSContentManager.Instance.GetVersions(contentID)
        If Not tempVersions Is Nothing Then
            versions = New List(Of ContentSchema.VERSION)
            versions.AddRange(tempVersions)
        End If

        If Not versions Is Nothing Then
            If versions.Count > 0 Then
                versionID = versions.Item(0).VersionID
            Else

                ' error condition; failed to add version
                Dim ex As Exception = New Exception("AddVersion method call failed")
                Throw ex
            End If
        Else

            ' error condition; failed to add version
            Dim ex As Exception = New Exception("AddVersion method call failed")
            Throw ex
        End If

        Dim tempschedules() As CMS.SCHEDULE
        tempschedules = CMSContentManager.Instance.GetSchedules(versionID)
        schedules = New List(Of ContentSchema.SCHEDULE)
        If Not tempschedules Is Nothing Then
            schedules.AddRange(tempschedules)
        End If

        If schedules Is Nothing Then
            CMSContentManager.Instance.AddSchedule(versionID, Date.Today, Nothing)
        ElseIf schedules.Count = 0 Then
            CMSContentManager.Instance.AddSchedule(versionID, Date.Today, Nothing)
        End If

    End Sub

    Private Sub ProcessFind(ByVal userControlID As String, ByVal ownerTypeID As OwnerType, ByVal ownerID As String)
        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance
        'With CMSContentManager

        ' try to get a content ID
        Dim contentID As Integer = CMSContentManager.Instance.GetContentID(userControlID, ownerID, ownerTypeID.ToString)

        ' did the arguments map to a content ID?
        Dim haveContent As Boolean = (contentID > 0)
        If haveContent Then

            ' yes; get the content
            contentIDLabel.Text = contentID.ToString()

            ' get the versions of the content
            Dim versions As List(Of ContentSchema.VERSION) = Nothing
            Dim tempversion() As CMS.VERSION = Nothing
            tempversion = CMSContentManager.Instance.GetVersions(contentID)
            If Not tempversion Is Nothing Then
                versions = New List(Of ContentSchema.VERSION)
                For Each obj As CMS.VERSION In tempversion
                    Dim objVersion As ContentSchema.VERSION = Nothing
                    objVersion.ContentID = obj.ContentID
                    objVersion.ContentText = obj.ContentText
                    objVersion.SearchResultDisplayable = obj.SearchResultDisplayable
                    objVersion.VERSION_NAME = obj.VERSION_NAME
                    objVersion.VersionID = obj.VersionID
                    versions.Add(objVersion)
                Next
                'versions.AddRange(tempversion)
            End If
            With versionDropDownList
                .DataSource = versions
                .DataTextField = "VERSION_NAME"
                .DataValueField = "VersionID"
                .DataBind()
            End With

            ' display the first version
            Dim versionID As Integer = CInt(versionDropDownList.SelectedValue)
            ProcessVersionSelection(versionID)
            submitButton.Enabled = True
        End If

        ' set the state of the controls
        userControlIDDropDownList.Enabled = haveContent
        ownerTypeIDDropDownList.Enabled = haveContent
        ownerIDTextBox.Enabled = haveContent
        contentLabel.Visible = haveContent
        contentIDLabel.Visible = haveContent
        FCKeditor.Visible = haveContent
        submitButton.Visible = haveContent
        createNewContentLabel.Visible = Not haveContent
        createNewContentButton.Visible = Not haveContent
        cancelNewContentButton.Visible = Not haveContent
        'End With

    End Sub

    Private Sub ProcessScheduleSelection(ByVal versionID As Integer, ByVal scheduleID As Integer)

        ' get the dates for the schedule
        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance
        Dim tempschedules() As CMS.SCHEDULE = Nothing
        Dim schedules As List(Of ContentSchema.SCHEDULE) = Nothing
        tempschedules = CMSContentManager.Instance.GetSchedules(versionID)
        If Not tempschedules Is Nothing Then
            schedules = New List(Of ContentSchema.SCHEDULE)
            For Each obj As CMS.SCHEDULE In tempschedules
                Dim objSchedule As ContentSchema.SCHEDULE
                objSchedule.ApprovedBy_UserID = obj.ApprovedBy_UserID
                objSchedule.ApprovedDate = obj.ApprovedDate
                objSchedule.CreateBy_UserID = obj.CreateBy_UserID
                objSchedule.CreateDate = obj.CreateDate
                objSchedule.DeleteBy_UserID = obj.DeleteBy_UserID
                objSchedule.DeleteDate = obj.DeleteDate
                objSchedule.EndDate = obj.EndDate
                objSchedule.ModifyBy_UserID = obj.ModifyBy_UserID
                objSchedule.ModifyDate = obj.ModifyDate
                objSchedule.ScheduleID = obj.ScheduleID
                objSchedule.StartDate = obj.StartDate
                objSchedule.VersionID = obj.VersionID

                schedules.Add(objSchedule)
            Next
            'versions.AddRange(tempversion)
        End If

        For Each thisSchedule As ContentSchema.SCHEDULE In schedules
            With thisSchedule
                If .ScheduleID = scheduleID Then
                    beginDateTextBox.Text = .StartDate.ToShortDateString()
                    Dim endDate As Date = .EndDate
                    If endDate.Equals(CDate(#12:00:00 AM#)) Then
                        endDateTextBox.Text = "None"
                    Else
                        endDateTextBox.Text = .EndDate.ToShortDateString()
                    End If
                    Exit For
                End If
            End With
        Next

    End Sub

    Private Sub ProcessSubmit(ByVal versionID As Integer, ByVal content As String, ByVal VERSIONNAME As String, ByVal SearchResultDisplayable As Boolean, ByVal TemplateID As Integer, ByVal Templatename As String)

        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance
        'CMSContentManager.Instance.UpdateVersionText(versionID, content, VERSIONNAME, SearchResultDisplayable)
        Try
            Dim cmsAdmin As New CMS.CMSService()
            cmsAdmin.Credentials = Net.CredentialCache.DefaultNetworkCredentials
            cmsAdmin.EditContent(versionID, content, VERSIONNAME, SearchResultDisplayable, TemplateID, Replace(Me.User.Identity.Name, "CHTR\", ""), Templatename)

        Catch ex As Exception
            Throw ex
        Finally

        End Try

    End Sub

    Private Sub ProcessVersionSelection(ByVal versionID As Integer)

        ' display the content for the selected version
        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

        Dim contentID As Integer = CInt(contentIDLabel.Text)
        Dim tempVersions() As CMS.VERSION = Nothing
        Dim versions As List(Of ContentSchema.VERSION) = Nothing
        tempVersions = CMSContentManager.Instance.GetVersions(contentID)
        If Not tempVersions Is Nothing Then
            versions = New List(Of ContentSchema.VERSION)
            For Each obj As CMS.VERSION In tempVersions
                Dim objVersion As ContentSchema.VERSION = Nothing
                objVersion.ContentID = obj.ContentID
                objVersion.ContentText = obj.ContentText
                objVersion.SearchResultDisplayable = obj.SearchResultDisplayable
                objVersion.VERSION_NAME = obj.VERSION_NAME
                objVersion.VersionID = obj.VersionID
                versions.Add(objVersion)
            Next
            'versions.AddRange(tempversion)
        End If

        Dim content As String = String.Empty
        For Each version As ContentSchema.VERSION In versions
            If version.VersionID = versionID Then
                content = version.ContentText

                If version.SearchResultDisplayable = True Then
                    SearchResultDisplayableCheckBox.Checked = True
                Else
                    SearchResultDisplayableCheckBox.Checked = False
                End If
                versionNameTextBox.Text = version.VERSION_NAME
                Exit For
            End If
        Next

        FCKeditor.Value = content

        ' get the schedules for the version

        Dim tempschedules() As CMS.SCHEDULE = Nothing
        Dim schedules As List(Of ContentSchema.SCHEDULE) = Nothing
        tempschedules = CMSContentManager.Instance.GetSchedules(versionID)
        schedules = New List(Of ContentSchema.SCHEDULE)
        If Not tempschedules Is Nothing Then
            schedules = New List(Of ContentSchema.SCHEDULE)
            For Each obj As CMS.SCHEDULE In tempschedules
                Dim objSchedule As ContentSchema.SCHEDULE = Nothing
                objSchedule.ApprovedBy_UserID = obj.ApprovedBy_UserID
                objSchedule.ApprovedDate = obj.ApprovedDate
                objSchedule.CreateBy_UserID = obj.CreateBy_UserID
                objSchedule.CreateDate = obj.CreateDate
                objSchedule.DeleteBy_UserID = obj.DeleteBy_UserID
                objSchedule.DeleteDate = obj.DeleteDate
                objSchedule.EndDate = obj.EndDate
                objSchedule.ModifyBy_UserID = obj.ModifyBy_UserID
                objSchedule.ModifyDate = obj.ModifyDate
                objSchedule.ScheduleID = obj.ScheduleID
                objSchedule.StartDate = obj.StartDate
                objSchedule.VersionID = obj.VersionID

                schedules.Add(objSchedule)
            Next
            'versions.AddRange(tempversion)
        End If

        'If Not tempschedules Is Nothing Then
        '  schedules.AddRange(tempschedules)
        'End If
        With scheduleDropDownList
            .DataSource = schedules
            .DataTextField = "StartDate"
            .DataValueField = "ScheduleID"
            .DataBind()
        End With

        For Each thisSchedule As ListItem In scheduleDropDownList.Items
            thisSchedule.Text = CDate(thisSchedule.Text).ToShortDateString()
        Next

        ' display the first schedule
        If Not scheduleDropDownList.SelectedItem Is Nothing Then
            Dim scheduleID As Integer = CInt(scheduleDropDownList.SelectedValue)
            ProcessScheduleSelection(versionID, scheduleID)
        End If
       




    End Sub

    ' temporary stuff

    Private Sub AddMissingSchedule()

        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

        Dim contentID As Integer = 184
        Dim versionID As Integer = 0

        ' the content item might actually be old, so check for any versions
        Dim versions As List(Of ContentSchema.VERSION) = Nothing
        Dim tempVersions() As CMS.VERSION = Nothing
        tempVersions = CMSContentManager.Instance.GetVersions(contentID)
        If Not tempVersions Is Nothing Then
            versions = New List(Of ContentSchema.VERSION)
            versions.AddRange(tempVersions)
        End If

        If Not versions Is Nothing Then
            If versions.Count > 0 Then
                versionID = versions.Item(0).VersionID
            Else

                ' error condition; failed to add version
                Dim ex As Exception = New Exception("AddVersion method call failed")
                Throw ex
            End If
        Else

            ' error condition; failed to add version
            Dim ex As Exception = New Exception("AddVersion method call failed")
            Throw ex
        End If

        Dim schedules As List(Of ContentSchema.SCHEDULE) = Nothing
        Dim tempschedules() As CMS.SCHEDULE = Nothing
        tempschedules = CMSContentManager.Instance.GetSchedules(versionID)
        schedules = New List(Of ContentSchema.SCHEDULE)
        If Not tempschedules Is Nothing Then
            schedules.AddRange(tempschedules)
        End If

        If schedules Is Nothing Then
            CMSContentManager.Instance.AddSchedule(versionID, Date.Today, Nothing)
        ElseIf schedules.Count = 0 Then
            CMSContentManager.Instance.AddSchedule(versionID, Date.Today, Nothing)
        End If

    End Sub

    Private Sub DeleteOldVersions()

        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance
        'CMSContentManager.DeleteVersion(299)
        'CMSContentManager.DeleteVersion(371)
        'CMSContentManager.DeleteVersion(387)
        'CMSContentManager.DeleteVersion(297)
        'CMSContentManager.DeleteVersion(298)
        'CMSContentManager.DeleteVersion(300)
        'CMSContentManager.DeleteVersion(301)
        'CMSContentManager.DeleteVersion(302)
        'CMSContentManager.DeleteVersion(303)
        'CMSContentManager.DeleteVersion(364)
        'CMSContentManager.DeleteVersion(365)
        'CMSContentManager.DeleteVersion(389)
        'CMSContentManager.DeleteVersion(395)
        CMSContentManager.Instance.DeleteVersion(445)
        'CMSContentManager.DeleteVersion(547)


    End Sub

    Private Sub EnterProducts()

        'Dim packageOwnerID As String = "25500,25200,25300,25400,25187,25700,25800,26000"
        'Dim packageVersionText As String = "Expanded Basic,Digital Big,Digital Bigger,Digital Biggest,3 Meg,5 Meg,10 Meg,Unlimited LDP"
        'Dim packageOwnerID As String = "25800"
        'Dim packageVersionText As String = "10 Meg"
        'Dim packageOwnerID As String = "25187,25700,25800,26000"
        'Dim packageVersionText As String = "3 Meg,5 Meg,10 Meg,Unlimited LDP"
        Dim packageOwnerID As String = "25700,25800,26000"
        Dim packageVersionText As String = "5 Meg,10 Meg,Unlimited LDP"

        'Dim bundleOwnerID As String = "16200,16400,16700,16500,16600,16100,16300"
        'Dim bundleVersionText As String = "Expanded Basic and 3 Meg,Digital Big and Unlimited LDP,3 Meg and Unlimited LDP,Digital Big and 3 Meg,Digital Big and 5 Meg,Expanded Basic and 3 Meg and ULDP,Digital Big and 3 MEg and ULDP"
        'Dim bundleOwnerID As String = "16200,16400,16700,16600"
        'Dim bundleVersionText As String = "Expanded Basic and 3 Meg,Digital Big and Unlimited LDP,3 Meg and Unlimited LDP,Digital Big and 5 Meg"
        'Dim bundleOwnerID As String = "16100,16300"
        'Dim bundleVersionText As String = "Expanded Basic and 3 Meg and ULDP,Digital Big and 3 MEg and ULDP"
        Dim bundleOwnerID As String = "16300"
        Dim bundleVersionText As String = "Digital Big and 3 Meg and ULDP"

        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

        Dim thisProduct As Integer = 0

        Dim ownerID As String() = packageOwnerID.Split(",".ToCharArray())
        Dim versionText As String() = packageVersionText.Split(",".ToCharArray())
        For thisProduct = 0 To ownerID.Length - 1

            ' add the content item
            AddContentItem("OfferDetail", OwnerType.ServicePlan, ownerID(thisProduct), versionText(thisProduct))
        Next

        ownerID = bundleOwnerID.Split(",".ToCharArray())
        versionText = bundleVersionText.Split(",".ToCharArray())
        For thisProduct = 0 To ownerID.Length - 1

            ' add the content item
            AddContentItem("OfferDetail", OwnerType.Bundle, ownerID(thisProduct), versionText(thisProduct))
        Next

    End Sub

    Private Sub EnterOther()

        'Dim userControlIDString As String = "PrivacyRight:CableTV,PrivacyRight:Internet,PrivacyRight:Telephone"
        'Dim userControlIDString As String = "Support:OnlineSecurity:1,Support:OnlineSecurity:2,Support:OnlineSecurity:3,Support:OnlineSecurity:4,Support:OnlineSecurity:5"
        'Dim userControlIDString As String = "AboutParentControls,CareersBenefits:1,CareersBenefits:2,CareersBenefits:3,CareersBenefits:4,OnlineGuide,Promotion:ThankYou,ProtectionAlert,SecurityAlert,TestYourComputer"
        Dim userControlIDString As String = "SecurityAlertInstructions"

        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

        Dim userControlID As String() = userControlIDString.Split(",".ToCharArray())
        For thisItem As Integer = 0 To userControlID.Length - 1

            ' add the content item
            AddContentItem(userControlID(thisItem), OwnerType.Other, "1", userControlID(thisItem) + " content")
        Next

    End Sub

    Private Sub EnterLocalAreas()

        Dim ownerIDString As String = "6"

        'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

        Dim ownerID As String() = ownerIDString.Split(",".ToCharArray())
        For thisItem As Integer = 0 To ownerIDString.Length - 1

            ' add the content item
            AddContentItem("LocalArea:Body", OwnerType.ZipCode, ownerID(thisItem), "LocalArea:Body content")
            AddContentItem("LocalArea:Head", OwnerType.ZipCode, ownerID(thisItem), "LocalArea:Head content")

            'Private Sub AddContentItem(ByVal userControlID As String, ByVal ownerType As OwnerType, ByVal ownerID As String, _
            '        ByVal versionText As String)
        Next

    End Sub

    ' end temporary stuff

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        FCKeditor.ImageBrowserURL = "VersionImage.aspx"



'       set possibly previously hidden items
'       ##############################################################
        Me.btnClearForceSubmit.Visible = False
'       ##############################################################


        '#load all meta information
        Dim metaAdapter As DALTableAdapters.HtmlMetaTableAdapter = New DALTableAdapters.HtmlMetaTableAdapter
        'me.htmlmetas = metaAdapter.fin 
        metaTable = metaAdapter.GetData()

        Me.lblErrorMessage.Visible = False
    


        

        If Not IsPostBack Then
        
        '#Load data into templates drop down
        Dim templatescmsTA As DALTableAdapters.Template_CMSTableAdapter = New DALTableAdapters.Template_CMSTableAdapter

'       the value 1 here represents the roleid (ContentAuthor)
        Dim templates As DAL.Template_CMSDataTable = templatescmsTA.GetDataBy(Me.CurrentUserID, 1)
        ddlTemplate.Items.Clear()
        For Each template As DAL.Template_CMSRow In templates
            ddlTemplate.Items.Add(New ListItem(template.TemplateName, template.TemplateID))
        Next

            '#Load data into global metalist
            txtGlobalMetaList.Items.Clear()
            For Each row As DAL.HtmlMetaRow In metaTable
                txtGlobalMetaList.Items.Add(New ListItem(row.MetaAlias, row.MetaID))
            Next
            ViewState.Add("templateid", 0)





            ' calls to temporary stuff in lieu of UI functionality

            'EnterProducts()
            'EnterOther()
            'EnterLocalAreas()
            'DeleteOldVersions()
            'AddMissingSchedule()

            Dim ownerTypes As Dictionary(Of Integer, String) = Nothing
            Dim organization As String = Nothing
            Dim userControlIDDictionary As Dictionary(Of Integer, String) = Nothing

            Try
                'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

                ' load the owner types
                Dim tempownertypes() As CMS.OWNERDATA = Nothing
                tempownertypes = CMSContentManager.Instance.GetOwnerTypes()

                If Not tempownertypes Is Nothing Then
                    ownerTypes = New Dictionary(Of Integer, String)
                    For Each a As CMS.OWNERDATA In tempownertypes
                        If a.DESCRIPTION.ToLower() = "other" Then
                            ownerTypes.Add(a.ID, "General")
                        Else
                            ownerTypes.Add(a.ID, a.DESCRIPTION)
                        End If
                    Next
                End If

                With ownerTypeIDDropDownList
                    .DataSource = ownerTypes
                    .DataTextField = "Value"
                    .DataValueField = "Key"
                    .DataBind()
                End With

                'select owner type and load owner ids for that type
                Dim obj As Object = Me.userControlIDDropDownList
                Me.userControlIDDropDownList.DataBind()
                Me.userControlIDDropDownList.SelectedIndex = 0

                ownerTypeIDDropDownList.SelectedIndex = 2

                Dim ownertypeid As Int32 = Int32.Parse(ownerTypeIDDropDownList.SelectedItem.Value)
                Dim usercontrolname As String = Me.userControlIDDropDownList.SelectedItem.Value

                Dim corgTA As DALTableAdapters.Content_OrganizationTableAdapter = New DALTableAdapters.Content_OrganizationTableAdapter()
                Dim corgTable As DAL.Content_OrganizationDataTable = corgTA.GetData(ownertypeid, usercontrolname)

                Me.ownerIDTextBox.Items.Clear()
                For Each owneridrow As DAL.Content_OrganizationRow In corgTable
                    Me.ownerIDTextBox.Items.Add(New ListItem(owneridrow.ownerid, owneridrow.ownerid))
                Next

                ' load the organization structure
                'organization = CMSContentManager.GetOrganization()

                'Dim xmlDataSource As XmlDataSource = New XmlDataSource()
                'With xmlDataSource
                '    .Data = organization
                '    .DataBind()
                'End With
                'With organizationUnitTreeView

                '    .DataSource = xmlDataSource
                '    Dim binding1 As TreeNodeBinding = New TreeNodeBinding()
                '    With binding1
                '        .DataMember = "Org"
                '        .TextField = "name"
                '        .ValueField = "id"
                '    End With
                '    .DataBindings.Add(binding1)
                '    Dim binding2 As TreeNodeBinding = New TreeNodeBinding()
                '    With binding2
                '        .DataMember = "Org"
                '        .TextField = "name"
                '        .ValueField = "id"
                '    End With
                '    .DataBindings.Add(binding2)
                '    .DataBind()
                'End With

                ' set the organizational unit
                'CMSContentManager.Instance.SetOrganization("0")
                selectedUnitLabel.Text = "(National)"

                ' '' load the list of user control IDs
                ''Dim userControlIDs As String = ConfigurationManager.AppSettings.Get(CONFIGURATION_USER_CONTROL_IDS)

                ''Dim userControlIDArray As String() = userControlIDs.Split(",".ToCharArray())
                ''userControlIDDictionary = New Dictionary(Of Integer, String)(userControlIDArray.Length)
                ''For thisUserControlID As Integer = 0 To userControlIDArray.Length - 1
                ''    userControlIDDictionary.Add(thisUserControlID, userControlIDArray(thisUserControlID))
                ''Next

                ''With userControlIDDropDownList
                ''    .DataSource = userControlIDDictionary
                ''    .DataTextField = "Value"
                ''    .DataValueField = "Value"
                ''    .DataBind()
                ''End With



                'Dim lSearchTypes As New Dictionary(Of Integer, String)
                'lSearchTypes.Add(0, "")
                'lSearchTypes.Add(1, "SUPPORT")
                'lSearchTypes.Add(3, "HR")
                'lSearchTypes.Add(5, "HR-EEO")
                'lSearchTypes.Add(6, "TELEPHONE")
                'With SearchTypeDropDownList
                '    .DataSource = lSearchTypes
                '    .DataTextField = "Value"
                '    .DataValueField = "Value"
                '    .DataBind()
                'End With




            Catch ex As Exception
                Session.Item("errorMessage") = ex.Message
                Response.Redirect("DisplayError.aspx")
            End Try
        End If



    End Sub

  Protected Sub cancelNewContentButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cancelNewContentButton.Click

    ' set the state of the controls
    userControlIDDropDownList.Enabled = True
    ownerTypeIDDropDownList.Enabled = True
    ownerIDTextBox.Enabled = True
    contentLabel.Visible = False
    contentIDLabel.Visible = False
    FCKeditor.Visible = False
    submitButton.Visible = False
    createNewContentLabel.Visible = False
    createNewContentButton.Visible = False
    cancelNewContentButton.Visible = False

  End Sub

  Protected Sub createNewContentButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles createNewContentButton.Click

    Try
      ' get the content parameters
      Dim userControlID As String = userControlIDDropDownList.SelectedValue
      Dim ownerTypeID As Integer = ownerTypeIDDropDownList.SelectedValue
      Dim ownerID As String = ownerIDTextBox.Text.Trim()

      ' validate them (TODO)

      ' add the content item
      AddContentItem(userControlID, ownerTypeID, ownerID, userControlID + " content")

      ' retrieve it
      ProcessFind(userControlID, ownerTypeID, ownerID)

    Catch ex As Exception
      Session.Item("errorMessage") = ex.Message
      Response.Redirect("DisplayError.aspx")
    End Try

  End Sub

  Protected Sub findButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles findButton.Click

        SearchResultDisplayableCheckBox.Checked = False
    versionNameTextBox.Text = ""


        ' get the search parameters
        Dim userControlID As String = userControlIDDropDownList.SelectedValue
        Dim ownerTypeID As Integer = ownerTypeIDDropDownList.SelectedValue
        Dim ownerID As String = ownerIDTextBox.SelectedItem.Value

    ' validate them (TODO)

    Try
      ProcessFind(userControlID, ownerTypeID, ownerID)
    Catch ex As Exception
      Session.Item("errorMessage") = ex.Message
      Response.Redirect("DisplayError.aspx")
    End Try

  End Sub

  Protected Sub organizationUnitTreeView_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs)

    selectedUnitLabel.Text = "(" + organizationUnitTreeView.SelectedNode.Text + ")"
    Dim organizationUnitID As String = organizationUnitTreeView.SelectedNode.Value

    Try
      'Dim CMSContentManager As RemotingClient.CMSContentManager = RemotingClient.CMSContentManager.Instance

      ' set the organizational unit
      'CMSContentManager.Instance.SetOrganization(organizationUnitID)
    Catch ex As Exception
      Session.Item("errorMessage") = ex.Message
      Response.Redirect("DisplayError.aspx")
    End Try

  End Sub

  Protected Sub scheduleDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles scheduleDropDownList.SelectedIndexChanged

    Dim versionID As Integer = CInt(versionDropDownList.SelectedValue)
    Dim scheduleID As Integer = CInt(scheduleDropDownList.SelectedValue)

    Try
      ProcessScheduleSelection(versionID, scheduleID)
    Catch ex As Exception
      Session.Item("errorMessage") = ex.Message
      Response.Redirect("DisplayError.aspx")
    End Try

  End Sub

  Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click

        Dim versionID As Integer = CInt(versionDropDownList.SelectedValue)
        Dim content As String = FCKeditor.Value

        Dim VersionName As String = ""
        Dim SearchResultDisplayable As Boolean = False

        If versionNameTextBox.Text.Trim() <> "" Then
            VersionName = versionNameTextBox.Text.Trim()
        End If

        If SearchResultDisplayableCheckBox.Checked = True Then
            SearchResultDisplayable = True
        End If

        'If SearchTypeDropDownList.SelectedValue.ToString() <> "0" Then
        '    SearchResultDisplayable = CType(SearchTypeDropDownList.SelectedValue.ToString(), Integer)
        'End If


        Try
            Dim retVal As String = String.Empty
            If Not Me.submitButton.Text.ToLower() = "force submit" Then
                retVal = ParseHTML(content)
            Else
                Me.submitButton.Text = "Submit for Approval"
            End If

            If retVal = String.Empty Then
                lblErrorMsg.Visible = False
                ProcessSubmit(versionID, content, VersionName, SearchResultDisplayable, ddlTemplate.SelectedValue, ddlTemplate.Items(ddlTemplate.SelectedIndex).Text)
                GridView1.DataBind()
            Else
                Me.submitButton.Text = "Force Submit"
                Me.btnClearForceSubmit.Visible = True
                lblErrorMsg.Visible = True
                lblErrorMsg.Text = retVal
            End If
        Catch ex As Exception
            Session.Item("errorMessage") = ex.Message
            Response.Redirect("DisplayError.aspx")
        End Try

  End Sub

  Protected Sub versionDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles versionDropDownList.SelectedIndexChanged

    Dim versionID As Integer = CInt(versionDropDownList.SelectedValue)

    Try
      ProcessVersionSelection(versionID)
    Catch ex As Exception
      Session.Item("errorMessage") = ex.Message
      Response.Redirect("DisplayError.aspx")
    End Try

  End Sub

    Private Function ParseHTML(ByVal HTMLtext As String) As String
        Dim xmlobj As New XmlDataDocument
        Try
            HTMLtext = Replace(HTMLtext, "&", "")
            xmlobj.LoadXml(HTMLtext)
            'If InStr(HTMLtext.ToUpper(), "<SCRIPT") > 0 Then
            '    Throw New Exception("Scripts are not allowed")
            'End If
            Return String.Empty
        Catch ex As Exception
            Return "<br>Content failed to parse through due to : " & ex.Message & "<BR> Please correct and submit again.<br>If you are sure this content is acceptable, click force submit to submit anyways."
        Finally
            xmlobj = Nothing
        End Try
    End Function



    Protected Sub ddlTemplate_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlTemplate.SelectedIndexChanged

        Dim obj As Object = ddlTemplate.SelectedValue
        Dim templateId As Int32 = Int32.Parse(obj)
        ViewState.Add("templateid", templateId)
        Dim tempxml As Object = Session("template" & templateId)
        Dim contentInfo As XmlNode = Nothing

        Dim _providermanager As ContentProvider.ProviderManager = New ContentProvider.ProviderManager()
        Dim xml As String = _providermanager.GetTemplateContent(templateId)
        Dim xdoc As XmlDocument = New XmlDocument
        xdoc.LoadXml(xml)
        Session("template" & templateId) = xdoc.DocumentElement
        contentInfo = xdoc.DocumentElement

        '# load header information
        txtTitleText.Text = contentInfo("Header").Attributes("Title").Value
        tblAddMeta.Visible = False

'       load meta list for the given template
        txtMetaList.Items.Clear()
        For Each meta As XmlNode In contentInfo("Header")("Metas").ChildNodes
            Me.txtMetaList.Items.Add(New ListItem(meta.Attributes("Alias").Value, meta.Attributes("ID").Value))
        Next

        'refresh onerid list
        Me.userControlIDDropDownList.DataBind()
        Dim ownertypeid As Int32 = Int32.Parse(ownerTypeIDDropDownList.SelectedItem.Value)
        Dim usercontrolname As String = Me.userControlIDDropDownList.SelectedItem.Value

        Dim corgTA As DALTableAdapters.Content_OrganizationTableAdapter = New DALTableAdapters.Content_OrganizationTableAdapter()
        Dim corgTable As DAL.Content_OrganizationDataTable = corgTA.GetData(ownertypeid, usercontrolname)

        Me.ownerIDTextBox.Items.Clear()
        For Each owneridrow As DAL.Content_OrganizationRow In corgTable
            Me.ownerIDTextBox.Items.Add(New ListItem(owneridrow.ownerid, owneridrow.ownerid))
        Next
    End Sub

    Protected Sub btnAddMeta_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddMeta.Click
        tblAddMeta.Visible = True
        txtMetaName.Text = ""
        txtMetaContent.Text = ""
        txtMetaAlias.Text = ""
        Me.btnSaveMeta.Text = "Save Meta"
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim templateAdapter As DALTableAdapters.TemplateTableAdapter = New DALTableAdapters.TemplateTableAdapter
        Dim templateTable As DAL.TemplateDataTable = templateAdapter.GetData()

        'get templateid
        Dim temp As Object = ViewState("templateid")
        Dim templateid As Int32 = Int32.Parse(temp)

        If templateid > 0 Then
            Dim row As DAL.TemplateRow = templateTable.FindByTemplateID(templateid)
            row.HeaderTitle = Me.txtTitleText.Text
            templateAdapter.Update(row)
        Else
            lblErrorMessage.Visible = True
            lblErrorMessage.Text = "Cannot add meta tags to default template"
        End If



    End Sub

    Protected Sub txtMetaList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMetaList.SelectedIndexChanged
'       metatable here is set in the page load
        Dim row As DAL.HtmlMetaRow = metaTable.FindByMetaID(Int32.Parse(txtMetaList.SelectedItem.Value))

        tblAddMeta.Visible = True

'       populate meta fields from database
        txtMetaName.Text = row.MetaName
        txtMetaAlias.Text = row.MetaAlias
        txtMetaContent.Text = row.MetaContent

'       only global meta list emtries can be updated.  this list is for meta entries for a given template and is immutable
        Me.btnSaveMeta.Text = "Close"

    End Sub

    Protected Sub btnSaveMeta_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveMeta.Click
        If btnSaveMeta.Text.ToLower() = "save meta" Then


            Dim metaAdapter As DALTableAdapters.HtmlMetaTableAdapter = New DALTableAdapters.HtmlMetaTableAdapter
            metaAdapter.Insert(txtMetaAlias.Text, txtMetaName.Text, txtMetaContent.Text, Me.CurrentUserID, DateTime.Now)
    '       
    '       clear meta fields and hide area
            txtMetaName.Text = ""
            txtMetaContent.Text = ""
            txtMetaAlias.Text = ""
            Me.tblAddMeta.Visible = False


    '       retrieve metas from the table and reload the list (after clearing it of course)
            metaTable = metaAdapter.GetData()
            txtGlobalMetaList.Items.Clear()
            For Each row As DAL.HtmlMetaRow In metaTable
                txtGlobalMetaList.Items.Add(New ListItem(row.MetaAlias, row.MetaID))
            Next
        ElseIf btnSaveMeta.Text.ToLower() = "close" Then
    '       clear meta fields and hide area
            txtMetaName.Text = ""
            txtMetaContent.Text = ""
            txtMetaAlias.Text = ""
            Me.tblAddMeta.Visible = False
        Else
            Dim metaId As Int32 = Int32.Parse(txtGlobalMetaList.SelectedItem.Value)
            Dim row As DAL.HtmlMetaRow = Me.metaTable.FindByMetaID(metaId)
            row.MetaContent = txtMetaContent.Text
            row.MetaName = txtMetaName.Text
            row.MetaAlias = txtMetaAlias.Text

            Dim metaAdapter As DALTableAdapters.HtmlMetaTableAdapter = New DALTableAdapters.HtmlMetaTableAdapter
            metaAdapter.Update(row)

'           update global meta list
            txtGlobalMetaList.Items.Clear()
            For Each globalrow As DAL.HtmlMetaRow In metaTable
                txtGlobalMetaList.Items.Add(New ListItem(globalrow.MetaAlias, globalrow.MetaID))
            Next

'           update template meta list (the method below is actually the event handler for selectoing a template.
'           since all it does is get the content for a given template and build the meta list based on that I re-use it here
            ddlTemplate_SelectedIndexChanged(Nothing, Nothing)

        End If
    End Sub

    Protected Sub txtGlobalMetaList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtGlobalMetaList.SelectedIndexChanged
        tblAddMeta.Visible = True


'       find the row in the meta table (using the value field of the meta list which in this case is MetaID) and
'       use that to populate the meta fields
        Dim row As DAL.HtmlMetaRow = metaTable.FindByMetaID(Int32.Parse(txtGlobalMetaList.SelectedItem.Value))
        txtMetaAlias.Text = row.MetaAlias
        txtMetaName.Text = row.MetaName
        txtMetaContent.Text = row.MetaContent
        Me.btnSaveMeta.Text = "Update"
    End Sub

    Protected Sub btnRegister_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRegister.Click

'       This function places a given meta selection from the global meta list into a given template's meta list
        If txtGlobalMetaList.SelectedItem Is Nothing Then
            lblErrorMessage.Visible = True
            lblErrorMessage.Text = "Select an item first"
        Else
            Dim temp As Object = ViewState("templateid")
            Dim templateid As Int32 = Int32.Parse(temp)
            If templateid > 0 Then
                Dim templateMeta As DALTableAdapters.Template_HtmlMetaTableAdapter = New DALTableAdapters.Template_HtmlMetaTableAdapter
                templateMeta.Insert(Int32.Parse(temp), Int32.Parse(txtGlobalMetaList.SelectedItem.Value))

                'update template meta list (the method below is actually the event handler for selectoing a template.
    '           since all it does is get the content for a given template and build the meta list based on that I re-use it here
                ddlTemplate_SelectedIndexChanged(Nothing, Nothing)
            Else
                lblErrorMessage.Visible = True
                lblErrorMessage.Text = "Cannot add meta tags to default template"
            End If

        End If
        
        


    End Sub


    Protected Sub btnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        If Me.txtMetaList.SelectedItem Is Nothing Then
            lblErrorMessage.Visible = True
            lblErrorMessage.Text = "Select an item first"
        Else
            Dim temp As Object = ViewState("templateid")
            Dim templateid As Int32 = Int32.Parse(temp)
            If templateid > 0 Then
                Dim metaId As Int32 = Int32.Parse(txtMetaList.SelectedItem.Value)
                Dim templateMeta As DALTableAdapters.Template_HtmlMetaTableAdapter = New DALTableAdapters.Template_HtmlMetaTableAdapter
                templateMeta.Delete(templateid, metaId)


                'update template meta list (the method below is actually the event handler for selectoing a template.
    '           since all it does is get the content for a given template and build the meta list based on that I re-use it here
                ddlTemplate_SelectedIndexChanged(Nothing, Nothing)

            Else
                lblErrorMessage.Visible = True
                lblErrorMessage.Text = "Cannot remove meta tags from default template"
            End If
        End If


        
    End Sub

    Protected Sub btnCreateTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateTemplate.Click
        Me.tblCreateTemplate.Visible = True
    End Sub

    Protected Sub btnSaveTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveTemplate.Click
        Dim templateAdapter As DALTableAdapters.TemplateTableAdapter = New DALTableAdapters.TemplateTableAdapter
        templateAdapter.Insert(txtTemplateName.Text, Me.txtTemplateHeaderTitle.Text, Me.txtTemplateLiveURL.Text, DateTime.Now, Me.CurrentUserID)
        txtTemplateName.Text = ""
        txtTemplateHeaderTitle.Text = ""
        txtTemplateLiveURL.Text = ""
        tblCreateTemplate.Visible = False

    End Sub

    Protected Sub btnCancelCreateTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelCreateTemplate.Click
        tblCreateTemplate.Visible = False
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
         If txtGlobalMetaList.SelectedItem Is Nothing Then
            lblErrorMessage.Visible = True
            lblErrorMessage.Text = "Select an item first"
        Else
            Dim metaId As Int32 = Int32.Parse(txtGlobalMetaList.SelectedItem.Value)
            Dim deleteTA As DALTableAdapters.DeleteGlobalMetaEntryTableAdapter = New DALTableAdapters.DeleteGlobalMetaEntryTableAdapter
            Dim deleteTable As DAL.DeleteGlobalMetaEntryDataTable = deleteTA.GetData(metaId)

            txtGlobalMetaList.Items.Clear()
            For Each row As DAL.DeleteGlobalMetaEntryRow In deleteTable
                txtGlobalMetaList.Items.Add(New ListItem(row.MetaAlias, row.MetaID))
            Next

             'update template meta list (the method below is actually the event handler for selectoing a template.
    '         since all it does is get the content for a given template and build the meta list based on that I re-use it here
             ddlTemplate_SelectedIndexChanged(Nothing, Nothing)
        End If

      

    End Sub

    Protected Sub btnClearForceSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClearForceSubmit.Click
        Me.submitButton.Text = "Submit for Approval"
    End Sub

    Protected Sub ownerTypeIDDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ownerTypeIDDropDownList.SelectedIndexChanged
        Dim ownertypeid As Int32 = Int32.Parse(ownerTypeIDDropDownList.SelectedItem.Value)
        Dim usercontrolname As String = Me.userControlIDDropDownList.SelectedItem.Value

        Dim corgTA As DALTableAdapters.Content_OrganizationTableAdapter = New DALTableAdapters.Content_OrganizationTableAdapter()
        Dim corgTable As DAL.Content_OrganizationDataTable = corgTA.GetData(ownertypeid, usercontrolname)

        Me.ownerIDTextBox.Items.Clear()
        For Each owneridrow As DAL.Content_OrganizationRow In corgTable
            Me.ownerIDTextBox.Items.Add(New ListItem(owneridrow.ownerid, owneridrow.ownerid))
        Next

    End Sub

    Protected Sub userControlIDDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles userControlIDDropDownList.SelectedIndexChanged
        Dim ownertypeid As Int32 = Int32.Parse(ownerTypeIDDropDownList.SelectedItem.Value)
        Dim usercontrolname As String = Me.userControlIDDropDownList.SelectedItem.Value

        Dim corgTA As DALTableAdapters.Content_OrganizationTableAdapter = New DALTableAdapters.Content_OrganizationTableAdapter()
        Dim corgTable As DAL.Content_OrganizationDataTable = corgTA.GetData(ownertypeid, usercontrolname)

        Me.ownerIDTextBox.Items.Clear()
        For Each owneridrow As DAL.Content_OrganizationRow In corgTable
            Me.ownerIDTextBox.Items.Add(New ListItem(owneridrow.ownerid, owneridrow.ownerid))
        Next
    End Sub
End Class
