/*
 * JS-Datei für event.tpl
 */

/*
 if (user_hasRight_17) {
 //AutoComplete für Empfängerauswahl
 
 jQuery(document).ready(function () {
 AutoComplete('emailToContact');
 //AutoComplete('emailToCC');
 AutoComplete('emailToSupport');
 });
 
 //Hilfsfunktionen fürs AutoComplete der Zus.Empfänger
 //Daten kommen im format: eMail|Name|Company
 function selectItem(li) {
 return false;
 }
 function formatItem(row) {
 return row[1] + " < " + row[0] + " > " + row[2];
 }
 function countInstances(string, word) {
 var substrings = string.split(word);
 return substrings.length - 1;
 }
 
 function AutoComplete(FieldID) {
 if (FieldID === 'emailToContact') {
 var url = 'index.php?module=ticket&event=AutoCompleteMailRecipients';
 } else if (FieldID === 'emailToSupport') {
 var url = 'index.php?module=ticket&event=AutoCompleteMailRecipients&justsupporter';
 } else {
 return false;
 }
 $("#" + FieldID).autocomplete(url, {
 minChars: 2,
 matchSubset: 1,
 matchContains: 1,
 cacheLength: 1,
 onItemSelect: selectItem,
 formatItem: formatItem,
 multiple: true,
 multipleSeparator: '; ',
 width: 400,
 max: 0,
 scroll: true,
 scrollHeight: 180
 });
 
 $("#" + FieldID).result(function (event, data, formatted) {
 
 if (data) {
 var str = $("#" + FieldID).val();
 var count = countInstances(str, data[0]);
 
 if (count > 1) {   //Mailadresse schon enthalten
 var eMailArray = str.split(';');
 eMailArray.pop();
 eMailArray.pop();
 str = eMailArray.join("; ");
 $("#" + FieldID).val(str + "; ");
 }
 }
 });
 }
 
 }
 */
function ShowHide(id) {
    obj = document.getElementsByTagName("div");
    if (obj[id].style.display == 'none') {
        obj[id].style.display = 'block';
    } else {
        obj[id].style.display = 'none';
    }
}


function ValidateForm() {
    //console.log("Validate");

    var obj = document.getElementById('LongDescr');
    ValidPage = true;


    var $expense = $('#expense');

    // Prüfen, ob das Feld vorhanden, sichtbar und required ist
    if ($expense.length && $expense.is(':visible') && $expense.prop('required')) {
        var value = $.trim($expense.val());

        // Leerprüfung
        if (value === '') {
            alert('Bitte geben Sie den Aufwand in Minuten an.');
            $expense.focus();
            ValidPage = false;
        }

        // In Zahl umwandeln und prüfen ob <= 0 oder keine gültige Zahl
        var num = parseFloat(value);
        if (isNaN(num) || num <= 0) {
            alert('Der Aufwand muss eine Zahl größer als 0 sein.');
            $expense.focus();
            ValidPage = false;
        }
    }


//    if (obj.value.length < 4) {
//SCEditor funktion zum ermitteln des Inhalts verwenden (https://www.sceditor.com/api/sceditor/val/):
    if ((typeof $('#LongDescr').sceditor('instance') !== 'undefined' && $('#LongDescr').sceditor('instance').val().length < 4) ||
            (typeof $('#LongDescr').val() === 'string' && $('#LongDescr').val().length < 4)
            ) {

        obj.className = "textboxerror";
        alert(strLongDescrError);
        ValidPage = false;
    } else {
        //Ggf. Inhalt der Bearbeitung in FormularFeld übergeben (Edge)
        if ($('#LongDescr').val() == '' && typeof $('#LongDescr').sceditor('instance') !== 'undefined') {
            $('#LongDescr').val($('#LongDescr').sceditor('instance').val());
        }
        obj.className = "textbox";
        //ValidPage = true;
    }

    var projectEndDate = document.getElementById('projectEndDate');
    var expense = document.getElementById('expense');

    if (projectEndDate.value.length > 0 && expense.value != 0) {
        expense.className = "textboxerror";
        alert(strProjektEndError);
        ValidPage = false;
    } else {
        expense.className = "form-control";
        //ValidPage = true;
    }

    if (expense.value < -(60 * 60 * 24 * 10) || expense.value > (60 * 60 * 24 * 10)) {
        expense.className = "textboxerror";
        if (expense.value < 0) {
            alert(strNegativeExpenseError);
        } else {
            alert(strToMuchExpense);
        }
        ValidPage = false;
    } else {
        expense.className = "textbox";
        //ValidPage = true;
    }

    if (typeof (ProcTypErr) === "string") {
        var ProcTyp = $("#processingtype");
        if (ProcTyp) {
            if (parseInt(ProcTyp.val()) === 0) {
                $("#ProcTypeField").addClass('textboxerror');
                alert(ProcTypErr);
                ValidPage = false;
            } else {
                $("#ProcTypeField").removeClass('error');
            }
        }
    }

    if (isModifiyAbleTicketDate) {

        var TicketDate = document.getElementById('TicketDate');
        var EventDate = document.getElementById('eventdate');

        if (EventDate == null)
            EventDate = Date($.now());
        if (EventDate.value.length > 0) {
            if (string2date(EventDate.value) == null) {
                ValidPage = false;
                EventDate.className = "textboxerror";
            } else {
                var arrDate = EventDate.value.split('.');
                var arrYT = arrDate[2].split(' ');
                var arrTime = arrYT[1].split(':');
                var EventDateTimestamp = Date.UTC(arrYT[0], arrDate[1] - 1, arrDate[0], arrTime[0] - 1, arrTime[1]);

                if ((EventDateTimestamp / 1000 + 60) < TicketDate.value) {
                    check = confirm(strConfirmTicketDateChange);
                    if (check) {
                        document.getElementById('editEditDate').value = 1;
                        //ValidPage = true;
                    } else {
                        ValidPage = false;
                    }
                }
            }
        }
    }

    if (document.getElementById('close').value == 1 && document.getElementById('EditDateFuture').value == 1) {
        alert(strTicketDateIsFutureError);
        ValidPage = false;
    }

    if (!checkDecider())
    {
        alert(strDeciderMandatory);
        ValidPage = false;
    }

    if (ValidPage) {
        document.getElementById("EventForm").submit();
        self.parent.fancyBoxClose();
    }
}

