var isEnddateSet;
$(document).ready(function () {
    if (!$("#zeiterfassung").length) {
        return;
    }

    toggleErrorPopup2('errorPopupDiv2');

    $("#leistungen_select,#kategorien_select,#recordLoader_select").prop("disabled", false);
    
    toggleSelectClassesForElement("#kategorien_select", "#kategorien-select-container");
    toggleSelectClassesForElement("#leistungen_select", "#leistungen-select-container");
    toggleSelectClassesForElement("#recordLoader_select", "#record-loader-select-container");

    //Lade Dokumentationsreiter aus Bewo 
    checkDokuReiter();

    //ist EndDate Gewünscht
    checkEndDate();

    initBeWoMobile(loadGoalsUrl);

    var h = $("#datum_textbox").css("height");

    $(".dropdownlist-for").css("height", h);

    $("#statistik-button").css("height", h);
    $("#statistik-button").css("width", h);

    $("#statistik-button-td").css("width", h);
    
    

    if (localStorage.getItem("Zeitdaten") != null || localStorage.getItem("Kalenderdaten") != null) {
        console.log("Ich bin hier drinne weil Storage vorhanden");
         if (document.getElementById("ErrorZeiterfassungAfterCrashSchalter").value == 1 ||
                document.getElementById("ErrorZeiterfassungAfterCrashSchalter").value == null ||
                document.getElementById("ErrorZeiterfassungAfterCrashSchalter").value == 0) {
                console.log("Ich bin hier beim Laden einer Zeiterfassung  ");
                LoadOnly(1, 2);
                DeletStorage(1);
                DeletStorage(2);
            } else {
                ErrorZeiterfassungAfterCrash();
                console.log(" ich bin hier nach dem Crash ")
            } 
    } else {
        console.log("Ich bin hier drinne weil Storage nicht vorhanden");
    }
   
   
    ErfolgteSpx();
   
    vm = new KlientenVM();
    ko.applyBindings(vm);

    loadSettingsAccordingToBWP();  
    
});



function initBeWoMobile(actionPath) {
    try {
        $("#recordLoader_select,#kategorien_select,#leistungen_select").prop("disabled", true);

        toggleSelectClassesForElement("#kategorien_select", "#kategorien-select-container");
        toggleSelectClassesForElement("#leistungen_select", "#leistungen-select-container");
        toggleSelectClassesForElement("#recordLoader_select", "#record-loader-select-container");

        var selectedSC = $($("#scDropDown")).find(":selected").val();

        if (selectedSC !== "-1") {
            $("#recordLoader_select").prop("disabled", false);

            if ($("#anlegenEditierenBtn").val() == "Anlegen") {
                activateForm(actionPath);
            }

            $("#datum_textbox").val(getDateStringWithLeadingZeros(new Date()));

           // $("#enddatum_textbox").val($("#datum_textbox").val());
        }

        $(".not-required-input").on(
			"click blur change focus",
			function () {
			    var v = $(this).attr("id");
			    setTimeout(function () {
			        toggleLabel(v);
			    }, 1);
			}
		);

        $("#start_textbox").on("blur", function () {
            var startHasValue = $("#start_textbox").val() != "";
            var endHasValue = $("#ende_textbox").val() != "";
            var durationHasValue = $("#duration_textbox").val() != "";

            if (startHasValue && endHasValue) {
                calcDurationByStartEnd();
            } else if (startHasValue && durationHasValue) {
                calcEndByStartDuration();
            }
        });

        $("#ende_textbox").on("blur", function () {
            var startHasValue = $("#start_textbox").val() != "";
            var endHasValue = $("#ende_textbox").val() != "";
            var durationHasValue = $("#duration_textbox").val() != "";

            if (endHasValue && startHasValue) {
                calcDurationByStartEnd();
            } else if (endHasValue && durationHasValue) {
                calcStartByEndDuration();
            }
          
        });

        //$("#ende_textbox").on("input", function () {
        //    validateTimeField("#ende_textbox");
        //});

        //$("#start_textbox").on("input", function () {
        //    validateTimeField("#start_textbox");
        //});

        $("#duration_textbox").on("blur", function () {
            var startHasValue = $("#start_textbox").val() != "";
            var endHasValue = $("#ende_textbox").val() != "";
            var durationHasValue = $("#duration_textbox").val() != "";

            clearZED();

            if (durationHasValue && startHasValue) {
                calcEndByStartDuration();
            } else if (durationHasValue && endHasValue) {
                calcStartByEndDuration();
            }
           
        });
    } catch (err) {
        console.log("Fehler: " + err.message);
    }
}

