Imports System.Globalization
Imports Microsoft.Office.Interop

Public Class frmDienstplanATILLA
    Private isDrawn As Boolean = False
    Public niederlassung = ""
    Private blueBrush As New SolidBrush(Color.LightBlue)
    Private greenBrush As New SolidBrush(Color.LightGreen)
    Private f_black As New Font("Arial", 8)
    Private f_black_bold As New Font("Arial", 8, FontStyle.Bold)
    Private stift As New Pen(Color.Gray, 1)
    Private stift2 As New Pen(Color.LightGray, 2)
    Private scr_left As Integer = 200
    Private scr_top As Integer = 50
    Dim week() As String = {"SO", "MO", "DI", "MI", "DO", "FR", "SA"}
    Private SCHICHT = "ROT"
    'Private SCHICHT2 = "1"

    Dim SQLDienst As New cDienstplan
    Dim ListMA As New List(Of cMAShort)
    Dim MA As New cDienstMA
    Dim DienstDetails As List(Of cDienstDetails)
    Dim DGV As New List(Of cDienstDGV)
    Dim aktDate As Date = Now
    Dim aktWoche As Integer = 0
    Dim aktJahr As Integer = 1900
    Dim aktMitarbeiterEintrag As String 'ID des Eintrages des aktuell ausgewählen MA

    Dim markId As Integer = -1
    Sub New()
        InitializeComponent()
    End Sub
    Sub New(niederlassung)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        Me.niederlassung = niederlassung
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub
    Sub fillCboQS()
        cboQSSpaet.Items.Clear()
        Dim ListMA As New List(Of cDienstMA)
        ListMA = SQLDienst.getAllDienstMA(niederlassung, CalendarWeek(aktWoche, aktJahr)) ', " AND dstma_abteilung = 'QS' ")
        For Each m In ListMA
            cboQSSpaet.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(m.dstma_kuerzel, m.dstma_id))
        Next
    End Sub

    Public Sub initDienstplan()
        Dim STD_LIST = cDienstMitarbAbweichendeWochenstunden.GET_STD_LIST(CalendarWeek(aktWoche, aktJahr))

        Dim pf As New cProgramFunctions
        pf.KWAbschluss(STD_LIST, niederlassung, aktJahr, aktWoche, SCHICHT)
        '  initDienstplan()

        If pnl.Controls.Count > 0 Then DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).loaded = False
        DienstDetails = SQLDienst.getAllDienstDetails(niederlassung)
        fillCboQS()

        'Button14.Visible = Not SQLDienst.existsEntryKWUeberstd(niederlassung, aktJahr, aktWoche)
        If Not SQLDienst.existsEntryKWUeberstd(niederlassung, aktJahr, aktWoche) Then
            Button14.Text = "Woche erneut abschließen"
        Else
            Button14.Text = "Woche abschließen"
        End If

        Dim datum As Date = CalendarWeek(aktWoche, aktJahr)

        Dim arrZoll1 As String() = {"dgvZoll1_Mo", "dgvZoll1_Di", "dgvZoll1_Mi", "dgvZoll1_Do", "dgvZoll1_Fr", "dgvZoll1_Sa", "dgvZoll1_So"}
        Dim arrZoll2 As String() = {"dgvZoll2_Mo", "dgvZoll2_Di", "dgvZoll2_Mi", "dgvZoll2_Do", "dgvZoll2_Fr", "dgvZoll2_Sa", "dgvZoll2_So"}
        Dim arrZollTag As String() = {"dgvZollTag_Mo", "dgvZollTag_Di", "dgvZollTag_Mi", "dgvZollTag_Do", "dgvZollTag_Fr", "dgvZollTag_Sa", "dgvZollTag_So"}
        Dim arrNACHT As String() = {"dgvNACHT_Mo", "dgvNACHT_Di", "dgvNACHT_Mi", "dgvNACHT_Do", "dgvNACHT_Fr", "dgvNACHT_Sa", "dgvNACHT_So"}
        Dim arrKS As String() = {"dgvKS_Mo", "dgvKS_Di", "dgvKS_Mi", "dgvKS_Do", "dgvKS_Fr", "dgvKS_Sa", "dgvKS_So"}
        Dim arrUrl As String() = {"dgvUrl_Mo", "dgvUrl_Di", "dgvUrl_Mi", "dgvUrl_Do", "dgvUrl_Fr", "dgvUrl_Sa", "dgvUrl_So"}
        Dim arrDR As String() = {"dgvDR_Mo", "dgvDR_Di", "dgvDR_Mi", "dgvDR_Do", "dgvDR_Fr", "dgvDR_Sa", "dgvDR_So"}
        Dim arrFrei As String() = {"dgvFrei_Mo", "dgvFrei_Di", "dgvFrei_Mi", "dgvFrei_Do", "dgvFrei_Fr", "dgvFrei_Sa", "dgvFrei_So"}
        Dim arrZA As String() = {"dgvZA_Mo", "dgvZA_Di", "dgvZA_Mi", "dgvZA_Do", "dgvZA_Fr", "dgvZA_Sa", "dgvZA_So"}
        DGV.Clear()
        For i = 0 To 6
            Dim andstr As String = " AND dstetr_datum='" & datum.ToShortDateString & "' AND dstetr_dstmaId=dstma_id AND mit_id=dstma_mitId "
            andstr &= " AND dstetr_niederlassung='" & niederlassung & "'"

            Dim orderBy As String = " ORDER BY dstma_reihenfolge ASC, dstma_kuerzel ASC "
            Dim orderBy2 As String = " ORDER BY dstma_kuerzel ASC "

            getDGV(arrZoll1(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id, dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE (dstetr_art='ZOLL_VM' or dstetr_art='DBL') " & andstr & orderBy)
            DGV.Add(New cDienstDGV(arrZoll1(i), datum, "ZOLL_VM")) ', getDienstDetails("ZOLL1", "von"), getDienstDetails("ZOLL1", "bis")))

            getDGV(arrZoll2(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE (dstetr_art='ZOLL_NM' or dstetr_art='DBL') " & andstr & orderBy)
            DGV.Add(New cDienstDGV(arrZoll2(i), datum, "ZOLL_NM")) ', getDienstDetails("ZOLL2", "von"), getDienstDetails("ZOLL2", "bis")))

            getDGV(arrZollTag(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE dstetr_art='ZOLL_TAG'  " & andstr & orderBy)
            DGV.Add(New cDienstDGV(arrZollTag(i), datum, "ZOLL_TAG")) ', getDienstDetails("ZOLL_TAG", "von"), getDienstDetails("ZOLL_TAG", "bis")))

            getDGV(arrNACHT(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE dstetr_art='NACHT'" & andstr & orderBy)
            DGV.Add(New cDienstDGV(arrNACHT(i), datum, "NACHT")) ', getDienstDetails("NACHT", "von"), getDienstDetails("NACHT", "bis")))

            getDGV(arrUrl(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE dstetr_art='URL'" & andstr & orderBy2)
            DGV.Add(New cDienstDGV(arrUrl(i), datum, "URL")) ', getDienstDetails("URL", "von"), getDienstDetails("URL", "bis")))

            getDGV(arrKS(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE dstetr_art='KS'" & andstr & orderBy2)
            DGV.Add(New cDienstDGV(arrKS(i), datum, "KS")) ', getDienstDetails("KS", "von"), getDienstDetails("KS", "bis")))

            getDGV(arrDR(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE (dstetr_art='DR' OR dstetr_art='BS')" & andstr & orderBy2)
            DGV.Add(New cDienstDGV(arrDR(i), datum, "DR")) ', getDienstDetails("DR", "von"), getDienstDetails("DR", "bis")))

            getDGV(arrFrei(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE dstetr_art='FREI'" & andstr & orderBy2)
            DGV.Add(New cDienstDGV(arrFrei(i), datum, "FREI")) ', getDienstDetails("FREI", "von"), getDienstDetails("FREI", "bis")))

            getDGV(arrZA(i)).DataSource = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info,dstma_id,dstma_arbvh, dstetr_von,dstetr_bis,dstma_stammSchicht, dstetr_info,dstma_reihenfolge, dstma_farbe,dstetr_pause FROM tblDienstplanEintraege,tblDienstMitarb,tblMitarbeiter WHERE dstetr_art='ZA'" & andstr & orderBy2)
            DGV.Add(New cDienstDGV(arrZA(i), datum, "ZA")) ', getDienstDetails("ZA", "von"), getDienstDetails("ZA", "bis")))


            datum = datum.AddDays(1)
        Next
        '  MsgBox("t5")

        initDGVVerhalten()
        initStdMa()

        clearAllSelection()
        initAusslastung()
        initAnzahl()
        initDetails(True)

        If markId > 0 Then
            markNamesinDGV(markId)
        End If
        If pnl.Controls.Count > 0 Then DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).loaded = True

    End Sub

    Sub initStdMa()
        Dim usrcntl As New usrcntlDienstplanStunden(aktWoche, aktJahr, niederlassung, SCHICHT)
        '  usrcntl.initStdMa()
        pnl.Controls.Clear()
        pnl.Controls.Add(usrcntl)
        AddHandler usrcntl.NAME_CHANGED, Sub(id)
                                             markNamesinDGV(id)
                                         End Sub
        DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).initStdMa()
    End Sub


    Private Sub frmDienstplan_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.PageDown) Then
            Button7.PerformClick()
        End If
        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.PageUp) Then
            Button6.PerformClick()
        End If
    End Sub

    Sub initAnzahl()
        lblAnzZoll1_Mo.Text = dgvZoll1_Mo.RowCount
        lblAnzZoll1_Di.Text = dgvZoll1_Di.RowCount
        lblAnzZoll1_Mi.Text = dgvZoll1_Mi.RowCount
        lblAnzZoll1_Do.Text = dgvZoll1_Do.RowCount
        lblAnzZoll1_Fr.Text = dgvZoll1_Fr.RowCount
        lblAnzZoll1_Sa.Text = dgvZoll1_Sa.RowCount
        lblAnzZoll1_So.Text = dgvZoll1_So.RowCount

        lblAnzZoll2_Mo.Text = dgvZoll2_Mo.RowCount
        lblAnzZoll2_Di.Text = dgvZoll2_Di.RowCount
        lblAnzZoll2_Mi.Text = dgvZoll2_Mi.RowCount
        lblAnzZoll2_Do.Text = dgvZoll2_Do.RowCount
        lblAnzZoll2_Fr.Text = dgvZoll2_Fr.RowCount
        lblAnzZoll2_Sa.Text = dgvZoll2_Sa.RowCount
        lblAnzZoll2_So.Text = dgvZoll2_So.RowCount

        lblAnzZollTag_Mo.Text = dgvZollTag_Mo.RowCount
        lblAnzZollTag_Di.Text = dgvZollTag_Di.RowCount
        lblAnzZollTag_Mi.Text = dgvZollTag_Mi.RowCount
        lblAnzZollTag_Do.Text = dgvZollTag_Do.RowCount
        lblAnzZollTag_Fr.Text = dgvZollTag_Fr.RowCount
        lblAnzZollTag_Sa.Text = dgvZollTag_Sa.RowCount
        lblAnzZollTag_So.Text = dgvZollTag_So.RowCount

        lblAnzQS_Mo.Text = dgvNACHT_Mo.RowCount
        lblAnzQS_Di.Text = dgvNACHT_Di.RowCount
        lblAnzQS_Mi.Text = dgvNACHT_Mi.RowCount
        lblAnzQS_Do.Text = dgvNACHT_Do.RowCount
        lblAnzQS_Fr.Text = dgvNACHT_Fr.RowCount
        lblAnzQS_Sa.Text = dgvNACHT_Sa.RowCount
        lblAnzQS_So.Text = dgvNACHT_So.RowCount

    End Sub


    Sub initAusslastung()
        Dim maxMaZoll As Integer = 18
        Dim maxMaQS As Integer = 11

        lblAuslastMaZoll_Mo.Text = CInt((dgvZoll1_Mo.RowCount + dgvZoll2_Mo.RowCount + dgvZollTag_Mo.RowCount) / (maxMaZoll / 100)) & " %"
        lblAuslastMaZoll_Di.Text = CInt((dgvZoll1_Di.RowCount + dgvZoll2_Di.RowCount + dgvZollTag_Di.RowCount) / (maxMaZoll / 100)) & " %"
        lblAuslastMaZoll_Mi.Text = CInt((dgvZoll1_Mi.RowCount + dgvZoll2_Mi.RowCount + dgvZollTag_Mi.RowCount) / (maxMaZoll / 100)) & " %"
        lblAuslastMaZoll_Do.Text = CInt((dgvZoll1_Do.RowCount + dgvZoll2_Do.RowCount + dgvZollTag_Do.RowCount) / (maxMaZoll / 100)) & " %"
        lblAuslastMaZoll_Fr.Text = CInt((dgvZoll1_Fr.RowCount + dgvZoll2_Fr.RowCount + dgvZollTag_Fr.RowCount) / (maxMaZoll / 100)) & " %"
        lblAuslastMaZoll_Sa.Text = CInt((dgvZoll1_Sa.RowCount + dgvZoll2_Sa.RowCount + dgvZollTag_Sa.RowCount) / (maxMaZoll / 100)) & " %"
        lblAuslastMaZoll_So.Text = CInt((dgvZoll1_So.RowCount + dgvZoll2_So.RowCount + dgvZollTag_So.RowCount) / (maxMaZoll / 100)) & " %"

        lblAuslastMaQS_Mo.Text = CInt(dgvNACHT_Mo.RowCount / (maxMaQS / 100)) & " %"
        lblAuslastMaQS_Di.Text = CInt(dgvNACHT_Di.RowCount / (maxMaQS / 100)) & " %"
        lblAuslastMaQS_Mi.Text = CInt(dgvNACHT_Mi.RowCount / (maxMaQS / 100)) & " %"
        lblAuslastMaQS_Do.Text = CInt(dgvNACHT_Do.RowCount / (maxMaQS / 100)) & " %"
        lblAuslastMaQS_Fr.Text = CInt(dgvNACHT_Fr.RowCount / (maxMaQS / 100)) & " %"
        lblAuslastMaQS_Sa.Text = CInt(dgvNACHT_Sa.RowCount / (maxMaQS / 100)) & " %"
        lblAuslastMaQS_So.Text = CInt(dgvNACHT_So.RowCount / (maxMaQS / 100)) & " %"

    End Sub


    Function getDGV(s) As DataGridView
        Return DirectCast(Me.Controls.Find(s, True)(0), DataGridView)
    End Function

    Sub initWeekInfo()
        Dim dStart As Date = CalendarWeek(aktWoche, aktJahr)

        Label1.Text = dStart & " - " & dStart.AddDays(6)
        lblKW.Text = "KW " & aktWoche

        If EvenNumber() = False Then
            Panel3.BackColor = Color.Firebrick
            ' Panel4.BackColor = Color.Firebrick
            Label12.ForeColor = Color.White
            Label15.ForeColor = Color.White
            SCHICHT = "ROT"
        Else
            Panel3.BackColor = System.Drawing.Color.FromArgb(0, 60, 120)
            '  Panel4.BackColor = System.Drawing.Color.FromArgb(0, 60, 120)
            Label12.ForeColor = Color.White
            Label15.ForeColor = Color.White
            SCHICHT = "BLAU"
        End If

        If EvenNumber2() = False Then
            SCHICHT &= "1"
        Else
            SCHICHT &= "2"
        End If

        'Private SCHICHT2 = "1"

        Dim datum As Date = dStart
        For i = 0 To 6
            Select Case week(datum.DayOfWeek)
                Case "MO" : lblMo.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
                Case "DI" : lblDi.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
                Case "MI" : lblMi.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
                Case "DO" : lblDo.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
                Case "FR" : lblFr.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
                Case "SA" : lblSa.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
                Case "SO" : lblSo.Text = week(datum.DayOfWeek) & " " & datum.ToShortDateString
            End Select
            datum = datum.AddDays(1)
        Next


    End Sub

    Public Function EvenNumber() As Boolean
        Dim RefDate As Date = CDate("01.08.2015")
        Dim wD As Long = DateDiff(DateInterval.Weekday, aktDate, RefDate)
        EvenNumber = (wD And 1&) = 0&
    End Function

    Public Function EvenNumber2() As Boolean
        Dim RefDate As Date = CDate("01.08.2015")
        Dim wD As Long = DateDiff(DateInterval.Weekday, aktDate, RefDate)
        EvenNumber2 = (wD And 2&) = 0&
    End Function

    Private Sub frmDienstplan_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.Cursor = Cursors.WaitCursor
        txtKWYear.Text = Now.Year
        aktWoche = DateToWeek(aktDate).Substring(4, 2)
        aktJahr = DateToWeek(aktDate).Substring(0, 4)

        For Each c In Panel1.Controls
            If TypeOf c Is DataGridView Then
                DirectCast(c, DataGridView).RowTemplate.Height = 15
            End If
        Next
        For Each c In Panel3.Controls
            If TypeOf c Is DataGridView Then
                DirectCast(c, DataGridView).RowTemplate.Height = 15
            End If
        Next
        For Each c In Panel4.Controls
            If TypeOf c Is DataGridView Then
                DirectCast(c, DataGridView).RowTemplate.Height = 15
            End If
        Next

        initWeekInfo()
        initDienstplan()
        '   Dim l As New List(Of Control)
        ' l.Add(Panel3.Controls)

        Me.Cursor = Cursors.Default

    End Sub
    Sub initDGVVerhalten()
        Try
            For Each datagridview As cDienstDGV In DGV
                Dim d As DataGridView = getDGV(datagridview.dgvName)
                AddHandler d.MouseDown, AddressOf handleDGVContextMenue
                AddHandler d.LostFocus, AddressOf remHandlerKey
                AddHandler d.MouseClick, AddressOf handleDGVClick

                If False Then ' d.ColumnCount = 0 Then
                    Dim col As New DataGridViewTextBoxColumn
                    col.DataPropertyName = "dstetr_id"
                    col.HeaderText = "dstetr_id"
                    col.Name = "dstetr_id"
                    d.Columns.Add(col)

                    Dim col2 As New DataGridViewTextBoxColumn
                    col2.DataPropertyName = "Name"
                    col2.HeaderText = "Name"
                    col2.Name = "Name"
                    d.Columns.Add(col2)

                End If
                For Each r As DataGridViewRow In d.Rows
                    ' MsgBox(r.Cells(1).Value)
                    If r.Cells(6).Value = "ZOLL1" Then r.Cells(1).Style.BackColor = System.Drawing.Color.FromArgb(255, 230, 230)
                    If r.Cells(6).Value = "ZOLL2" Then r.Cells(1).Style.BackColor = System.Drawing.Color.FromArgb(230, 255, 255)
                    If r.Cells(6).Value = "NACHT" Then r.Cells(1).Style.BackColor = System.Drawing.Color.FromArgb(255, 255, 230)
                    If r.Cells(6).Value = "" Then r.Cells(1).Style.BackColor = System.Drawing.Color.FromArgb(255, 255, 255)
                Next
                setDGV(d)
                '  AddHandler d.DragDrop, AddressOf dgv_DragDrop
                '  AddHandler d.DragEnter, AddressOf dgv_DragEnter
                AddHandler d.Leave, AddressOf dgv_clearSelection
                d.Columns(1).Width = d.Width - 20

            Next
        Catch ex As Exception
            MsgBox("initDGVVerhalten-Error: " & ex.Message)
        End Try

    End Sub
    Sub setDGV(dgv As DataGridView)

        With dgv
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowHeadersVisible = False
            .ColumnHeadersVisible = False

            .RowTemplate.Height = 15

            If .ColumnCount > 0 Then .Columns(0).Visible = False
            If .ColumnCount > 2 Then
                For i = 2 To .ColumnCount - 1
                    .Columns(i).Visible = False
                Next
            End If
        End With
        initDGV(dgv)
    End Sub
    Sub initDGV(dgv As DataGridView)
        For Each r As DataGridViewRow In dgv.Rows
            If r.Cells(3).Value = "TZ" Then
                '  r.Cells(1).Style.ForeColor = Color.Blue
                r.Cells(1).Style.ForeColor = ColorTranslator.FromHtml(r.Cells(9).Value)
            End If
        Next
    End Sub
    Sub clearAllSelection()
        markId = -1
        For Each datagridview As cDienstDGV In dgv
            Dim dgv As DataGridView = getDGV(datagridview.dgvName)
            dgv.ClearSelection()
            initDGV(dgv)
        Next
        TextBox1.Text = ""
        TextBox2.Text = ""
        TextBox3.Text = ""
        TextBox4.Text = ""
        Button9.Visible = False
        Label32.Text = "-"
        lblMAInfo.Text = "-"
        aktMitarbeiterEintrag = ""

    End Sub
    Function getDienstDetails(abt, s) As String
        For Each d In DienstDetails
            If d.dedet_abt = abt Then
                If s = "von" Then Return d.dedet_von
                If s = "bis" Then Return d.dedet_bis
                If s = "pause" Then Return d.dedet_pause
            End If
        Next
        Return ""
    End Function

    Private Sub PaintLeft(e As PaintEventArgs)

        '  If Not isDrawn Then
        isDrawn = True
        Dim z As Graphics
        z = e.Graphics
        z.Clear(Color.White)
        ' Dim f_red As New Font("Arial", 8)

        Dim myDT As DateTime = DateTime.Now

        Dim myCal As Calendar = CultureInfo.InvariantCulture.Calendar

        Dim lastMonth As DateTime = myCal.AddMonths(myDT, -1)
        Dim nextMonth As DateTime = myCal.AddMonths(myDT, 1)

        Dim dayOWeak As Array = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}
        Dim monthOYear As Array = {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}
        Dim Mitarbeiter As Array = {"Luxbauer Johann", "Siener Josef", "Luxbauer Andreas"}

        Dim format As New StringFormat(StringFormatFlags.DirectionRightToLeft)
        Dim cnt_mitarb As Integer = 0
        For Each m In Mitarbeiter
            z.DrawString(m, f_black, Brushes.Black, New Rectangle(20, scr_top + 5 + (cnt_mitarb * 20), 160, 20), format)
            cnt_mitarb += 1
        Next
        z.DrawString("", f_black, Brushes.Black, New Rectangle(20, scr_top + 25, 160, 20), format)


    End Sub

    Public Function DateToWeek(ByVal dDate As Date) As String
        ' Startdatum der ersten Kalenderwoche des Jahres und Folgejahres berechnen
        Dim dThisYear As Date = CalendarWeek(1, dDate.Year)
        Dim dNextYear As Date = CalendarWeek(1, dDate.Year + 1)

        ' Prüfen, ob Datum zur ersten Woche des Folgejahres gehört
        If dDate >= dNextYear Then
            ' Rückgabe: KW 1 des Folgejahres
            Return dDate.Year + 1 & "01"
        ElseIf dDate < dThisYear Then
            ' Falls das Datum noch zu einer KW aus dem letzten Jahr zählt
            Return dDate.Year - 1 & DatePart(DateInterval.WeekOfYear, _
              New Date(dDate.Year - 1, 12, 28), FirstDayOfWeek.Monday, _
              FirstWeekOfYear.FirstFourDays)
        Else
            ' KW = Differenz zum ersten Tag der ersten Woche
            Return dDate.Year & Format$(dDate.Subtract(dThisYear).Days \ 7 + 1, "00")
        End If
    End Function

    Public Function CalendarWeek(ByVal nWeek As Integer, _
  ByVal nYear As Integer) As Date

        ' Wochentag des 4. Januar des Jahres ermitteln
        Dim dStart As New Date(nYear, 1, 4)
        Dim nDay As Integer = (dStart.DayOfWeek + 6) Mod 7 + 1

        ' Beginn der 1. KW des Jahres
        Dim dFirst As Date = dStart.AddDays(1 - nDay)

        ' Gesuchte KW ermitteln
        Return dFirst.AddDays((nWeek - 1) * 7)
    End Function
    Private Sub PaintThis(e As PaintEventArgs)

        '  If Not isDrawn Then
        isDrawn = True
        Dim z As Graphics
        z = e.Graphics
        z.Clear(Color.White)
        ' Dim f_red As New Font("Arial", 8)

        Dim myDT As DateTime = DateTime.Now

        Dim myCal As Calendar = CultureInfo.InvariantCulture.Calendar

        Dim lastMonth As DateTime = myCal.AddMonths(myDT, -1)
        Dim nextMonth As DateTime = myCal.AddMonths(myDT, 1)

        Dim dayOWeak As Array = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}
        Dim monthOYear As Array = {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}
        ' Dim Mitarbeiter As Array = {"Luxbauer Johann", "Siener Josef", "Luxbauer Andreas"}

        ' Dim format As New StringFormat(StringFormatFlags.DirectionRightToLeft)
        ' Dim cnt_mitarb As Integer = 0
        ' For Each m In Mitarbeiter
        'z.DrawString(m, f_black, Brushes.Black, New Rectangle(20, scr_top + 5 + (cnt_mitarb * 20), 160, 20), Format)
        ' cnt_mitarb += 1
        ' Next
        ' z.DrawString("", f_black, Brushes.Black, New Rectangle(20, scr_top + 25, 160, 20), Format)

        '  Dim lastMonth As DateTime = myCal.AddMonths(myDT, -1)


        Dim daysLastM As Integer = myCal.GetDaysInMonth(myCal.GetYear(lastMonth), myCal.GetMonth(lastMonth))
        Dim daysThisM As Integer = myCal.GetDaysInMonth(myCal.GetYear(myDT), myCal.GetMonth(myDT))
        Dim daysNextM As Integer = myCal.GetDaysInMonth(myCal.GetYear(nextMonth), myCal.GetMonth(nextMonth))

        Dim greyBrush As New SolidBrush(Color.LightGray)
        z.FillRectangle(greyBrush, scr_left, scr_top - 50, (daysLastM + daysThisM + daysNextM) * 20, 20)

        z.DrawRectangle(stift, scr_left, scr_top - 50, daysLastM * 20, 20) 'Rahmen lastMonth
        z.DrawRectangle(stift, scr_left, scr_top - 50, (daysLastM + daysThisM) * 20, 20) 'Rahmen myCal
        z.DrawRectangle(stift, scr_left, scr_top - 50, (daysLastM + daysThisM + daysNextM) * 20, 20) 'Rahmen nextMonth

        z.DrawString(monthOYear(myCal.GetMonth(lastMonth) - 1), f_black, Brushes.Black, scr_left + daysLastM * 20 / 2, 2)
        z.DrawString(monthOYear(myCal.GetMonth(myDT) - 1), f_black_bold, Brushes.Black, scr_left + daysLastM * 20 + daysThisM * 20 / 2, 2)
        z.DrawString(monthOYear(myCal.GetMonth(nextMonth) - 1), f_black, Brushes.Black, scr_left + daysLastM * 20 + daysThisM * 20 + daysNextM * 20 / 2, 2)

        z.DrawRectangle(stift, 0, 0, 1800 + scr_left, 500 + scr_top) 'Rahmen

        z.FillRectangle(blueBrush, scr_left, scr_top - 30, 90 * 20, 30)
        Dim arrayDays(daysLastM + daysThisM + daysNextM) As Date
        Dim cnt As Integer = 0
        'lastMonth zeichnen:
        For i As Integer = 0 To daysLastM - 1
            z.DrawRectangle(stift, scr_left + i * 20, scr_top - 30, 20, 30)
            Dim b As Brush : Dim d As New DateTime(myCal.GetYear(lastMonth), myCal.GetMonth(lastMonth), i + 1)
            Dim dow As String = dayOWeak(myCal.GetDayOfWeek(d))
            If dow = "Sa" Or dow = "So" Then b = Brushes.Red Else b = Brushes.Black
            z.DrawString(dow & vbNewLine & (i + 1), f_black, b, scr_left + i * 20, scr_top - 30)
            arrayDays(cnt) = d : cnt += 1
        Next
        'thisMonth zeichnen:
        For i As Integer = 0 To daysThisM - 1
            z.DrawRectangle(stift, scr_left + i * 20, scr_top - 30, 20, 30)
            Dim b As Brush : Dim d As New DateTime(myCal.GetYear(myDT), myCal.GetMonth(myDT), i + 1)
            Dim dow As String = dayOWeak(myCal.GetDayOfWeek(d))
            If dow = "Sa" Or dow = "So" Then b = Brushes.Red Else b = Brushes.Black
            Dim f As Font = f_black : If (i + 1) = myCal.GetDayOfMonth(myDT) Then f = f_black_bold
            z.DrawString(dow & vbNewLine & (i + 1), f, b, scr_left + (daysLastM + i) * 20, scr_top - 30)
            arrayDays(cnt) = d : cnt += 1
        Next
        'nextMonth zeichnen:
        For i As Integer = 0 To daysNextM - 1
            z.DrawRectangle(stift, scr_left + i * 20, scr_top - 30, 20, 30)
            Dim b As Brush : Dim d As New DateTime(myCal.GetYear(nextMonth), myCal.GetMonth(nextMonth), i + 1)
            Dim dow As String = dayOWeak(myCal.GetDayOfWeek(d))
            If dow = "Sa" Or dow = "So" Then b = Brushes.Red Else b = Brushes.Black
            z.DrawString(dow & vbNewLine & (i + 1), f_black, b, scr_left + (daysLastM + daysThisM + i) * 20, scr_top - 30)
            arrayDays(cnt) = d : cnt += 1
        Next



        'Raster zeichnen:
        For j As Integer = 0 To 20
            For i As Integer = 0 To 90
                z.DrawRectangle(stift, scr_left + i * 20, scr_top + j * 20, 20, 20)
            Next
        Next

        insertUrlaub(z, New DateTime(2015, 3, 15), New DateTime(2015, 4, 18), arrayDays, 0)
        insertUrlaub(z, New DateTime(2015, 4, 1), New DateTime(2015, 4, 10), arrayDays, 2)

    End Sub

    Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Paint
        PaintThis(e)
    End Sub
    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Paint
        PaintLeft(e)
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs)
        Panel2.AutoScrollPosition = New Point(Panel2.HorizontalScroll.Value + 20, 0)
    End Sub

    Private Sub insertUrlaub(z As Graphics, startDate As DateTime, endDate As DateTime, arrayDays() As DateTime, Zeile As Integer)
        '  Dim startDate As New DateTime(2015, 3, 15)
        '  Dim endDate As New DateTime(2015, 4, 18)

        Dim x_start As Integer : Dim x_end As Integer
        If arrayDays(arrayDays.Count - 1) < endDate Then x_start = arrayDays.Count * 20 + 20
        If arrayDays(0) > startDate Then x_start = 0
        Dim diff As Integer
        For i As Integer = 0 To arrayDays.Count - 1
            If arrayDays(i) = startDate Then x_start = i * 20 : diff = i
            If arrayDays(i) = endDate Then x_end = (i - diff) * 20 + 20
        Next
        z.FillRectangle(greenBrush, scr_left + x_start, scr_top + (Zeile * 20), x_end, 20)
        z.DrawRectangle(stift, scr_left + x_start, scr_top + (Zeile * 20), x_end, 20)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs)
        Panel2.AutoScrollPosition = New Point(Panel2.HorizontalScroll.Value - 20, 0)
    End Sub


    Private Sub handleDGVClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim thisDgv As DataGridView = DirectCast(sender, DataGridView)
            Dim row As DataGridViewRow = thisDgv.CurrentRow
            setDetails(row.Cells("dstetr_id").Value) 'NULL???????
        Catch ex As Exception
            clearAllSelection()
        End Try
    End Sub
    Public entryId_TMP As Integer = -1
    Sub setDetails(entryId)
        Try
            entryId_TMP = entryId

            Dim row As DataRow = SQLDienst.loadDGV("SELECT dstetr_id,  dstma_kuerzel + ' '+ dstetr_info as dstma_kuerzel,dstetr_info,dstma_id, dstetr_von,dstetr_bis,dstetr_art,dstetr_pause,dstetr_datum FROM  tblDienstplanEintraege, tblDienstMitarb, tblMitarbeiter WHERE dstetr_dstmaId=dstma_id AND mit_id=dstma_mitId AND dstetr_id='" & entryId & "'").Rows(0)

            TextBox1.Text = row("dstetr_von").ToString
            TextBox2.Text = row("dstetr_bis").ToString
            TextBox3.Text = row("dstetr_info").ToString
            TextBox4.Text = row("dstetr_pause").ToString

            Label32.Text = CDate(row("dstetr_datum")).ToShortDateString
            lblMAInfo.Text = row("dstma_kuerzel").ToString
            aktMitarbeiterEintrag = row("dstetr_id").ToString

            '  If row("dstetr_art").ToString.Contains("NACHT") Then Button9.Visible = True


            markNamesinDGV(row("dstma_id").ToString)


            If pnl.Controls.Count > 0 Then
                DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).markrow(row("dstma_id").ToString)
            End If

            '    For Each r In dgvStundenMa.Rows
            'If r.Cells("dstma_id").value = thisDgv.CurrentRow.Cells(2).Value Then
            'r.DefaultCellStyle.Font = New Font(thisDgv.Font, FontStyle.Bold)
            ' End If
            '  Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Sub markNamesinDGV(id)
        markId = id
        '  clearBlackFont()
        If pnl.Controls.Count > 0 Then
            DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).clearRowBg()
            DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).markrow(id)
        End If
        For Each d In DGV
            For Each r As DataGridViewRow In getDGV(d.dgvName).Rows
                If r.Cells(2).Value = id Then
                    'r.Cells(1).Style.Font.Style = FontStyle.Bold
                    Dim style As New DataGridViewCellStyle
                    '  style.Font = New Font(dataGridView1.Font, FontStyle.Bold)
                    r.DefaultCellStyle.Font = New Font(r.DataGridView.Font, FontStyle.Bold)
                Else
                    r.DefaultCellStyle.Font = New Font(r.DataGridView.Font, FontStyle.Regular)
                End If
            Next
        Next

    End Sub


    Private Sub handleDGVContextMenue(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) 'Handles dgvZoll1_Mo.MouseDown

        Dim thisDgv As DataGridView = DirectCast(sender, DataGridView)
        Dim ht As DataGridView.HitTestInfo
        ht = thisDgv.HitTest(e.X, e.Y)

        If ht.Type = DataGridViewHitTestType.Cell Then
            thisDgv.ContextMenuStrip = ctxtDgv
            If thisDgv.SelectedCells.Count = 0 Then
                thisDgv.CurrentCell = thisDgv(ht.ColumnIndex, ht.RowIndex)
                thisDgv.CurrentCell.Selected = True

            End If
        End If

        If e.Button = Windows.Forms.MouseButtons.Right Then
            ' Dim ht As DataGridView.HitTestInfo
            '  ht = thisDgv.HitTest(e.X, e.Y)
            If ht.Type = DataGridViewHitTestType.Cell Then
                thisDgv.ContextMenuStrip = ctxtDgv
                ctiSchicht1.Enabled = True : ctiSchicht2.Enabled = True : ctiDbl.Enabled = True : ctiQS.Enabled = True
                ctiZollTag.Enabled = True : ctiUrlaub.Enabled = True : ctiKrankenstand.Enabled = True : ctiWocheSchichtWechsel.Enabled = False
                Select Case week(CDate((getValuesDienstDGV(thisDgv.Name, "datum"))).DayOfWeek)
                    Case "SO" : ctiSchicht1.Enabled = False : ctiDbl.Enabled = False
                        ctiQS.Enabled = False : ctiZollTag.Enabled = False : ctiUrlaub.Enabled = False : ctiKrankenstand.Enabled = False
                    Case "SA" : ctiDbl.Enabled = False
                        ctiZollTag.Enabled = False : ctiUrlaub.Enabled = False : ctiKrankenstand.Enabled = False ' ctiSchicht2.Enabled = False 
                    Case Else
                        Select Case getValuesDienstDGV(thisDgv.Name, "abt")
                            Case "ZOLL_VM" : ctiWocheSchichtWechsel.Enabled = True
                            Case "ZOLL_NM" : ctiWocheSchichtWechsel.Enabled = True
                            Case Else : ctiWocheSchichtWechsel.Enabled = False
                        End Select
                End Select




                If thisDgv.SelectedCells.Count <= 1 Then
                    thisDgv.CurrentCell = thisDgv(ht.ColumnIndex, ht.RowIndex)
                    thisDgv.CurrentCell.Selected = True
                End If
                ' ctxtDgvSchicht1.Items(0).Text = String.Format("This is the cell at {0}, {1}", ht.ColumnIndex, ht.RowIndex)
            End If
        Else
            RemoveHandler DirectCast(sender, DataGridView).KeyDown, AddressOf changeByKey
            AddHandler thisDgv.KeyDown, AddressOf changeByKey

            'MsgBox(dgv.Name)

            Exit Sub ' kein dragdrop
            Dim info As DataGridView.HitTestInfo = thisDgv.HitTest(e.X, e.Y)
            If info.RowIndex >= 0 Then
                Dim row As DataGridViewRow = thisDgv.Rows(info.RowIndex)
                thisDgv.DoDragDrop(row, DragDropEffects.All)
            End If
        End If
    End Sub

    Sub changeByKey(sender As Object, e As KeyEventArgs)
        Dim dgv As DataGridView = DirectCast(sender, DataGridView)
        If dgv.SelectedCells.Count > 0 Then

            '   Case "SO" : ctiSchicht1.Enabled = False : ctiDbl.Enabled = False : ctiQS.Enabled = False : ctiZollTag.Enabled = False : ctiUrlaub.Enabled = False : ctiKrankenstand.Enabled = False
            '        Case "SA" : ctiSchicht2.Enabled = False : ctiDbl.Enabled = False : ctiZollTag.Enabled = False : ctiUrlaub.Enabled = False : ctiKrankenstand.Enabled = False
            Dim d As Date = CDate(getValuesDienstDGV(dgv.Name, "datum"))
            Select Case week(CDate(getValuesDienstDGV(dgv.Name, "datum")).DayOfWeek)
                Case "SA"
                    Select Case e.KeyCode
                        Case Keys.V : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_VM"))
                        Case Keys.N : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_NM"))
                        Case Keys.Q : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "NACHT"))
                        Case Keys.F : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "FREI"))
                        Case Keys.S : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "DR"))
                    End Select
                Case "SO"
                    Select Case e.KeyCode
                        Case Keys.N : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_NM"))
                        Case Keys.T : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_TAG"))
                        Case Keys.F : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "FREI"))
                        Case Keys.S : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "DR"))
                    End Select
                Case Else
                    Select Case e.KeyCode
                        Case Keys.V : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_VM"))
                        Case Keys.N : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_NM"))
                        Case Keys.T : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZOLL_TAG"))
                        Case Keys.Q : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "NACHT"))
                        Case Keys.U : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "URL"))
                        Case Keys.F : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "FREI"))
                        Case Keys.K : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "KS"))
                        Case Keys.S : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "DR"))
                        Case Keys.Z : changeDGV(dgv, getDgvByDatArt(getValuesDienstDGV(dgv.Name, "datum"), "ZA"))
                    End Select
            End Select

        End If
    End Sub
    Sub remHandlerKey(sender As Object, e As EventArgs)
        RemoveHandler DirectCast(sender, DataGridView).KeyDown, AddressOf changeByKey
    End Sub
    Sub clearBlackFont()
        markId = -1
        For Each d In DGV
            For Each r As DataGridViewRow In getDGV(d.dgvName).Rows
                r.DefaultCellStyle.Font = New Font(r.DataGridView.Font, FontStyle.Regular)
            Next
        Next
        If pnl.Controls.Count > 0 Then
            DirectCast(pnl.Controls(0), usrcntlDienstplanStunden).clearRowBg()
        End If
        'For Each r In dgvStundenMa.Rows
        'r.DefaultCellStyle.Font = New Font(dgvStundenMa.Font, FontStyle.Regular)
        'Next
    End Sub

    Private Sub dgv_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs)
        e.Effect = DragDropEffects.All
    End Sub

    Private Sub dgv_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs)
        Dim row As DataGridViewRow = TryCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)

        If row IsNot Nothing Then
            Try
                changeDGV(row.DataGridView, DirectCast(sender, DataGridView))
            Catch ex As Exception
                MessageBox.Show("dgv_DragDrop-Error: " & ex.Message)
            End Try
        End If
    End Sub

    Function getValuesDienstDGV(dgvname, s)
        For Each d In DGV
            If d.dgvName = dgvname Then
                If s = "abt" Then Return d.dgvAbteilung
                If s = "von" Then Return d.dgvVon
                If s = "bis" Then Return d.dgvBis
                If s = "datum" Then Return d.dgvDatum
            End If
        Next
        Return ""
    End Function
    Function alreadyExists(d As DataGridView, s As String) As Boolean
        For Each r As DataGridViewRow In d.Rows
            If r.Cells(2).Value.ToString = s Then Return True
        Next
        Return False
    End Function

    Function removeRow(d As DataGridView, id As String) As Boolean
        Try
            For Each r As DataGridViewRow In d.Rows
                If r.Cells(0).Value.ToString = id Then d.Rows.RemoveAt(r.Index) : Return True
            Next
        Catch ex As Exception

        End Try
        Return False
    End Function

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click


        If vbYes = MsgBox("Möchten Sie wirklich neu initialisieren?" & vbNewLine & "(Dabei gehen alle Änderungen in dieser Woche verloren)", vbYesNoCancel) Then
            initALL()
        End If
    End Sub
    Public Sub initALL(Optional MAID As Integer = -1)
        'MsgBox("init" & MAID, MAID)
        Me.Cursor = Cursors.WaitCursor
        ' Me.Enabled = False
        Dim dStart As Date = CalendarWeek(aktWoche, aktJahr)
        Label1.Text = dStart & " - " & dStart.AddDays(6)
        Dim montag As Date = CalendarWeek(aktWoche, aktJahr)
        Dim sonntag As Date = montag.AddDays(6)

        Dim cDienstAbwesendheiten As List(Of cDienstAbwesendheiten) = SQLDienst.getDienstAbwesendheiten(montag, sonntag, niederlassung)


        Dim ma As List(Of cDienstMA) = Nothing
        If MAID > 0 Then
            ma = SQLDienst.getAllDienstMA(niederlassung, montag, " AND dstma_id = " & MAID)
        Else
            If Not SQLDienst.delDstEintraege(montag, sonntag, niederlassung) Then Exit Sub 'Alle löschen
            ma = SQLDienst.getAllDienstMA(niederlassung, montag)
        End If


        ' If SQLDienst.delDstEintraege(montag, sonntag, niederlassung) Then
        '  Dim ma As List(Of cDienstMA) = SQLDienst.getAllDienstMA(niederlassung)
        Dim datum As Date = montag
        For i = 1 To 7
            Dim FT As New VERAG_PROG_ALLGEMEIN.cFeiertage(datum.Year) 'Evtl Jahressprung, darum neu definieren
            For Each m In ma
                Dim eintrag As New cDienstEintrag
                eintrag.dstetr_dstmaId = m.dstma_id
                eintrag.dstetr_datum = datum

                If Not FT.isFeiertag(datum, cDienstSettings.getLand(niederlassung)) Then
                    If m.dstma_muster Then
                        '   MsgBox("HIER")
                        Dim tz As List(Of cDienstTeilzeit) = SQLDienst.getAllDienstTeilzeit(m.dstma_id)
                        eintrag.dstetr_art = getFromTeilzeit("abt", tz, datum, SCHICHT, m.dstma_4wo)
                        If eintrag.dstetr_art = "" Then
                            eintrag.dstetr_art = "FREI"
                        Else
                            '  MsgBox(getFromTeilzeit("von", tz, datum, SCHICHT) & " _ " & getFromTeilzeit("bis", tz, datum, SCHICHT))
                            eintrag.dstetr_von = getFromTeilzeit("von", tz, datum, SCHICHT, m.dstma_4wo)
                            eintrag.dstetr_bis = getFromTeilzeit("bis", tz, datum, SCHICHT, m.dstma_4wo)
                            eintrag.dstetr_pause = getFromTeilzeit("pause", tz, datum, SCHICHT, m.dstma_4wo)
                            eintrag.dstetr_grund = ""
                            eintrag.dstetr_info = ""
                            ' MsgBox(eintrag.dstetr_art)
                            eintrag.dstetr_art = getFromTeilzeit("abt", tz, datum, SCHICHT, m.dstma_4wo)
                            ' SQLDienst.updateInsertByDienstEintrag(eintrag, niederlassung)
                        End If

                    Else
                        If m.dstma_arbvh = "VZ" Then

                            If week(datum.DayOfWeek) = "SA" Or week(datum.DayOfWeek) = "SO" Then
                                eintrag.dstetr_art = "FREI"
                            Else
                                eintrag.dstetr_art = getSchichtArt(m.dstma_abteilung, m.dstma_stammSchicht, datum)


                            End If

                            eintrag.dstetr_von = getDefaultTimeBySchicht(eintrag.dstetr_art, "von", week(datum.DayOfWeek).ToUpper)
                            eintrag.dstetr_bis = getDefaultTimeBySchicht(eintrag.dstetr_art, "bis", week(datum.DayOfWeek).ToUpper)
                            eintrag.dstetr_pause = getDefaultTimeBySchicht(eintrag.dstetr_art, "pause", week(datum.DayOfWeek).ToUpper)
                            eintrag.dstetr_grund = ""
                            eintrag.dstetr_info = ""

                            ' SQLDienst.updateInsertByDienstEintrag(eintrag, niederlassung)
                        Else 'TEILZEIT
                            eintrag.dstetr_art = "FREI"
                            eintrag.dstetr_von = "00:00"
                            eintrag.dstetr_bis = "00:00"
                            eintrag.dstetr_pause = "0"
                            eintrag.dstetr_grund = ""
                            eintrag.dstetr_info = ""
                            ' SQLDienst.updateInsertByDienstEintrag(eintrag, niederlassung)

                        End If
                    End If
                Else 'FEIERTAG
                    eintrag.dstetr_art = "FREI"
                    eintrag.dstetr_von = "00:00"
                    eintrag.dstetr_bis = "00:00"
                    eintrag.dstetr_pause = "0"
                    eintrag.dstetr_grund = ""
                    eintrag.dstetr_info = ""
                    ' SQLDienst.updateInsertByDienstEintrag(eintrag, niederlassung)

                End If

                'Abwesenheiten prüfen:
                For Each d In cDienstAbwesendheiten
                    If d.dstna_mitId = eintrag.dstetr_dstmaId AndAlso d.dstna_datum_von <= datum And d.dstna_datum_bis >= datum Then
                        eintrag.dstetr_art = d.dstna_grund

                        If week(datum.DayOfWeek) = "SA" Or week(datum.DayOfWeek) = "SO" Then
                            eintrag.dstetr_art = "FREI"
                        End If

                        eintrag.dstetr_von = getDefaultTimeBySchicht(d.dstna_grund, "von", week(datum.DayOfWeek).ToUpper)
                        eintrag.dstetr_bis = getDefaultTimeBySchicht(d.dstna_grund, "bis", week(datum.DayOfWeek).ToUpper)
                        eintrag.dstetr_pause = getDefaultTimeBySchicht(d.dstna_grund, "pause", week(datum.DayOfWeek).ToUpper)
                    End If
                Next
                SQLDienst.updateInsertByDienstEintrag(eintrag, niederlassung)

            Next
            datum = datum.AddDays(1)
        Next
        ' End If

        Me.Enabled = True
        initDienstplan()
        Me.Cursor = Cursors.Default

    End Sub
    Function getFromTeilzeit(switch, tz, datum, dienstplan, dp4wo) As String
        For Each t As cDienstTeilzeit In tz
            Dim isSchicht = False
            If dp4wo Then
                If dienstplan = t.dsttz_dienstplan Then isSchicht = True
            Else
                If dienstplan.contains("ROT") And t.dsttz_dienstplan.Contains("ROT") Then isSchicht = True
                If dienstplan.contains("BLAU") And t.dsttz_dienstplan.Contains("BLAU") Then isSchicht = True
            End If

            If t.dsttz_wotag = week(datum.DayOfWeek) And isSchicht Then
                If switch = "von" Then Return t.dsttz_von
                If switch = "bis" Then Return t.dsttz_bis
                If switch = "pause" Then Return t.dsttz_pause
                If switch = "abt" Then
                    If t.dsttz_abt = "ZOLL1" Then Return "ZOLL_VM"
                    If t.dsttz_abt = "ZOLL2" Then Return "ZOLL_NM"
                    Return t.dsttz_abt
                    '  If False Then
                    'If t.dsttz_abt = "ZOLL1" Then
                    'If SCHICHT.ToString.StartsWith("ROT") Then Return "ZOLL_VM" Else Return "ZOLL_NM"
                    'End If
                    'If t.dsttz_abt = "ZOLL2" Then
                    'If SCHICHT.ToString.StartsWith("ROT") Then Return "ZOLL_NM" Else Return "ZOLL_VM"
                    ' End If
                    'If t.dsttz_abt = "ZOLL_TAG" Then
                    'If SCHICHT.ToString.StartsWith("ROT") Then Return "ZOLL_NM" Else Return "ZOLL_TAG"
                    'End If
                    'If t.dsttz_abt = "NACHT" Then Return "NACHT"
                    ' End If
                End If
            End If
        Next
        Return ""



    End Function
    Public Function getSchichtArt(abteilung, stammschicht, datum)
        Dim s1 = ""
        Dim s2 = ""
        If stammschicht = "ZOLL TAG" Then Return "ZOLL_TAG"
        If abteilung = "NACHT" Then Return abteilung
        If niederlassung = "SUB" Or niederlassung = "ATILLA" Then
            If SCHICHT.ToString.StartsWith("ROT") Then
                Select Case week(datum.DayOfWeek)
                    Case "MO", "MI", "FR"
                        s1 = "ZOLL_NM"
                        s2 = "ZOLL_VM"
                    Case "DI", "DO"
                        s2 = "ZOLL_NM"
                        s1 = "ZOLL_VM"
                End Select
            Else
                Select Case week(datum.DayOfWeek)
                    Case "MO", "MI", "FR"
                        s2 = "ZOLL_NM"
                        s1 = "ZOLL_VM"
                    Case "DI", "DO"
                        s1 = "ZOLL_NM"
                        s2 = "ZOLL_VM"
                End Select
            End If
        Else
            s1 = "ZOLL_VM"
            s2 = "ZOLL_NM"
        End If
        If stammschicht = "ZOLL1" Then Return s1
        If stammschicht = "ZOLL2" Then Return s2
        Return ""
    End Function

    Public Function getDefaultTimeBySchicht(abteilung, vonOrBis, woTag)
        abteilung = abteilung.ToString.Replace("ZOLL_VM", "ZOLL1")
        abteilung = abteilung.ToString.Replace("ZOLL_NM", "ZOLL2")
        Dim d As cDienstDetails = SQLDienst.getDienstDetailsWoTagByArtAndWoTag(niederlassung, abteilung, woTag)
        If vonOrBis = "von" Then
            If d.dedet_von <> "" Then Return d.dedet_von Else  : Return "00:00" : End If
        If vonOrBis = "bis" Then
            If d.dedet_bis <> "" Then Return d.dedet_bis Else  : Return "00:00" : End If
        If vonOrBis = "pause" Then
            Return d.dedet_pause : End If
        Return ""
    End Function

    Private Sub dgv_clearSelection(sender As Object, e As EventArgs)
        DirectCast(sender, DataGridView).ClearSelection()
        '  TextBox1.Text = ""
        ' TextBox2.Text = ""
    End Sub



    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim txt As String = Button4.Text
        Button4.Text = txt & " (0 %)"

        Me.Cursor = Cursors.WaitCursor
        Dim exclApp As Object 'as Application
        Dim Datei As Object 'as WorkBook
        Dim Blatt As Object 'as WorkSheet
        exclApp = CreateObject("Excel.Application")

        '  Dim nWeek As Integer
        ' nWeek = DatePart(DateInterval.WeekOfYear, New Date(2004, 3, 22), _
        '     FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFourDays)




        If Not My.Computer.FileSystem.DirectoryExists(Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\tmp\") Then
            My.Computer.FileSystem.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\tmp\")
        End If
        Dim strFileName As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\tmp\tmp.xlsx"
        Try
            With exclApp
                .Visible = False
                Datei = .Workbooks.Open(AppDomain.CurrentDomain.BaseDirectory & "Resources\DienstplanATILLA.xlsx")
                'WordDoc.Activate()
                ' MsgBox(AppDomain.CurrentDomain.BaseDirectory & "Resources\Dienstplan.xlsx")
                '  .Visible = True
                '  Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\Dienstplan\" ' My.Computer.FileSystem.GetTempFileName
                '  If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
                'My.Computer.FileSystem.CreateDirectory(sPath)
                '  End If
                '
                ' Try
                'My.Computer.FileSystem.WriteAllBytes(sPath & "Auswertung.xlsx", My.Resources, False)
                'System.IO.File.Copy("C:\Users\DEVELOPER1\Desktop\Dienstplan.xlsx", sPath & "Dienstplan.xlsx", True)
                'Catch ex As Exception
                'MsgBox(ex.Message)
                '   Exit Sub
                'End Try

                'Datei = .Workbooks.Open(sPath & "Dienstplan.xlsx") 'Anpassen
                Blatt = Datei.Worksheets("DIENSTPLAN")

                Dim d As Date = CalendarWeek(aktWoche, aktJahr)
                Blatt.Range("B2").Value = "MONTAG, " & d.ToString("dd.MMM") : d = d.AddDays(1)
                Blatt.Range("D2").Value = "DIENSTAG, " & d.ToString("dd.MMM") : d = d.AddDays(1)
                Blatt.Range("F2").Value = "MITTWOCH, " & d.ToString("dd.MMM") : d = d.AddDays(1)
                Blatt.Range("H2").Value = "DONNERSTAG, " & d.ToString("dd.MMM") : d = d.AddDays(1)
                Blatt.Range("J2").Value = "FREITAG, " & d.ToString("dd.MMM") : d = d.AddDays(1)
                Blatt.Range("O2").Value = "SA, " & d.ToString("dd.MMM") : d = d.AddDays(1)
                Blatt.Range("P2").Value = "SO, " & d.ToString("dd.MMM")

                If SCHICHT.ToString.StartsWith("ROT") Then
                    Blatt.Range("A4").Font.Color = Color.Red
                    Blatt.Range("H1").Font.Color = Color.Red
                    Blatt.Range("H1").value = "ROT"
                Else
                    Blatt.Range("A4").Font.Color = Color.Blue
                    Blatt.Range("H1").Font.Color = Color.Blue
                    Blatt.Range("H1").value = "BLAU"
                End If
                Blatt.Range("A4").Value = aktWoche

                Button4.Text = txt & " (10 %)"

                'MONTAG
                Dim zoll1Mo(20) As String
                For i = 0 To 19 : zoll1Mo(i) = "B" & i + 14 : Next
                Dim zoll2Mo(20) As String
                For i = 0 To 19 : zoll2Mo(i) = "C" & i + 14 : Next
                Dim zollTagMo(6) As String
                For i = 0 To 2 : zollTagMo(i) = "B" & i + 34 : Next
                For i = 0 To 2 : zollTagMo(i + 3) = "C" & i + 34 : Next

                Dim NACHTMo1(6) As String
                For i = 0 To 2 : NACHTMo1(i) = "B" & i + 37 : Next
                '  Dim NACHTMo2(11) As String
                For i = 0 To 2 : NACHTMo1(i + 3) = "C" & i + 37 : Next

                Dim ZAMo(10) As String
                For i = 0 To 4 : ZAMo(i) = "B" & i + 40 : Next
                For i = 0 To 4 : ZAMo(i + 5) = "C" & i + 40 : Next

                Dim UrlMo(6) As String
                For i = 0 To 2 : UrlMo(i) = "B" & i + 45 : Next
                For i = 0 To 2 : UrlMo(i + 3) = "C" & i + 45 : Next

                Dim SOMo(4) As String
                For i = 0 To 1 : SOMo(i) = "B" & i + 48 : Next
                For i = 0 To 1 : SOMo(i + 2) = "C" & i + 48 : Next

                Dim KSMo(6) As String
                For i = 0 To 2 : KSMo(i) = "B" & i + 50 : Next
                For i = 0 To 2 : KSMo(i + 3) = "C" & i + 50 : Next

                Blatt = fill(dgvZoll1_Mo, zoll1Mo, Blatt)
                Blatt = fill(dgvZoll2_Mo, zoll2Mo, Blatt)
                Blatt = fill(dgvZollTag_Mo, zollTagMo, Blatt)
                Blatt = fill(dgvNACHT_Mo, NACHTMo1, Blatt)
                Blatt = fill(dgvZA_Mo, ZAMo, Blatt)
                Blatt = fill(dgvUrl_Mo, UrlMo, Blatt)
                Blatt = fill(dgvDR_Mo, SOMo, Blatt)
                Blatt = fill(dgvKS_Mo, KSMo, Blatt)

                Button4.Text = txt & " (25 %)"

                'DIENSTAG
                Dim zoll1Di(20) As String
                For i = 0 To 19 : zoll1Di(i) = "D" & i + 14 : Next
                Dim zoll2Di(20) As String
                For i = 0 To 19 : zoll2Di(i) = "E" & i + 14 : Next
                Dim zollTagDi(6) As String
                For i = 0 To 2 : zollTagDi(i) = "D" & i + 34 : Next
                For i = 0 To 2 : zollTagDi(i + 3) = "E" & i + 34 : Next

                Dim NACHTDi1(6) As String
                For i = 0 To 2 : NACHTDi1(i) = "D" & i + 37 : Next
                ' Dim NACHTDi2(11) As String
                For i = 0 To 2 : NACHTDi1(i + 3) = "E" & i + 37 : Next

                Dim ZADi(10) As String
                For i = 0 To 4 : ZADi(i) = "D" & i + 40 : Next
                For i = 0 To 4 : ZADi(i + 5) = "E" & i + 40 : Next

                Dim UrlDi(6) As String
                For i = 0 To 2 : UrlDi(i) = "D" & i + 45 : Next
                For i = 0 To 2 : UrlDi(i + 3) = "E" & i + 45 : Next

                Dim SODi(4) As String
                For i = 0 To 1 : SODi(i) = "D" & i + 48 : Next
                For i = 0 To 1 : SODi(i + 2) = "E" & i + 48 : Next

                Dim KSDi(6) As String
                For i = 0 To 2 : KSDi(i) = "D" & i + 50 : Next
                For i = 0 To 2 : KSDi(i + 3) = "E" & i + 50 : Next

                Blatt = fill(dgvZoll1_Di, zoll1Di, Blatt)
                Blatt = fill(dgvZoll2_Di, zoll2Di, Blatt)
                Blatt = fill(dgvZollTag_Di, zollTagDi, Blatt)
                Blatt = fill(dgvNACHT_Di, NACHTDi1, Blatt)
                Blatt = fill(dgvZA_Di, ZADi, Blatt)
                Blatt = fill(dgvUrl_Di, UrlDi, Blatt)
                Blatt = fill(dgvDR_Di, SODi, Blatt)
                Blatt = fill(dgvKS_Di, KSDi, Blatt)

                Button4.Text = txt & " (40 %)"

                'MITTWOCH
                Dim zoll1Mi(20) As String
                For i = 0 To 19 : zoll1Mi(i) = "F" & i + 14 : Next
                Dim zoll2Mi(20) As String
                For i = 0 To 19 : zoll2Mi(i) = "G" & i + 14 : Next
                Dim zollTagMi(6) As String
                For i = 0 To 2 : zollTagMi(i) = "F" & i + 34 : Next
                For i = 0 To 2 : zollTagMi(i + 3) = "G" & i + 34 : Next

                Dim NACHTMi1(6) As String
                For i = 0 To 2 : NACHTMi1(i) = "F" & i + 37 : Next
                ' Dim NACHTMi2(11) As String
                For i = 0 To 2 : NACHTMi1(i + 3) = "G" & i + 37 : Next

                Dim ZAMi(10) As String
                For i = 0 To 4 : ZAMi(i) = "F" & i + 40 : Next
                For i = 0 To 4 : ZAMi(i + 5) = "G" & i + 40 : Next

                Dim UrlMi(6) As String
                For i = 0 To 2 : UrlMi(i) = "F" & i + 45 : Next
                For i = 0 To 2 : UrlMi(i + 3) = "G" & i + 45 : Next

                Dim SOMi(4) As String
                For i = 0 To 1 : SOMi(i) = "F" & i + 48 : Next
                For i = 0 To 1 : SOMi(i + 2) = "G" & i + 48 : Next

                Dim KSMi(6) As String
                For i = 0 To 2 : KSMi(i) = "F" & i + 50 : Next
                For i = 0 To 2 : KSMi(i + 3) = "G" & i + 50 : Next

                Blatt = fill(dgvZoll1_Mi, zoll1Mi, Blatt)
                Blatt = fill(dgvZoll2_Mi, zoll2Mi, Blatt)
                Blatt = fill(dgvZollTag_Mi, zollTagMi, Blatt)
                Blatt = fill(dgvNACHT_Mi, NACHTMi1, Blatt)
                Blatt = fill(dgvZA_Mi, ZAMi, Blatt)
                Blatt = fill(dgvUrl_Mi, UrlMi, Blatt)
                Blatt = fill(dgvDR_Mi, SOMi, Blatt)
                Blatt = fill(dgvKS_Mi, KSMi, Blatt)

                Button4.Text = txt & " (55 %)"

                'DONNERSTAG
                Dim zoll1Do(20) As String
                For i = 0 To 19 : zoll1Do(i) = "H" & i + 14 : Next
                Dim zoll2Do(20) As String
                For i = 0 To 19 : zoll2Do(i) = "I" & i + 14 : Next
                Dim zollTagDo(6) As String
                For i = 0 To 2 : zollTagDo(i) = "H" & i + 34 : Next
                For i = 0 To 2 : zollTagDo(i + 3) = "I" & i + 34 : Next

                Dim NACHTDo1(6) As String
                For i = 0 To 2 : NACHTDo1(i) = "H" & i + 37 : Next
                '  Dim NACHTDo2(11) As String
                For i = 0 To 2 : NACHTDo1(i + 3) = "I" & i + 37 : Next

                Dim ZADo(10) As String
                For i = 0 To 4 : ZADo(i) = "H" & i + 40 : Next
                For i = 0 To 4 : ZADo(i + 5) = "I" & i + 40 : Next

                Dim UrlDo(6) As String
                For i = 0 To 2 : UrlDo(i) = "H" & i + 45 : Next
                For i = 0 To 2 : UrlDo(i + 3) = "I" & i + 45 : Next

                Dim SODo(4) As String
                For i = 0 To 1 : SODo(i) = "H" & i + 48 : Next
                For i = 0 To 1 : SODo(i + 2) = "I" & i + 48 : Next

                Dim KSDo(6) As String
                For i = 0 To 2 : KSDo(i) = "H" & i + 50 : Next
                For i = 0 To 2 : KSDo(i + 3) = "I" & i + 50 : Next

                Blatt = fill(dgvZoll1_Do, zoll1Do, Blatt)
                Blatt = fill(dgvZoll2_Do, zoll2Do, Blatt)
                Blatt = fill(dgvZollTag_Do, zollTagDo, Blatt)
                Blatt = fill(dgvNACHT_Do, NACHTDo1, Blatt)
                Blatt = fill(dgvZA_Do, ZADo, Blatt)
                Blatt = fill(dgvUrl_Do, UrlDo, Blatt)
                Blatt = fill(dgvDR_Do, SODo, Blatt)
                Blatt = fill(dgvKS_Do, KSDo, Blatt)

                Button4.Text = txt & " (70 %)"

                'FREITAG
                Dim zoll1Fr(20) As String
                For i = 0 To 19 : zoll1Fr(i) = "J" & i + 14 : Next
                Dim zoll2Fr(20) As String
                For i = 0 To 19 : zoll2Fr(i) = "L" & i + 14 : Next
                Dim zollTagFr(6) As String
                For i = 0 To 2 : zollTagFr(i) = "J" & i + 34 : Next
                For i = 0 To 2 : zollTagFr(i + 3) = "L" & i + 34 : Next

                Dim NACHTFr1(6) As String
                For i = 0 To 2 : NACHTFr1(i) = "J" & i + 37 : Next
                ' Dim NACHTFr2(11) As String
                For i = 0 To 2 : NACHTFr1(i + 3) = "L" & i + 37 : Next

                Dim ZAFr(10) As String
                For i = 0 To 4 : ZAFr(i) = "J" & i + 40 : Next
                For i = 0 To 4 : ZAFr(i + 5) = "L" & i + 40 : Next

                Dim UrlFr(6) As String
                For i = 0 To 2 : UrlFr(i) = "J" & i + 45 : Next
                For i = 0 To 2 : UrlFr(i + 3) = "L" & i + 45 : Next

                Dim SOFr(4) As String
                For i = 0 To 1 : SOFr(i) = "J" & i + 48 : Next
                For i = 0 To 1 : SOFr(i + 2) = "L" & i + 48 : Next

                Dim KSFr(6) As String
                For i = 0 To 2 : KSFr(i) = "J" & i + 50 : Next
                For i = 0 To 2 : KSFr(i + 3) = "L" & i + 50 : Next

                Blatt = fill(dgvZoll1_Fr, zoll1Fr, Blatt)
                Blatt = fill(dgvZoll2_Fr, zoll2Fr, Blatt)
                Blatt = fill(dgvZollTag_Fr, zollTagFr, Blatt)
                Blatt = fill(dgvNACHT_Fr, NACHTFr1, Blatt)
                Blatt = fill(dgvZA_Fr, ZAFr, Blatt)
                Blatt = fill(dgvUrl_Fr, UrlFr, Blatt)
                Blatt = fill(dgvDR_Fr, SOFr, Blatt)
                Blatt = fill(dgvKS_Fr, KSFr, Blatt)

                Button4.Text = txt & " (80 %)"

                'SAMSTAG
                Dim zoll1Sa(20) As String
                For i = 0 To 19 : zoll1Sa(i) = "O" & i + 14 : Next
                Dim zollTagSa(3) As String
                For i = 0 To 2 : zollTagSa(i) = "O" & i + 34 : Next
                '     Dim zoll2Sa(14) As String
                '   For i = 0 To 13 : zoll2Sa(i) = "L" & i + 14 : Next

                Dim NACHTSa1(3) As String
                For i = 0 To 2 : NACHTSa1(i) = "O" & i + 37 : Next
                ' Dim NACHTSa2(11) As String
                ' For i = 0 To 2 : NACHTSa2(i) = "L" & i + 31 : Next

                Dim ZASa(5) As String
                For i = 0 To 4 : ZASa(i) = "O" & i + 40 : Next
                ' For i = 0 To 3: ZAFr(i + 3) = "L" & i + 40 : Next

                Dim UrlSa(3) As String
                For i = 0 To 2 : UrlSa(i) = "O" & i + 45 : Next
                ' For i = 0 To 2 : UrlSa(i + 4) = "L" & i + 45 : Next

                Dim SOSa(2) As String
                For i = 0 To 1 : SOSa(i) = "O" & i + 48 : Next
                'For i = 0 To 2 : SOSa(i + 3) = "L" & i + 48 : Next

                Dim KSSa(3) As String
                For i = 0 To 2 : KSSa(i) = "O" & i + 50 : Next
                ' For i = 0 To 2 : KSSa(i + 3) = "L" & i + 50 : Next



                Blatt = fill(dgvZoll1_Sa, dgvZoll2_Sa, zoll1Sa, Blatt)
                'Blatt = fill(dgvZoll2_Sa, zoll1Sa, Blatt)
                'Blatt = fill(dgvZollTag_Sa, zollTagSa, Blatt)
                Blatt = fill(dgvNACHT_Sa, NACHTSa1, Blatt)
                Blatt = fill(dgvZA_Sa, ZASa, Blatt)
                Blatt = fill(dgvUrl_Sa, UrlSa, Blatt)
                Blatt = fill(dgvDR_Sa, SOSa, Blatt)
                Blatt = fill(dgvKS_Sa, KSSa, Blatt)

                Button4.Text = txt & " (90 %)"

                'SONNTAG
                ' Dim zoll1So(14) As String
                ' For i = 0 To 13 : zoll1So(i) = "Q" & i + 14 : Next
                Dim zoll2So(20) As String
                For i = 0 To 19 : zoll2So(i) = "P" & i + 14 : Next
                Dim zollTagSo(3) As String
                For i = 0 To 2 : zollTagSo(i) = "P" & i + 34 : Next
                '     Dim zoll2So(14) As String
                '   For i = 0 To 13 : zoll2So(i) = "L" & i + 14 : Next

                Dim NACHTSo1(3) As String
                For i = 0 To 2 : NACHTSo1(i) = "P" & i + 37 : Next
                ' Dim NACHTSo2(11) As String
                ' For i = 0 To 2 : NACHTSo2(i) = "L" & i + 31 : Next

                Dim ZASo(5) As String
                For i = 0 To 4 : ZASo(i) = "P" & i + 40 : Next
                ' For i = 0 To 3: ZAFr(i + 3) = "L" & i + 40 : Next

                Dim UrlSo(3) As String
                For i = 0 To 2 : UrlSo(i) = "P" & i + 45 : Next
                ' For i = 0 To 2 : UrlSo(i + 4) = "L" & i + 45 : Next

                Dim SOSo(2) As String
                For i = 0 To 1 : SOSo(i) = "P" & i + 48 : Next
                'For i = 0 To 2 : SOSo(i + 3) = "L" & i + 48 : Next

                Dim KSSo(3) As String
                For i = 0 To 2 : KSSo(i) = "P" & i + 50 : Next
                ' For i = 0 To 2 : KSSo(i + 3) = "L" & i + 50 : Next

                ' Blatt = fill(dgvZoll1_So, zoll1So, Blatt)
                Blatt = fill(dgvZoll2_So, zoll2So, Blatt, "SO")
                '  Blatt = fill(dgvZollTag_So, zollTagSo, Blatt)
                Blatt = fill(dgvNACHT_So, NACHTSo1, Blatt)
                Blatt = fill(dgvZA_So, ZASo, Blatt)
                Blatt = fill(dgvUrl_So, UrlSo, Blatt)
                Blatt = fill(dgvDR_So, SOSo, Blatt)
                Blatt = fill(dgvKS_So, KSSo, Blatt)

                Button4.Text = txt & " (100 %)"

                .Visible = True
                .DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
                Try : Datei.SaveAs(strFileName) : Catch : End Try

            End With

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Me.Cursor = Cursors.Default
        Button4.Text = txt
    End Sub

    Function fillQS(dgv As DataGridView, s1() As String, s2() As String, mestan As String, Blatt As Excel.Worksheet) As Excel.Worksheet
        With dgv
            Dim cnt1 As Integer = 0
            Dim cnt2 As Integer = 0
            If .RowCount > 0 Then
                Dim cnt As Integer = 0
                For i = 0 To .RowCount - 1
                    Dim r As DataGridViewRow = .Rows(i)
                    ' MsgBox("DGV: " & dgv.Name & " RAGNE: " & s(i) & " VALUE: " & r.Cells(1).Value)
                    If r.Cells(1).Value.ToString.Contains("AKPINAR") Then
                        Try : Blatt.Range(mestan).Value = r.Cells(1).Value : Catch : End Try
                    ElseIf r.Cells(4).Value = "10:00" And r.Cells(5).Value = "19:00" Then
                        Try : Blatt.Range(s2(cnt2)).Value = r.Cells(1).Value : cnt2 += 1 : Catch : End Try
                    Else
                        Try : Blatt.Range(s1(cnt1)).Value = r.Cells(1).Value : cnt1 += 1 : Catch : End Try
                    End If

                Next
            End If
        End With
        Return Blatt
    End Function




    Function fill(dgv As DataGridView, s() As String, Blatt As Excel.Worksheet, Optional dayOweek As String = "") As Excel.Worksheet
        With dgv
            If .RowCount > 0 Then
                Dim cnt As Integer = 0
                For i = 0 To .RowCount - 1
                    Dim r As DataGridViewRow = .Rows(i)

                    'MsgBox("DGV: " & dgv.Name & " RAGNE: " & s(i) & " VALUE: " & r.Cells(1).Value)
                    Try
                        If r.Cells(1).Style.ForeColor <> Color.Black Then Blatt.Range(s(i)).Font.Color = ColorTranslator.FromHtml(r.Cells(9).Value)
                    Catch ex As Exception : MsgBox(ex.Message) : End Try
                    Try : Blatt.Range(s(i)).Value = r.Cells(1).Value : Catch ex As Exception : MsgBox(ex.Message) : End Try
                    If dayOweek = "SO" Then
                        Try : Blatt.Range(s(i)).Font.Color = Color.Red : Catch ex As Exception : MsgBox(ex.Message) : End Try
                    End If

                    If dayOweek <> "SO" And i = 0 And (dgv.Name.Contains("Zoll1") Or dgv.Name.Contains("Zoll2")) Then
                        Blatt.Range(s(i)).Value = Blatt.Range(s(i)).Value & " (SL)"
                        Dim start As Integer = Blatt.Range(s(i)).Value.ToString.Length - 2
                        Blatt.Range(s(i)).Characters(Start:=start, Length:=2).Font.Color = Color.Red
                    End If

                Next
            End If
        End With
        Return Blatt
    End Function





    Function fill(dgv As DataGridView, dgv2 As DataGridView, s() As String, Blatt As Excel.Worksheet, Optional dayOweek As String = "") As Excel.Worksheet
        Dim j = 0
        With dgv

            If .RowCount > 0 Then
                Dim cnt As Integer = 0
                For i = 0 To .RowCount - 1
                    Dim r As DataGridViewRow = .Rows(i)

                    'MsgBox("DGV: " & dgv.Name & " RAGNE: " & s(i) & " VALUE: " & r.Cells(1).Value)
                    Try
                        If r.Cells(1).Style.ForeColor <> Color.Black Then Blatt.Range(s(j)).Font.Color = ColorTranslator.FromHtml(r.Cells(9).Value)
                    Catch ex As Exception : MsgBox(ex.Message) : End Try
                    Try : Blatt.Range(s(j)).Value = r.Cells(1).Value : Catch ex As Exception : MsgBox(ex.Message) : End Try
                    If dayOweek = "SO" Then
                        Try : Blatt.Range(s(j)).Font.Color = Color.Red : Catch ex As Exception : MsgBox(ex.Message) : End Try
                    End If

                    If dayOweek <> "SO" And i = 0 And (.Name.Contains("Zoll1") Or .Name.Contains("Zoll2")) Then
                        Blatt.Range(s(j)).Value = Blatt.Range(s(j)).Value & " (SL)"
                        Dim start As Integer = Blatt.Range(s(j)).Value.ToString.Length - 2
                        Blatt.Range(s(j)).Characters(Start:=start, Length:=2).Font.Color = Color.Red
                    End If
                    j += 1
                Next
            End If
        End With
        With dgv2
            If .RowCount > 0 Then
                Dim cnt As Integer = 0
                For i = 0 To .RowCount - 1
                    Dim r As DataGridViewRow = .Rows(i)

                    'MsgBox("DGV: " & dgv.Name & " RAGNE: " & s(i) & " VALUE: " & r.Cells(1).Value)
                    Try
                        If r.Cells(1).Style.ForeColor <> Color.Black Then Blatt.Range(s(j)).Font.Color = ColorTranslator.FromHtml(r.Cells(9).Value)
                    Catch ex As Exception : MsgBox(ex.Message) : End Try
                    Try : Blatt.Range(s(j)).Value = r.Cells(1).Value : Catch ex As Exception : MsgBox(ex.Message) : End Try
                    j += 1
                Next
            End If
        End With
        Return Blatt
    End Function






    Private Sub Schicht2ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ctiZollTag.Click, ctiDbl.Click, ctiSchicht1.Click, ctiSchicht2.Click, ctiKrankenstand.Click, ctiQS.Click, ctiFrei.Click, ctiDienstreise.Click, ctiUrlaub.Click, ctiWocheSchichtWechsel.Click, ctiBemWo.Click, ZeitausgleichToolStripMenuItem.Click, NormaldienstToolStripMenuItem.Click, _
        ctiZVMLaenger.Click, ctiZNMLaenger.Click
        ' Dim a As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim dgv_tmp As DataGridView = DirectCast(sender.owner.SourceControl, DataGridView)


        Dim vm = "ZOLL2" : If SCHICHT.ToString.StartsWith("ROT") Then vm = "ZOLL1"
        Dim nm = "ZOLL1" : If SCHICHT.ToString.StartsWith("BLAU") Then vm = "ZOLL2"

        Select Case sender.Name
            Case "ctiSchicht1"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "ZOLL_VM"))
            Case "ctiSchicht2"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "ZOLL_NM"))
            Case "ctiZollTag"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "ZOLL_TAG"))
            Case "ctiKrankenstand"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "KS"))
            Case "ctiQS"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "NACHT"))
            Case "ctiFrei"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "FREI"))
            Case "ctiDienstreise"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "DR"))
            Case "ctiUrlaub"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "URL"))
            Case "ctiDbl"
                changeDGVToDBL(dgv_tmp)
            Case "ctiWocheSchichtWechsel"
                changeDGVWoSchicht(dgv_tmp)
            Case "ctiBemWo"
                changeDGVWoBemerkung(dgv_tmp)
            Case "ZeitausgleichToolStripMenuItem"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "ZA"))
            Case "NormaldienstToolStripMenuItem"
                initALL(dgv_tmp.CurrentRow.Cells("dstma_id").Value)
            Case "ctiZVMLaenger"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "ZOLL_VM"), "06:00", "16:00", 0, " 06-16")
            Case "ctiZNMLaenger"
                changeDGV(dgv_tmp, getDgvByDatArt(getValuesDienstDGV(dgv_tmp.Name, "datum"), "ZOLL_NM"), "16:00", "01:00", 0, " 16-01")
        End Select
    End Sub


    Sub changeDGVToDBL(dgv_sender As DataGridView)
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim arr As DataGridViewSelectedCellCollection = dgv_sender.SelectedCells
            For Each c As DataGridViewCell In arr
                Dim r As DataGridViewRow = c.OwningRow
                Dim von = getDefaultTimeBySchicht("DBL", "von", CDate(getValuesDienstDGV(dgv_sender.Name, "datum")).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                Dim bis = getDefaultTimeBySchicht("DBL", "bis", CDate(getValuesDienstDGV(dgv_sender.Name, "datum")).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                Dim pause = getDefaultTimeBySchicht("DBL", "pause", CDate(getValuesDienstDGV(dgv_sender.Name, "datum")).ToString("ddd", New CultureInfo("de-DE")).ToUpper)

                SQLDienst.updateDienstEintragArtChange(r.Cells(0).Value, getValuesDienstDGV(dgv_sender.Name, "datum"), "DBL", von, bis, pause)
            Next
            initDienstplan()
        Catch ex As Exception
            MessageBox.Show("changeDGVToDBL-Error: " & ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Sub changeDGVWoSchicht(dgv_sender As DataGridView)
        Me.Cursor = Cursors.WaitCursor
        Try
            If dgv_sender.SelectedCells.Count = 1 Then
                Dim maId = dgv_sender.CurrentRow.Cells(2).Value
                Dim montag As Date = CalendarWeek(aktWoche, aktJahr)
                For i = 0 To 4
                    Dim datum = montag.AddDays(i)
                    Dim abt = ""
                    Select Case SQLDienst.getSchichtOnDate(maId, datum)
                        Case "ZOLL_VM" : abt = "ZOLL_NM"
                        Case "ZOLL_NM" : abt = "ZOLL_VM"
                    End Select
                    If abt <> "" Then
                        Dim von As String = getDefaultTimeBySchicht(abt, "von", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                        Dim bis As String = getDefaultTimeBySchicht(abt, "bis", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                        Dim pause As String = getDefaultTimeBySchicht(abt, "pause", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                        SQLDienst.updateDienstEintragArtChangeByDstMaId(maId, datum, abt, von, bis, "", pause)
                    End If
                Next
            Else
                MsgBox("Bei dieser Funktion muss genau ein Mitarbeiter auswegählt sein!")
            End If

            initDienstplan()
        Catch ex As Exception
            MessageBox.Show("changeDGVWoSchicht-Error: " & ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Sub changeDGVWoBemerkung(dgv_sender As DataGridView)
        Me.Cursor = Cursors.WaitCursor
        Try
            If dgv_sender.SelectedCells.Count = 1 Then
                Dim maId = dgv_sender.CurrentRow.Cells(2).Value
                Dim montag As Date = CalendarWeek(aktWoche, aktJahr)
                Dim input = InputBox("Bitte geben Sie eine Bemerkung ein:", "Bemerkung ändern")
                If input <> "" Then
                    SQLDienst.updateDienstBemerkungChange(maId, montag, montag.AddDays(4), input, niederlassung)
                Else
                    MsgBox("Keine Bemerkung angegeben!")
                End If
            Else
                MsgBox("Bei dieser Funktion muss genau ein Mitarbeiter auswegählt sein!")

            End If
            initDienstplan()
        Catch ex As Exception
            MessageBox.Show("changeDGVWoBemerkung-Error: " & ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    Sub checkMaTageIfTeilzeit(maId)
        Dim dMa As cDienstMA = SQLDienst.getDstMAByDstMaId(maId)
        If dMa.dstma_arbvh = "TZ" Then
            Dim daysEintrag = SQLDienst.getCountDays(maId, CalendarWeek(aktWoche, aktJahr), CalendarWeek(aktWoche, aktJahr).AddDays(6))
            If dMa.dstma_TageProWoche >= 0 And daysEintrag > dMa.dstma_TageProWoche Then
                MsgBox(dMa.dstma_kuerzel & " wurde " & daysEintrag & " Mal eingetragen (Standard: " & dMa.dstma_TageProWoche & " Tage)!", vbInformation)
            End If
        End If
    End Sub
    Sub changeDGV(dgv_sender As DataGridView, dgv_receiver As DataGridView)
        Me.Cursor = Cursors.WaitCursor
        Try
            If dgv_sender IsNot Nothing And dgv_receiver IsNot Nothing Then
                If Not dgv_sender.Name = dgv_receiver.Name Then
                    If getValuesDienstDGV(dgv_receiver.Name, "datum") = getValuesDienstDGV(dgv_sender.Name, "datum") Then

                        Dim arr As DataGridViewSelectedCellCollection = dgv_sender.SelectedCells
                        For Each c As DataGridViewCell In arr
                            Dim r As DataGridViewRow = c.OwningRow
                            'If Not alreadyExists(dgv_receiver, r.Cells(2).Value) Then
                            Dim datum As Date = Date.Parse(getValuesDienstDGV(dgv_receiver.Name, "datum"))
                            Dim abt As String = getValuesDienstDGV(dgv_receiver.Name, "abt")
                            Dim von = getDefaultTimeBySchicht(abt, "von", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                            Dim bis = getDefaultTimeBySchicht(abt, "bis", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                            Dim pause = getDefaultTimeBySchicht(abt, "pause", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)

                            SQLDienst.updateDienstEintragArtChange(r.Cells(0).Value, datum.ToShortDateString, abt, von, bis, pause)

                            If abt.Contains("ZOLL") Or abt = "NACHT" And r.Cells("dstma_arbvh").Value = "TZ" Then
                                checkMaTageIfTeilzeit(r.Cells("dstma_id").Value)
                            End If
                        Next

                        initDienstplan()
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("changeDGV-Error: " & ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Sub changeDGV(dgv_sender As DataGridView, dgv_receiver As DataGridView, von As String, bis As String, pause As Double, info As String)
        Me.Cursor = Cursors.WaitCursor
        Try
            'If dgv_sender IsNot Nothing And dgv_receiver IsNot Nothing Then
            ' If Not dgv_sender.Name = dgv_receiver.Name Then
            If getValuesDienstDGV(dgv_receiver.Name, "datum") = getValuesDienstDGV(dgv_sender.Name, "datum") Then

                Dim arr As DataGridViewSelectedCellCollection = dgv_sender.SelectedCells
                For Each c As DataGridViewCell In arr
                    Dim r As DataGridViewRow = c.OwningRow
                    'If Not alreadyExists(dgv_receiver, r.Cells(2).Value) Then
                    Dim datum As Date = Date.Parse(getValuesDienstDGV(dgv_receiver.Name, "datum"))
                    Dim abt As String = getValuesDienstDGV(dgv_receiver.Name, "abt")
                    ' If von = "" Then von = getDefaultTimeBySchicht(abt, "von", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                    ' If bis = "" Then bis = getDefaultTimeBySchicht(abt, "bis", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)
                    ' If pause < 0 Then pause = getDefaultTimeBySchicht(abt, "pause", datum.ToString("ddd", New CultureInfo("de-DE")).ToUpper)

                    SQLDienst.updateDienstEintragArtChange(r.Cells(0).Value, datum.ToShortDateString, abt, von, bis, pause)
                    If info <> "" Then SQLDienst.updateDienstEintragInfo(r.Cells(0).Value, info)

                    If abt.Contains("ZOLL") Or abt = "NACHT" And r.Cells("dstma_arbvh").Value = "TZ" Then
                        checkMaTageIfTeilzeit(r.Cells("dstma_id").Value)
                    End If
                Next

                initDienstplan()
            End If
            'End If
            ' End If
        Catch ex As Exception
            MessageBox.Show("changeDGV-Error: " & ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub


    Function getDgvByDatArt(datum, art) As DataGridView
        For Each d As cDienstDGV In DGV
            If d.dgvDatum = datum And d.dgvAbteilung = art Then Return getDGV(d.dgvName)
        Next
        Return Nothing
    End Function

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        AbwesenheitEintragen("URL")
        Exit Sub
        Dim frmDiestEintrag As New frmDiestEintrag
        frmDiestEintrag.niederlassung = niederlassung
        frmDiestEintrag.art = "URL"
        frmDiestEintrag.Show()
    End Sub

    Private Sub AbwesenheitEintragen(grund)
        '  MsgBox(e.ColumnIndex & " : " & e.RowIndex)
        If markId < 0 Then MsgBox("Mitarbeiter auswählen!") : Exit Sub
        Dim frmUrlKW As New frmUrlKW
        Dim art = ""
        frmUrlKW.KW = aktWoche
        frmUrlKW.YEAR = aktJahr
        'Dim kw As Integer = dgvUrlaub.Rows(e.RowIndex).Cells(e.ColumnIndex).Tag
        ' Dim maId = markId
        Dim ll As List(Of cDienstAbwesendheitenKW) = SQLDienst.getDienstAbwesendheitenKWByArt(aktWoche, markId, aktJahr, niederlassung, grund)
        ' Dim ll As List(Of cDienstAbwesendheitenKW) = DP.getDienstAbwesendheitenKW(kw, aktJahr, niederlassung)
        ' MsgBox(e.ColumnIndex - 1)
        If ll.Count = 1 Then
            frmUrlKW.KW_ID = ll(0).dstnk_id
            '  frmUrlKW.KW_ID = ll(0).dstnk_grund
        ElseIf ll.Count > 1 Then
            Dim frmDienstAuswahl As New frmDienstAuswahl
            frmDienstAuswahl.list = ll
            frmDienstAuswahl.ShowDialog(Me)
            frmUrlKW.KW_ID = frmDienstAuswahl.kw_id
        End If

        frmUrlKW.maId = markId
        frmUrlKW.niederlassung = niederlassung

        frmUrlKW.ShowDialog(Me)
        If frmUrlKW.RESULT <> "" Then
            initALL(markId)
        End If


    End Sub


    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Me.Cursor = Cursors.WaitCursor
        aktDate = aktDate.AddDays(7)
        aktWoche = DateToWeek(aktDate).Substring(4, 2)
        aktJahr = DateToWeek(aktDate).Substring(0, 4)
        initWeekInfo()
        initDienstplan()
        txtKWYear.Text = aktDate.Year
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        Me.Cursor = Cursors.WaitCursor
        aktDate = aktDate.AddDays(-7)
        aktWoche = DateToWeek(aktDate).Substring(4, 2)
        aktJahr = DateToWeek(aktDate).Substring(0, 4)
        initWeekInfo()
        initDienstplan()
        txtKWYear.Text = aktDate.Year
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        Me.Cursor = Cursors.WaitCursor
        'MsgBox(dgvZoll1_Mo.Rows(0).Cells(2).Value)
        Try
            If TextBox1.Text = "" Then Throw New Exception
            If TextBox2.Text = "" Then Throw New Exception

            If Not IsNumeric(TextBox4.Text) Then Throw New Exception
            If TextBox4.Text > 3 Or TextBox4.Text < 0 Then MsgBox("Die Pause darf nicht größer als 3 Stunden sein!") : Throw New Exception

            If cbxChangeForWo.Checked Then 'für ganze Woche
                Try
                    Dim montag As Date = CalendarWeek(aktWoche, aktJahr)
                    Dim maid = SQLDienst.getMaIdByEtrId(aktMitarbeiterEintrag)
                    If maid <> "" Then
                        SQLDienst.updateDienstEintragVonBisBemWOCHEChangeByMitId(CInt(maid), montag, montag.AddDays(4), TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, niederlassung)
                    End If
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            Else 'für diesen Eintrag
                SQLDienst.updateDienstEintragArtBemerkungChange(aktMitarbeiterEintrag, TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text)
            End If
            cbxChangeForWo.Checked = False
        Catch ex As Exception
            MsgBox("Fehler beim Speichern des Eintrages.")
        End Try
        'Where dsteintr_id=aktMitarbeiterEintrag
        initDienstplan()
        setDetails(entryId_TMP)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        TextBox1.Text = "10:00"
        TextBox2.Text = "19:00"
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        AbwesenheitEintragen("KS")
        Exit Sub
        Dim frmDiestEintrag As New frmDiestEintrag
        frmDiestEintrag.niederlassung = niederlassung
        frmDiestEintrag.art = "KS"
        frmDiestEintrag.Show()
    End Sub



    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        AbwesenheitEintragen("DR")
        Exit Sub
        Dim frmDiestEintrag As New frmDiestEintrag
        frmDiestEintrag.niederlassung = niederlassung
        frmDiestEintrag.art = "DR"
        frmDiestEintrag.Show()
    End Sub


    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        Dim frmUrlaubsplaner As New frmUrlaubsplaner
        frmUrlaubsplaner.niederlassung = niederlassung
        frmUrlaubsplaner.ShowDialog()
        Exit Sub
        frmDienstAbwesenheitenUebersicht.Show()
    End Sub

    Private Sub cboQSSpaet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboQSSpaet.SelectedIndexChanged
        Dim montag As Date = CalendarWeek(aktWoche, aktJahr)

        'SONNTAG
        Dim von = getDefaultTimeBySchicht("NACHT", "von", montag.AddDays(6).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
        Dim bis = getDefaultTimeBySchicht("NACHT", "bis", montag.AddDays(6).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
        Dim pause = getDefaultTimeBySchicht("NACHT", "pause", montag.AddDays(6).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
        SQLDienst.updateDienstEintragArtChangeByDstMaId(CType(cboQSSpaet.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, montag.AddDays(6), "NACHT", von, bis, "", pause)


        For i = 0 To 4
            von = getDefaultTimeBySchicht("NACHT", "von", montag.AddDays(i).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
            bis = getDefaultTimeBySchicht("NACHT", "bis", montag.AddDays(i).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
            pause = getDefaultTimeBySchicht("NACHT", "pause", montag.AddDays(i).ToString("ddd", New CultureInfo("de-DE")).ToUpper)
            ' If montag.AddDays(i).DayOfWeek = 6 Then
            SQLDienst.updateDienstEintragArtChangeByDstMaId(CType(cboQSSpaet.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, montag.AddDays(i), "NACHT", von, bis, "", pause)
            ' Else
            ' SQLDienst.updateDienstEintragArtChangeByDstMaId(CType(cboQSSpaet.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, montag.AddDays(i), "NACHT", "10:00", "19:00", "10-19", "1")
            'End If
        Next



        initDienstplan()
    End Sub


    Private Function GetWeekStartDate(weekNumber As Integer, year As Integer) As Date
        Dim startDate As New DateTime(year, 1, 1)
        Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber, startDate)
        Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate)
    End Function

    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
        If IsNumeric(txtKW.Text) AndAlso txtKW.Text < 54 AndAlso txtKW.Text > 0 Then
            If IsNumeric(txtKWYear.Text) AndAlso txtKWYear.Text < 3000 AndAlso txtKWYear.Text > 2000 Then
                Me.Cursor = Cursors.WaitCursor
                aktDate = GetWeekStartDate(txtKW.Text, txtKWYear.Text)
                aktWoche = DateToWeek(aktDate).Substring(4, 2)
                aktJahr = DateToWeek(aktDate).Substring(0, 4)
                initWeekInfo()
                initDienstplan()
                Me.Cursor = Cursors.Default
            End If
        End If
    End Sub

    Private Sub txtKW_KeyDown(sender As Object, e As KeyEventArgs) Handles txtKW.KeyDown, txtKWYear.KeyDown
        If e.KeyCode = Keys.Enter Then Button11.PerformClick()
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
        Exit Sub
        'Dim pf As New cProgramFunctions
        'pf.KWAbschluss(niederlassung, aktJahr, aktWoche, SCHICHT)
        'initDienstplan()

    End Sub

    Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
        AbwesenheitEintragen("BS")
    End Sub



    Private Sub Button16_Click_1(sender As Object, e As EventArgs) Handles Button16.Click
        If vbYes = MsgBox("Möchten Sie die Woche wirklich löschen?", vbYesNoCancel) Then
            Dim datum As Date = CalendarWeek(aktWoche, aktJahr)
            SQLDienst.delDienstplanEintraege(datum, datum.AddDays(6), niederlassung)
            SQLDienst.delDienstplanUeberSdtMa(aktWoche, aktJahr, niederlassung)
            initDienstplan()
        End If
    End Sub


    Private Sub btnDetails_Click_1(sender As Object, e As EventArgs) Handles btnDetails.Click
        initDetails(False)
    End Sub



    Sub initDetails(refresh As Boolean)
        If refresh Then 'nur Aktualisieren
            If usrDetailsTMP.Visible Then usrDetailsTMP.init(CalendarWeek(aktWoche, aktJahr), niederlassung)
            Exit Sub
        End If

        If usrDetailsTMP.Visible Then
            usrDetailsTMP.Visible = False
        Else
            usrDetailsTMP.init(CalendarWeek(aktWoche, aktJahr), niederlassung)
            usrDetailsTMP.Visible = True
        End If
    End Sub
  

End Class