function checkDecider() {
    var Result = true;
    Decider = $("#DecisorSelect2").val();

    if (Decider == null)
    {
        $.ajax({
            async: false,
            type: 'GET',
            url: "index.php?module=ticket&event=CheckDeciderMandatory",
            data: {Decider: Decider, TicketID: TicketID},
            success: function (data) {
                Result = (0 < parseInt(data)) ? true : false;
            }
        });
    }
    return Result;
}

function string2date(string) {
    if (!string)
        return null;
    string += '';
    string = string.replace(/[-\/]/g, '.'); // Trennzeichen normalisieren
    string = string.replace(/[^0-9.: ]/g, ''); // ungültige Zeichen entfernen
    string = string.replace(/ +/g, ' '); // doppelte Leerzeichen entfernen
    var uhr = string.split(" "); // Uhrzeit abtrennen
    var split = uhr[0].split(".");
    var day = parseInt(split[0], 10);
    var month = parseInt(split[1] || 0, 10);
    var year = parseInt(split[2] || 0, 10);

    if (isNaN(year))
        year = getFullYear();

    var check = new Date(year, month - 1, day);
    if (uhr[1]) {
        //Wenn die Uhrzeit nicht im Format hh:mm ist => Fehler
        if (uhr[1].length != 5)
            return null;

        var uhr = uhr[1].split(':');

        //Wenn die Stunden oder minuten nicht stimmen => Fehler
        if ((uhr[0] < 0 || uhr[0] > 23) || (uhr[1] < 0 || uhr[1] > 59))
            return null;

        check.setHours(uhr[0] || 0);
        check.setMinutes(uhr[1] || 0);
    } else {
        //Ist keine Uhrzeit angegeben => Fehler
        return null;
    }
    var day2 = check.getDate();
    var year2 = getFullYear(check);
    var month2 = check.getMonth() + 1;
    return (year2 == year && month == month2 && day == day2) ? check
            : null;
}

function getFullYear(date) {
    if (!date)
        date = new Date();
    if (typeof date.getFullYear != 'undefined')
        return date.getFullYear();
    var year = date.getYear();
    if (year < 1000)
        year += 2000;
    return year;
}

function closeWindow(id) {
    if (isActivityTicket) {
        self.parent.location.href = "index.php?module=ticket&event=show&id=" + id;
        //self.parent.$("#tab-history-form").submit();
        self.parent.focus();
        self.parent.$.fancybox.close();
    } else {
        //self.parent.location.href = "index.php?module=ticket&event=show&id="+id+"#tab-history";
        self.parent.$("#tab-history-form").submit();
        self.parent.focus();
        self.parent.$.fancybox.close();
    }

}

function showWindow(url, title, width, height) {
    width = parseInt(width);
    height = parseInt(height);
    var left = (screen.availWidth - width) / 2;
    var top = (screen.availHeight - height) / 2;
    var windowOptions = "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + ",dependent=yes,location=no,menubar=no,scrollbars=no,status=no,toolbar=no";
    if (typeof (userwindow) == "object") {
        userwindow.close();
    }
    userwindow = window.open(url, title, windowOptions);
    userwindow.focus();
}

function SwitchCheckBox(cb) {
    $('#notpulbic').prop("disabled", true);
    $('#requiredaction').prop("disabled", false);
}