function toggleSelectClassesForElement(elementIdentifier, parentElement) {
    var enabled = $(elementIdentifier).prop("disabled") === false;

    if (enabled) {
        $(parentElement).removeClass("disabled-select-container");
        $(parentElement).addClass("styled-select-div");
    } else {
        $(parentElement).removeClass("styled-select-div");
        $(parentElement).addClass("disabled-select-container");
    }
}


function toggleErrorPopup2(errorMessage) {
    var isDisplayNone = $("#errorPopupDiv2").css("display") == "none";
    var displayValue = isDisplayNone ? "block" : "none";

    $("#errorPopupDiv2").css("display", displayValue);
    $(".modalWrapper").css("display", displayValue);
    $(".modalWrapper").css("height", $(document).height());

    if (isDisplayNone) {
        $("#errorPopupText2").text(errorMessage);

        var h = 0;
        var t = $("#errorPopupTitle2").outerHeight();
        var u = $("#errorPopupText2").outerHeight();
        var v = $("#errorPopupBtnDiv2").outerHeight();
        var w = $("#errorPopupOkBtn2").outerHeight();

        h += t + u + v + w + w;

        $("#errorPopupDiv2").css("height", h + "px");

        $("#errorPopupDiv2").css("top", window.pageYOffset + window.innerHeight / 2 - h / 2);
        $("#errorPopupDiv2").css("margin-top", "0");
    } else {
        $("#errorPopupDiv2").css("margin-top", "auto");
    }
}


function logoutSettingsAccordingToBWP(timeoutTime) {
    if (timeoutTime > 0) {
        timeoutTime = timeoutTime * 1000 * 60;
        clearTimeout();
        setTimeout(function() {
            $.ajax({
                type: "POST",
                url: LogoutUrl,
                success: function() {
                    writeFatalErrorMessage("Ihre Sitzung ist abgelaufen.");

                    setTimeout(function() {
                        location.reload();
                    }, 3000);

                },
                error: function() {}
            });
        }, timeoutTime);
    }
}

var TimeoutSetting;

function loadSettingsAccordingToBWP() {
    $.ajax({
        type: "GET",
        url: LoadSessionSettingsFromBWPUrl,
        success: function (json) {
            var s  = $.parseJSON(json);
            TimeoutSetting = parseInt(s);
            logoutSettingsAccordingToBWP(TimeoutSetting);
        }
    });
}

function checkEndDate() {
    $.ajax({
        type: "GET",
        url: CheckEndDateUrl,
        success: function (json) {

            var s = $.parseJSON(json);
            var EndDateSetting = parseInt(s);

            if (EndDateSetting == 1) {
                document.getElementById('EndDate_div').style.display = 'block';
                $("#enddatum_textbox").val($("#datum_textbox").val());
            }
            else {           
                document.getElementById('EndDate_div').style.display = 'none';
            }
        }
    });
}