function transferAddress(el, Target) {
    var Target = document.getElementById(Target);
    if (el.value != '' && Target.value.indexOf(el.value) < 0) {
        if (Target.value != '')
            Target.value = Target.value + "; ";
        Target.value = Target.value + el.value;
        el.selected = true;
    }
}

$(".datetimepicker").datetimepicker({
    currentText: 'Jetzt',
    closeText: 'OK',
    timeText: 'Zeit',
    hourText: 'Stunde'
});


$('#RecipientsContact').on("change", function (e) {
    var selected = $(e.target).val();
    if (selected) {
        $('#contactmail').val(1);
    } else {
        $('#contactmail').val(0);
    }
});

$("#addAttachments").select2({theme: 'bootstrap-5'});

$(document).on('change', ':file', function () {
    var filePath = $(this).val();
    var fileName = filePath.replace(/^.*[\\\/]/, '')

    var input = $(this),
            numFiles = input.get(0).files ? input.get(0).files.length : 1,
            label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
    $("#FileSelectionLabel").html(label);

    $("#addAttachments").prepend(
            $('<option></option>').val('fromThisEvent').html(fileName)
            );
    $("#addAttachments").select2({theme: 'bootstrap-5'});
});







/*
 $("#useEditor").on("click", function () {
 
 $("#useEditor").hide();
 
 $("#LongDescr").sceditor({
 format: "bbcode",
 style: "includes/js/sceditor-2.1.2/minified/jquery.sceditor.default.min.css",
 toolbar: "bold,italic,underline,subscript,superscript,horizontalrule,bulletlist,orderedlist|font,color|pastetext,source,maximize|insertSnippet,addSnippet,showSnippetlist",
 //toolbar: "bold,italic,underline,subscript,superscript,horizontalrule,bulletlist,orderedlist|font,color|pastetext,source,maximize",
 colors: '#000|#F00|#11C11D|#00F|#B700B7|#FF8C00|#008080|#808080|#D3D3D3',
 emoticonsEnabled: false,
 charset: 'ISO-8859-1',
 autoUpdate: true,
 width: '85%',
 //autoExpand: true,
 autofocus: true,
 enablePasteFiltering: true,
 locale: strUserLang
 })   
 
 })
 */




$(".dialog_medium").fancybox({
    maxWidth: 1000,
    maxHeight: 1000,
    closeClick: false,
    autoResize: false,
    autoCenter: true,
    'autoSize': false
});

$(".dialog_ticketlist").fancybox({
    type: 'iframe',
    autoSize: false,
    autoResize: true,
    autoCenter: true,
    beforeLoad: function () {
        this.width = 1300;
        this.height = 600;
    }
});

$("#addSnippetForm").submit(function (event) {
    // Das eigentliche Absenden verhindern
    event.preventDefault();

    // Das sendende Formular und die Metadaten bestimmen
    var form = $(this); // Dieser Zeiger $(this) oder $("form"), falls die ID form im HTML exisitiert, klappt übrigens auch ohne jQuery ;)
    var action = form.attr("action"), // attr() kann enweder den aktuellen Inhalt des gennanten Attributs auslesen, oder setzt ein neuen Wert, falls ein zweiter Parameter gegeben ist
            method = form.attr("method"),
            data = form.serialize(); // baut die Daten zu einem String nach dem Muster vorname=max&nachname=Müller&alter=42 ... zusammen

    // Der eigentliche AJAX Aufruf
    $.ajax({
        url: action,
        type: method,
        data: data
    }).done(function (data) {
        // Bei Erfolg
        //alert("Erfolgreich:" + data);
        form.find('input:text, input:password, input:file, select, textarea').val('');
        $("#addSnippetForm").trigger("reset");
        $.fancybox.close();
    }).fail(function () {
        // Bei Fehler
        alert("Fehler!");
    }).always(function () {
        // Immer
        //alert("Beendet!");
    });
});

$('#expense').on('blur', function () {
    let input = $(this).val().trim().toLowerCase().replace(/\s+/g, '');

    let minutes = 0;

    // 1,5h → 1.5h
    input = input.replace(',', '.');

    // Extrahiere Stunden (z. B. 1.5h, 2h, 3std)
    const hourMatch = input.match(/(\d+(\.\d+)?)(h|std)/);

    // Extrahiere Minuten (z. B. 30m, 45min)
    const minMatch = input.match(/(\d+)(m|min)/);

    // Nur Zahl = Minuten direkt
    const onlyNumber = input.match(/^\d+$/);

    if (hourMatch) {
        minutes += parseFloat(hourMatch[1]) * 60;
    }

    if (minMatch) {
        minutes += parseInt(minMatch[1]);
    }

    if (onlyNumber) {
        minutes = parseInt(input);
    }

    if (minutes > 0) {
        $(this).val(Math.round(minutes));
    }
});