function checkDokuReiter() {
    $.ajax({
        type: "GET",
        url: CheckDokuReiterUrl,
        success: function (json) {

            var s = $.parseJSON(json);
           
            var x = s.length;
          
            if (x == 0) {
                document.getElementById('tddokureiter').style.display = 'none';
                document.getElementById('trnormalDoku').style.display = 'table-row';//block
                document.getElementById('notiz_textbox').style.width = '100%'; //795 || 200
            }
            if (x == 1) {
                document.getElementById('tddokureiter').style.display = 'none';
                document.getElementById('trnormalDoku').style.display = 'table-row';            
                document.getElementById('notiz_textbox').style.width = '100%'; // 765
                document.getElementById('trnormalDokuLabel').textContent = s[0].TypeDescription;
            }
            if (x == 2) {
                document.getElementById('DokName1').textContent = s[0].TypeDescription;
                document.getElementById('DokName2').textContent = s[1].TypeDescription;

                document.getElementById('notiz_textbox1').style.width = '40%';//100%
                document.getElementById('notiz_textbox2').style.width = '40%';
                
                document.getElementById('Dokumentation1').style.display = 'block'; // block
                document.getElementById('Dokumentation2').style.display = 'block';

                document.getElementById('Dokumentation1').style = 'width: 250%'; //247.5% || 250 
                document.getElementById('Dokumentation2').style = 'width: 250%';
            }
            if (x == 3) {
                document.getElementById('DokName1').textContent = s[0].TypeDescription;
                document.getElementById('DokName2').textContent = s[1].TypeDescription;
                document.getElementById('DokName3').textContent = s[2].TypeDescription;
                
                document.getElementById('notiz_textbox1').style.width = '50%';
                document.getElementById('notiz_textbox2').style.width = '50%';
                document.getElementById('notiz_textbox3').style.width = '50%';

                document.getElementById('Dokumentation1').style.display = 'block';
                document.getElementById('Dokumentation2').style.display = 'block';
                document.getElementById('Dokumentation3').style.display = 'block';

                document.getElementById('Dokumentation1').style = 'width: 200%'; //133.3% || 165%
                document.getElementById('Dokumentation2').style = 'width: 200%';
                document.getElementById('Dokumentation3').style = 'width: 200%';  
            }
            if (x == 4) {
                document.getElementById('DokName1').textContent = s[0].TypeDescription;
                document.getElementById('DokName2').textContent = s[1].TypeDescription;
                document.getElementById('DokName3').textContent = s[2].TypeDescription;
                document.getElementById('DokName4').textContent = s[3].TypeDescription;


                document.getElementById('notiz_textbox1').style.width = '76.9%';
                document.getElementById('notiz_textbox2').style.width = '76.9%';
                document.getElementById('notiz_textbox3').style.width = '76.9%';
                document.getElementById('notiz_textbox4').style.width = '76.9%';

                document.getElementById('Dokumentation1').style.display = 'block';
                document.getElementById('Dokumentation2').style.display = 'block';
                document.getElementById('Dokumentation3').style.display = 'block';
                document.getElementById('Dokumentation4').style.display = 'block';

                document.getElementById('Dokumentation1').style = 'width: 130%';
                document.getElementById('Dokumentation2').style = 'width: 130%';
                document.getElementById('Dokumentation3').style = 'width: 130%';
                document.getElementById('Dokumentation4').style = 'width: 130%';
            }
            if (x == 5) {
                document.getElementById('DokName1').textContent = s[0].TypeDescription;
                document.getElementById('DokName2').textContent = s[1].TypeDescription;
                document.getElementById('DokName3').textContent = s[2].TypeDescription;
                document.getElementById('DokName4').textContent = s[3].TypeDescription;
                document.getElementById('DokName5').textContent = s[4].TypeDescription;

                document.getElementById('notiz_textbox1').style.width = '101%';
                document.getElementById('notiz_textbox2').style.width = '101%';
                document.getElementById('notiz_textbox3').style.width = '101%';
                document.getElementById('notiz_textbox4').style.width = '101%';
                document.getElementById('notiz_textbox5').style.width = '101%';

                document.getElementById('Dokumentation1').style.display = 'block';
                document.getElementById('Dokumentation2').style.display = 'block';
                document.getElementById('Dokumentation3').style.display = 'block';
                document.getElementById('Dokumentation4').style.display = 'block';
                document.getElementById('Dokumentation5').style.display = 'block';

                document.getElementById('Dokumentation1').style = 'width: 99%';
                document.getElementById('Dokumentation2').style = 'width: 99%';
                document.getElementById('Dokumentation3').style = 'width: 99%';
                document.getElementById('Dokumentation4').style = 'width: 99%';
                document.getElementById('Dokumentation5').style = 'width: 99%';
            }
        }
    });
}