
/* Für Bootstrap */
var AttachmentList = false;
var objAttachmentList;
var TicketID = 0;
var Activity = false;

function showContactBox() {

    var userbox = document.getElementById("ContactBox");
    var txtfield = document.getElementById("contact");
    var spantop = absTop(txtfield);
    var spanleft = absLeft(txtfield);
    var spanwidth = txtfield.offsetWidth;
    var spanheight = txtfield.offsetHeight;
    spantop = spantop + spanheight;
    spanwidth = spanwidth - 2;

    if (IE) {
        spantop += 1;
        spanleft += 1;
    }

    userbox.style.width = spanwidth + "px";
    userbox.style.left = spanleft + "px";
    userbox.style.top = spantop + "px";

    if (userbox.style.visibility != "visible" || position_left != spanleft
            || position_top != spantop) {

        userbox.style.display = "block";
        position_top = spantop;
        position_left = spanleft;
        userbox.style.visibility = "visible";

    } else {
        userbox.style.visibility = "hidden";
        userbox.style.display = "none";
    }
}

function setTicketID(tid) {
    TicketID = tid;
}


function getAttachments(tid, page) {
    page = page || 1;

    TicketID = (0 < tid) ? tid : TicketID;
    AttachmentList = true;
    objAttachmentList = document.getElementById("AttachmentList");
    objAttachmentList.innerHTML = "";
    if (page > 1) {
        PageParameter = "&pos=" + page;
    } else {
        PageParameter = '';
    }

    if (Activity) {
        $("#AttachmentList").load("index.php?module=upload&event=showAttachments&activityid=" + aid + "&preacts=" + PreActs + PageParameter);
    } else {
        $("#AttachmentList").load("index.php?module=upload&event=showAttachments&tid=" + TicketID + PageParameter);
    }
}

function getImages(tid, page) {


    page = page || 1;

    TicketID = (0 < tid) ? tid : TicketID;
    AttachmentList = true;
    objAttachmentList = document.getElementById("AttachmentList");
    objAttachmentList.innerHTML = "";
    if (page > 1) {
        PageParameter = "&pos=" + page;
    } else {
        PageParameter = '';
    }

    if (Activity) {
        $("#ImagesList").load("index.php?module=upload&event=showImageAttachments&activityid=" + aid + "&preacts=" + PreActs + PageParameter);
    } else {
//        $.get("index.php?module=upload&event=showImageAttachments&tid=" + TicketID + PageParameter, function(res){
//           $("#ImagesList").html(res);
//        });
        $("#ImagesList").load("index.php?module=upload&event=showImageAttachments&tid=" + TicketID + PageParameter);
    }
}

function getActivityAttachments(aid, PreActs) {
    if (PreActs == undefined) {
        addPreActs = "";
    } else {
        addPreActs = "&preacts=" + PreActs
    }


    TicketID = aid;
    Activity = true;
    AttachmentList = true;
    $("#AttachmentList").load("index.php?module=upload&event=showAttachments&activityid=" + aid + addPreActs);
}


function switchPage(page, tid) {
    makeHttpRequest("index.php?module=upload&event=AJAXUploadList&tid=" + tid + "&pos=" + page, "buildAttachmentList", true);
}

function closeAttachmentPopUp(tid) {
    setTimeout("closePopup(" + tid + ")", 1000);
    userwindow.close();
}

function closePopup(tid) {
    if (tid > 0) {
        getAttachments(tid);
    } else {
        getAttachments();
    }
}


function loadProject(id, tid) {
    if (id > 0) {
        makeHttpRequest("index.php?module=ticket&event=showProject&id=" + id + "&tid=" + tid, "showProject", false);
    } else {
        document.getElementById('projectdata').innerHTML = '';
    }

}

function showProject(xmldoc) {
    document.getElementById('projectdata').innerHTML = xmldoc;
}



/// Autocompletition:

//Quelle: http://www.easy-coding.de/wiki/html-ajax-und-co/autocomplete-tutorial-mit-jquery.html

function selectItem(li) {
    return false;
}
function formatItem(row) {
    //return row[0] + "<br><i>" + row[1] + "</i>";
    return row[0];
}

// // Quelle: http://stackoverflow.com/questions/4098883/i-need-an-expample-of-jquery-autocomplete-returning-id-and-name-using-ajax
//

function nqi_search(task, text_name, id_name)
{

}

function changeContact(contactid, contactname) {
    makeHttpRequest("index.php?module=contact&event=TSearchContact&tid=" + TicketID + "&cid=" + contactid + "&save=1&confirmOnHold=hold", "ContactChanged", false);
    $("#contact_id").val(contactid);
    $("#contact").val(contactname);

}
function ContactChanged() {
    $("#contact_message").html("<span class=\"error\">" + contact_message + "</span>");
}

function Category1Changed(data) {
    $("#category1_message").html("<span class=\"error\">" + category1_message + "</span>");

}
function Category2Changed() {
    $("#category2_message").html("<span class=\"error\">" + category2_message + "</span>");
}
function GroupChanged() {
    $("#group_message").html("<span class=\"error\">" + group_message + "</span>");

}
function SupporterChanged() {
    $("#supporter_message").html("<span class=\"error\">" + supporter_message + "</span>");
}
function ChangeRefTicket() {
    location.reload();
}

function gueltigesDatum(datum) {

    var zeit;

    //(Schritt 1) Fehlerbehandlung
    if (!datum)
        return false;
    datum = datum.toString();

    // Schritt 2) In Zeit und Datum aufteilen
    datum = datum.split(" ");
    if (datum.length > 1) {
        if (datum[0].indexOf(".") != -1) {
            zeit = datum[1];
            datum = datum[0];
        } else {
            zeit = datum[0];
            datum = datum[1];
        }
    } else {
        zeit = "";
        datum = datum[0];
    }

    //(Schritt 3) Aufspaltung des Datums
    datum = datum.split(".");
    if (datum.length != 3)
        return false;

    //(Schritt 4) Entfernung der fuehrenden Nullen und Anpassung des Monats
    datum[0] = parseInt(datum[0], 10);
    datum[1] = parseInt(datum[1], 10) - 1;

    //(Schritt 5) Behandlung Jahr nur zweistellig
    if (datum[2].length == 2)
        datum[2] = "20" + datum[2];

    //(Schritt 6) Erzeugung eines neuen Dateobjektes
    var kontrolldatum = new Date(datum[2], datum[1], datum[0]);

    //(Schritt 7) Vergleich, ob das eingegebene Datum gleich dem JS-Datum ist
    if (kontrolldatum.getDate() == datum[0] &&
            kontrolldatum.getMonth() == datum[1] &&
            kontrolldatum.getFullYear() == datum[2]) {

        //(Schritt 8) Ueberpruefung der Zeitangabe
        if (zeit.length > 0) {

            //(Schritt 9) Aufsplatung der Zeitangabe
            zeit = zeit.split(":");
            if (zeit.length != 2)
                return false;

            //(Schritt 10) Entfernung der fuehrenden Nullen
            zeit[0] = parseInt(zeit[0], 10);
            zeit[1] = parseInt(zeit[1], 10);

            //(Schritt 11) Zeitangabe liegt im gueltigen Bereich
            if (zeit[0] > 23 || zeit[0] < 0 || zeit[1] > 59 || zeit[1] < 0) {
                return false;
            }
        }

        // Alle Angaben sind in Ordnung
        return true;

    } else
        return false;
}


//Initialisiert Javascript für Kategorieauswahl:
//var CatTree = new WebFXLoadTree(ts_Kategorien, "index.php?module=category&event=xml&type=ticket", "javascript:setCategoryValue(0, 0, '')");
$(document).ready(function () {
    if (typeof aid !== 'undefined') {

    } else {
        getAttachments(TicketID);
        getImages(TicketID);
    }


    var ProjectID = $("#ProjectID").val();
    if (0 < ProjectID) {
        loadProject(ProjectID, TicketID);
    }

//    $("#tabs").tabs();
    if (bool_ActionRequired) {
        $('#RequiredActionModal').modal('show');
    }



    $("#DocumentTabLink").on("click", function () {
        getAttachments(TicketID);
    });

    $("#ProjectTabLink").on("click", function () {
        var ProjectID = $("#ProjectID").val();
        if (0 < ProjectID) {
            loadProject(ProjectID, TicketID);
        }
    });


    $(".dialog").fancybox({
        maxWidth: 595,
        maxHeight: 600,
        closeClick: false,
        keys: {
            close: [27] //escape key
        },
        afterShow: function () {
            //this.wrap.draggable();
        }
    });

    $(".dialog").fancybox({
        maxWidth: 595,
        maxHeight: 600,
        closeClick: false,
        keys: {
            close: [27] //escape key
        },
        afterShow: function () {
            //this.wrap.draggable();
        }
    });

    $(".video-diaglog").fancybox({
        maxWidth: 600,
        maxHeight: 400,
        closeClick: false,
        keys: {
            close: [27] //escape key
        },
        afterShow: function () {
            //this.wrap.draggable();
        }
    });


    $(".dialog_editTicket").fancybox({
        maxWidth: 595,
        maxHeight: 810,
        closeClick: false,
        loop: false,
        keys: {
            //toggle: [32]
        },
        beforeLoad: function () {
            if (!checkForm_Edit()) {
                return false;
            }
        },
        afterShow: function () {
            $('.fancybox-iframe').contents().find('#LongDescr').focus();
            this.wrap.draggable();
            this.wrap.css("cursor", "move");
            $('.fancybox-iframe').contents().find("#useEditor").trigger("click");
        },
        helpers: {
            overlay: {closeClick: false} // prevents closing when clicking OUTSIDE fancybox
        },
        playspeed: 3000000
    });

    $(".ImageDialog").fancybox();
    $(".dialog_TicketPrintview").fancybox({
        width: '90%',
        maxWidth: 1200,
        maxHeight: 600,
        closeClick: false,
        loop: false,
        keys: {
            //toggle: [32]
        }
    });
    
    $(".dialog_big").fancybox({
        width: '90%',
        maxWidth: 1800,
        maxHeight: 800,
        closeClick: false,
        loop: false,
        keys: {
            //toggle: [32]
        }
    });
    $(".dialog_small").fancybox({
        maxWidth: 250,
        maxHeight: 220,
        closeClick: false
    });

    $(".dialog_dynamicsize").fancybox({
        closeClick: false,
        fitToView: false,
        autoSize: false,
        beforeShow: function () {
            // added 50px to avoid scrollbars inside fancybox
            this.width = ($('.fancybox-iframe').contents().find('form').width()) + 10;
            this.height = ($('.fancybox-iframe').contents().find('form').height()) + 10;
        }
    });

    $(".dialog_ticketlist")
            .fancybox({
                type: 'iframe',
                autoSize: false,
                autoResize: true,
                autoCenter: true,
                scrolling: 'no',
                keys: {
                    //toggle: [32]
                },
                beforeLoad: function () {
                    this.width = 1300;
                    this.height = 600;
                }
            });
    $(".fancybox")
            .attr('rel', 'gallery')
            .fancybox({
                type: 'iframe',
                autoSize: false,
                beforeLoad: function () {
                    if ($(this.element).attr('id') == 'item1') {
                        this.width = 500;
                        this.height = 200;
                    } else {
                        this.width = 200;
                        this.height = 500;
                    }
                }
            });

    $(".datepicker").datepicker();



    Dropzone.options.myDropzone = {

        init: function () {

            this.on("queuecomplete", function (file) {
                this.removeAllFiles();
                getAttachments(TicketID);
            });
        }
    };

    $("div#DropzoneField").dropzone({
        url: "index.php?module=upload&event=uploadDocs&tid=" + TicketID,
        init: function () {
            this.on("queuecomplete", function (file) {
                this.removeAllFiles();
                getAttachments(TicketID);
            });
        }
    });



    $("#prio_id").on("change", function () {
        $.ajax({
            type: "POST",
            url: "index.php?module=ticket&event=changePriority",
            data: {tid: TicketID, save: 1, PrioID: $("#prio_id").val()}
        }).done(function (msg) {
            noty({
                text: ts_TicketPrioChanged,
                //layout: 'top',
                //theme: 'defaultTheme', // or 'relax'
                //closeWith: ['click', 'hover'],
                type: 'success',
                timeout: notifyTimeout
            });
        });
    });

    $("#isProblem").on("change", function (e) {
        var isProblem = $('#isProblem').val();
        if (isProblem == 1) {
            check_string = ts_VorfallToProblem;
        } else {
            check_string = ts_ProblemToVorfall;
        }

        bootbox.confirm(check_string, function (result) {
            if (result) {
                $.getJSON('index.php?module=ticket&event=toggleProblem', {
                    format: "json",
                    ticketid: TicketID,
                    isProblem: isProblem == 1 ? 1 : 0,
                    data: {'ticketid': TicketID, 'isProblem': isProblem}
                }).done(function (data) {
                    if (data.error) {

                        noty({
                            text: ts_ProblemVorfallError,
                            //layout: 'top',
                            //theme: 'defaultTheme', // or 'relax'
                            //closeWith: ['click', 'hover'],
                            type: 'error',
                            timeout: notifyTimeout
                        });
                    } else {
                        if (isProblem) {
                            $("#isProblemImage").attr("src", 'images/isproblem.gif');
                        } else {
                            $("#isProblemImage").attr("src", 'images/isincident.gif');
                        }

                        if (data.hasOwnProperty('groupids')) {
                            var groupidArray = [];
                            $.each(data.groupids, function (i, groupid) {
                                groupidArray.push(groupid);
                            });
                            $('#GroupSelect').val(groupidArray);
                            $('#GroupSelect').trigger('change');
                            showSupporter("#GroupSelect");
                        }
                        if (data.hasOwnProperty('message')) {
                            noty({
                                text: data.message,
                                //layout: 'top',
                                //theme: 'defaultTheme', // or 'relax'
                                //closeWith: ['click', 'hover'],
                                type: 'success',
                                timeout: notifyTimeout
                            });
                        }
                    }
                });
            } else {
                $("#isProblem").val(isProblem == 1 ? 0 : 1);
            }
        })

    })

});

//RefTicket:
if (TicketData['ticketstatusid'] != 3 && TicketData['ticketstatusid'] != 7 && bool_hasRight[8] && (TicketData['ticketstatusid'] != 9 || bool_hasRight[112])) {

}

if (bool_showAttachments && bool_hasRight[11]) {
    function RemoveAttachment(id) {
        bootbox.confirm(ts_DokumentLoeschen, function (result) {
            if (result) {
                makeHttpRequest("index.php?module=upload&event=AJAXUploadList&tid=" + TicketID + "&id=" + id, "buildAttachmentList", true);
            }
        }).addClass('bootboxzindex');
    }
}

if (bool_showAttachments && bool_hasRight[26]) {
    function AddToBlacklist(id) {
        bootbox.confirm(ts_DokumentToBlacklist, function (result) {
            if (result) {
                makeHttpRequest("index.php?module=upload&event=addAttachmentToBlacklist&id=" + id, "buildAttachmentList", true);
            }
        }).addClass('bootboxzindex');
    }
}
/*
 function showFrame(oldFrame, newFrame) {
 if (newFrame == 'Document') {
 getAttachments(TicketID);
 }
 $("#" + newFrame + "TabLink").trigger("click");
 }
 */
function buildAttachmentList() {
    getAttachments(TicketID);
}

function buildImagesList() {
    getImages(TicketID);
}

if (UserData['SecurityProjects'] && bool_hasRight[500]) {
    if (TicketData['ticketstatusid'] != 3 && TicketData['ticketstatusid'] != 7) {
        function changeLevel2ID() {

            var Level2ID = document.getElementById("Level2ID");
            var ProjectID = document.getElementById("ProjectID");
            if (ProjectID) {
                var pid = ProjectID.value;
                if (pid > 0 && Level2ID) {
                    (Level2ID.value > 0)
                            ? makeHttpRequest("index.php?module=project&event=changeLevel2&tid=" + TicketID + "&pid=" + pid + "&ref=" + Level2ID.value, "updateProjectTicketLevel", false)
                            : alert(ts_RefLevel2Select);
                } else if (pid >= 0) {
                    makeHttpRequest("index.php?module=project&event=changeLevel2&tid=" + TicketID + "&pid=" + pid, "updateProjectTicketLevel", false);
                }
            }
        }

        function updateProjectTicketLevel(xmldoc) {
//            alert(ts_changeProjectAssign);
            noty({
                text: ts_changeProjectAssign,
                //layout: 'top',
                //theme: 'defaultTheme', // or 'relax'
                //closeWith: ['click', 'hover'],
                type: 'success',
                timeout: notifyTimeout
            });
        }
    }
}

function callURL(eventid) {
    $("#Event_" + eventid).trigger("click");
}


function OpenTicketNR(ticketid)
{
    if (ticketid != '')
    {
        window.location.href = 'index.php?module=ticket&event=show&id=' + ticketid;
    } else
    {
        document.getElementById("ticketnr").className = "textboxerror";
    }
}

function NoFutureEvent() {
    if (document.getElementById('EditDateFuture').value == 1) {
        alert(ts_DateError1);
        return false;
    }
    return true;
}

function keyEvent(event)
{
    if (event.keyCode == 13) {
        OpenTicketNR(document.getElementById('ticketnr').value);
    }
}

function removeTicketConnection(ConnectionID) {
    bootbox.confirm("Wollen Sie die Verkn&uuml;pfung zum Ticket (#" + ConnectionID + ") aufheben?", function (result) {
        if (result) {
            makeHttpRequest("index.php?module=ticketlist&event=connectTicket&ConnTicketID=" + TicketID + "&removeconnection&connectionid=" + ConnectionID, "reloadPage", false);
        }
    })
    return true;
}


function removeTicketStory(ChildID) {
    bootbox.confirm("Wollen Sie die Verkn&uuml;pfung zum Ticket (#" + ChildID + ") aufheben?", function (result) {
        if (result) {
            $.post('index.php?module=ticket&event=SetStory&TicketID=' + ChildID + '&TicketStoryID=0', function () {
                $("#StoryTicket_" + ChildID).detach();
            })
        }
    })
    return true;
}


function reloadPage() {
    location.href = "index.php?module=ticket&event=show&id=" + TicketID;
}


function browseTicket(Action) {
//Ladebildschirm:
    if ('p' == Action) {
        var html = ts_LadeVorgaengerticket;
    } else {
        var html = ts_LadeNachfolgerticket;
    }


    var dialog1 = bootbox.dialog({message: '<div class="text-center">' + html + '</div>', closeButton: false});

    var Timestamp = $('#TicketTimestamp').val();
    $.ajax({
        type: "POST",
        url: "index.php?module=ticketlist&event=browseTickets",
        data: {
            ticketid: TicketID,
            PrevNext: Action,
            TicketTimestamp: Timestamp
        }
    }).done(function (LoadedTicketID) {
        if (0 < LoadedTicketID) {
//Wenn eine TicketID ermittelt wurde, dieses Ticket aufrufen
            //$('#tab-details-form').attr('action', 'index.php?module=ticket&event=show&id=' + LoadedTicketID); //this fails silently
            //$('#tab-details-form').submit();            
            window.location.replace("index.php?module=ticket&event=show&id=" + LoadedTicketID + "&tlu=" + $('#tlu').val());
        } else {
//Gibt es keine ID, Meldung ausgeben
            if ('p' == Action) {
                html = '<span class="error">Kein Vorg&auml;ngerticket vorhanden.</span>';
                $('#browseTicket_p').attr("src", "images/up_off.gif");
            } else {
                html = '<span class="error">Kein Nachfolgerticket vorhanden.</span>';
                $('#browseTicket_n').attr("src", "images/down_off.gif");
            }
            dialog1.modal('hide');
            bootbox.dialog({title: null, message: '<div class="text-center">' + html + '</div>', backdrop: true});
        }
    });
}





$("#NewTag").keypress(function (event) {
    if (event.which == 13) {
        $("#NewTag").fadeOut();
        $.ajax({
            type: "POST",
            url: 'index.php?module=ticket&event=addTag',
            data: {tid: TicketID, tag: $('#NewTag').val()}
        }).done(function (msg) {
            if (msg > 0) {
                $("#Tag_" + msg).remove().fadeOut();
                html = '<li id="Tag_' + msg + '" class="Tag TicketTag">' + $('#NewTag').val() + '</li> ';
                $('#TicketTags').append(html).fadeIn();
                $("#NewTag").val('').fadeIn();
            } else {
                alert('Fehler');
            }
        });
    }
});

function TagFilterFunktion() {

    var filter = $('#TagFilter').val();
    if (filter) {
        // this finds all links in a list that contain the input,
        // and hide the ones not containing the input while showing the ones that do
        $("#AvailableTags").find("span:not(:Contains(" + filter + "))").parent().fadeOut();
        $("#AvailableTags").find("span:Contains(" + filter + ")").parent().fadeIn();
    } else {
        $("#AvailableTags").find("li").fadeIn();
    }
    return false;
}
jQuery.expr[':'].Contains = function (a, i, m) {
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
$("#AvailableTagsHeader").on("click", function () {
    $("#AvailableTagsDiv").fadeToggle();
    if ($(this).hasClass('hiddenList')) {
        $(this).removeClass('hiddenList').addClass('visibleList').html('Verfügbare Schlagworte ausblenden');
    } else {
        $(this).removeClass('visibleList').addClass('hiddenList').html('Verfügbare Schlagworte anzeigen');
    }
})
$("#AvailableTagsDiv").hide();
if (bool_hasRight[220]) {
    $('.Tag').dblclick(function () {

        var $item = $(this);
        var $TagID = $item.attr("id").replace('Tag_', '');

        bootbox.confirm('Schlagwort wirklich löschen?', function (result) {
            if (result) {
                $.ajax({
                    type: "POST",
                    url: 'index.php?module=ticket&event=deletetag',
                    data: {tagid: $TagID}
                }).done(function (msg) {
                    if (msg > 0) {
                        $item.fadeOut(function () {
                            $item
                                    .removeClass("AvailableTag")
                                    .addClass("TicketTag")
                                    .appendTo($("#TicketTags"))
                                    .fadeIn();
                        });
                    } else {
                        alert('Fehler');
                    }
                });
            }
        })

    })
}



function clearDocumentform() {
    $("#UploadFile").find(':input').each(function () {
        switch (this.type) {
            case 'text':
            case 'textarea':
            case 'file':
                $(this).val('');
                break;
        }
    });
}




function fancyBoxClose() {
    $("#fancybox-frame").on("load", function () {
        $.fancybox.close();
    });
}

function openCategory(nr) {
    var url = "index.php?module=category&class=select&id=" + nr + "&tid=" + TicketID + "&tickettype=" + $("#TicketType").val();
    $("#dialog-category").fancybox({
        title: ts_SelectCategory,
        href: url,
        type: 'ajax',
        fitToView: false,
        autoSize: false,
        width: 500, // or whatever
        height: 500
    }).trigger("click");
}

function openCategoryRequired(nr) {
    var url = "index.php?module=category&class=select&required&id=" + nr + "&tid=" + TicketID + "&tickettype=" + $("#TicketType").val();
    $("#dialog-category").fancybox({
        title: ts_SelectCategory,
        href: url,
        type: 'ajax',
        fitToView: false,
        autoSize: false,
        width: 500, // or whatever
        height: 500,
        closeBtn: false,
        closeClick: false
    }).trigger("click");
}


if (TicketData['ticketreferenzid'] < 1 && TicketData['ticketstatusid'] != 3 && TicketData['ticketstatusid'] != 7 && (TicketData['ticketstatusid'] != 9 || bool_hasRight[112])) {

    $(document).ready(function () {
        if (bool_hasRight[2]) {

        }
        //Kategorie 1:
        if (bool_hasRight[5] && !(bool_NoCatChangeWhenForms && CategoryFormData['formularid1'] > 0)) {

        }
        //Kategorie2:
        if (bool_hasRight[5] && !(bool_NoCatChangeWhenForms && CategoryFormData['formularid2'] > 0)) {

        }
        //Group:
        if (bool_hasRight[215]) {


        }

        //Supporter:
        if (bool_hasRight[216]) {


        }

        $('#RepairEnddate').datetimepicker({
            onClose: function () {
                var RepairEnddate = $("#RepairEnddate").val();
                var url = "index.php?module=ticket&event=setRepairEnddate";
                if (gueltigesDatum(RepairEnddate)) {
                    bootbox.confirm(ts_changeRepairEnddate, function (result) {
                        if (result) {
                            $.ajax({
                                type: "POST",
                                url: url,
                                data: {tid: TicketID, save: 1, RepairEnddate: RepairEnddate}
                            }).done(function (msg) {
                                console.log(msg);
                                noty({
                                    text: msg,
                                    type: 'success',
                                    timeout: notifyTimeout
                                });

                            });
                        } else {
                            $('#RepairEnddate').val(TicketData['repairenddate']);
                        }
                    })
                } else {
                    alert("Ungültiges Datumsformat");
                }

            },
            currentText: ts_Jetzt,
            closeText: ts_OK,
            language: ts_lang

        });

        $('#DamageDate').datetimepicker({
            onClose: function () {
                var DamageDate = $("#DamageDate").val();
                var url = "index.php?module=ticket&event=setDamageDate";
                if (gueltigesDatum(DamageDate)) {
                    bootbox.confirm(ts_changeDamageDate, function (result) {
                        if (result) {
                            $.ajax({
                                type: "POST",
                                url: url,
                                data: {tid: TicketID, save: 1, DamageDate: DamageDate}
                            }).done(function (msg) {
                                console.log(msg);
                                noty({
                                    text: msg,
                                    type: 'success',
                                    timeout: notifyTimeout
                                });

                            });
                        } else {
                            $('#DamageDate').val(TicketData['damagedate']);
                        }
                    })
                } else {
                    alert("Ungültiges Datumsformat");
                }

            },
            currentText: ts_Jetzt,
            closeText: ts_OK,
            language: ts_lang

        });

        if (bool_hasRight[6]) {
            $('#TicketDesireDate').datetimepicker({
                onClose: function (date) {
                    var TicketDesireDate = $("#TicketDesireDate").val();
                    var url = "index.php?module=ticket&event=setTicketDesireDateJSON";
                    if (gueltigesDatum(TicketDesireDate)) {

                        bootbox.confirm(ts_changeDesiredate, function (result) {
                            if (result) {
                                console.log(url);
                                $.ajax({
                                    type: "POST",
                                    url: url,
                                    data: {tid: TicketID, save: 1, TicketDesireDate: TicketDesireDate}
                                }).done(function (msg) {
                                    console.log(msg);

                                    if (1 != msg) {
                                        if (typeof msg === 'object' && msg.message) {
                                            noty({
                                                text: msg.message,
                                                type: 'success',
                                                timeout: notifyTimeout
                                            });
                                        } else {
                                            $("#TicketDesireDate").empty();
                                            $("#TicketDesireDate").addClass("textboxerror");
                                            $("#TicketDesireDate").before('<p style="color:red;">' + msg + '</p>');
                                        }
                                    } else {
                                        $("#TicketDesireDate").removeClass("textboxerror");
                                    }
                                });
                            } else {
                                $('#TicketDesireDate').val(TicketData['ticketdesiredate']);
                            }
                        })

                    } else {
                        $("#TicketDesireDate").addClass("textboxerror");
                        $("#TicketDesireDate").before('<p>Ungültiges Datumsformat</p>');
                    }

                },
                currentText: ts_Jetzt,
                closeText: ts_OK,
                timeText: ts_Zeit,
                hourText: ts_Stunde,
                language: 'en'

            });

            $('#TicketDesireDateDAS').datepicker({
                onClose: function (date) {
                    var TicketDesireDate = $("#TicketDesireDateDAS").val();
                    var url = "index.php?module=ticket&event=setTicketDesireDate";
                    if (gueltigesDatum(TicketDesireDate)) {
                        bootbox.confirm(ts_changeDesiredate, function (result) {
                            if (result) {
                                $.ajax({
                                    type: "POST",
                                    url: url,
                                    data: {tid: TicketID, save: 1, TicketDesireDate: TicketDesireDate}
                                }).done(function (msg) {
                                    console.log(msg);

                                    if (1 != msg) {
                                        if (typeof msg === 'object' && msg.message) {
                                            noty({
                                                text: msg.message,
                                                type: 'success',
                                                timeout: notifyTimeout
                                            });
                                        } else {
                                            $("#TicketDesireDateDAS").empty();
                                            $("#TicketDesireDateDAS").addClass("textboxerror");
                                            $("#TicketDesireDateDAS").before('<p style="color:red;">' + msg + '</p>');
                                        }
                                    } else {
                                        $("#TicketDesireDateDAS").removeClass("textboxerror");
                                    }
                                });
                            } else {
                                $('#TicketDesireDate').val(TicketData['ticketdesiredate']);
                            }
                        })
                    } else {
                        $("#TicketDesireDateDAS").addClass("textboxerror");
                        $("#TicketDesireDateDAS").before('<p>Ungültiges Datumsformat</p>');
                    }

                },
                currentText: ts_Jetzt,
                closeText: ts_OK,
                language: ts_lang

            });
        }

    });
}

var InitPicker = true;
var CurrentDayOfTheWeek;

$.datepicker.setDefaults($.datepicker.regional[ ts_lang ]);
//$.datetimepicker.setDefaults( $.datepicker.regional[ "en" ] );

$(document).ready(function () {
    SetCurrentDayOfTheWeek();
    if (bool_hasRight[12]) {
        $('#RemoveOnHoldDate').on("click", function () {
            RemoveOnHoldDate();
        });

        /**
         * Comment
         */
        function RemoveOnHoldDate() {
            $.ajax({
                type: "POST",
                url: "index.php?module=ticket&event=setOnHold",
                data: {tid: TicketID, save: 1, remove: 1, OnHoldDate: ''}
            }).done(function (msg) {
                if (1 != msg) {
                    $("#OnHoldDate").addClass("textboxerror");
                    $("#OnHoldDate").before('<p>' + msg + '</p>');
                } else {
                    reloadPage();
                }
            });
        }

        $('#OnHoldDate').datetimepicker({
            onClose: function (date) {
                var OnHoldDate = $("#OnHoldDate").val();
                var url = "index.php?module=ticket&event=setOnHold";
                if (jsonTicketData && jsonTicketData["updatedate"] != '') {
                    url += "&updatedate=" + jsonTicketData["updatedate"];
                }
                if ('' != OnHoldDate) {
                    if (gueltigesDatum(OnHoldDate)) {

                        bootbox.confirm(ts_changeOnhold, function (result) {
                            if (result) {
                                $.ajax({
                                    type: "POST",
                                    url: url,
                                    data: {tid: TicketID, save: 1, OnHoldDate: OnHoldDate}
                                }).done(function (msg) {
                                    if (1 != msg) {
                                        $("#OnHoldDateForm").addClass("has-error");
                                        $("#OnHoldDate").before('<p class="error">' + msg + '</p>');
                                    } else {
                                        reloadPage();
                                    }
                                });
                            } else {
                                $('#OnHoldDate').val('');
                            }
                        })

                    } else {
                        $("#OnHoldDateForm").addClass("has-error");
                        $("#OnHoldDate").before('<p class="error">Ungültiges Datumsformat</p>');
                    }
                }
                InitPicker = true;
            },
            currentText: ts_Jetzt,
            closeText: ts_OK,
            timeText: ts_Zeit,
            hourText: ts_Stunde,
            regional: 'en',
            hour: SetCurrentHours(),
            minute: SetCurrentMinutes(),
            onSelect: function (datetext) {
                GetDefaultOnHoldValue(datetext);
            }
        });
    }

    function SetCurrentDayOfTheWeek() {
        var CurrentDate = new Date();
        CurrentDayOfTheWeek = CurrentDate.getDay();
    }

    function SetCurrentHours() {
        var CurrentDate = new Date();
        return CurrentDate.getHours() + 1;
    }

    function SetCurrentMinutes() {
        var CurrentDate = new Date();
        return CurrentDate.getMinutes();
    }

    function GetDefaultOnHoldValue(datetext) {
        var date = $('#OnHoldDate').datepicker('getDate');
        var DayOfTheWeek = date.getDay();

        if (CurrentDayOfTheWeek != DayOfTheWeek) {
            InitPicker = true;
            CurrentDayOfTheWeek = DayOfTheWeek;
        }

        if (InitPicker) {
            $.get('index.php?module=ticket&event=GetDefaultOnHoldDate&weekday=' + DayOfTheWeek, function (result) {
                var Date = datetext.substring(0, 11) + result;
                $('#OnHoldDate').datetimepicker('setDate', Date);
                InitPicker = false;
            });
        }
    }

    if (bool_hasRight[221]) {
        $("#ArchivButton, #smallArchivButton").on("click", function () {
            $.ajax({
                type: "POST",
                url: "index.php?module=ticketlist&event=archivTicket",
                data: {ticketid: TicketID}
            }).done(function (result) {

                if (1 == result) {
                    if ($('#ArchivButton').text() == '... dearchivieren') {
                        $('#ArchivButton, #smallArchivButton').text('... archivieren');
                        $("#TicketArchivedMessage").html('');
                    } else {
                        $('#ArchivButton, #smallArchivButton').text('... dearchivieren');
                        $("#TicketArchivedMessage").html(ts_Archiviert);
                    }
                }
            });
        });
    }






    //Ausgehnde Links in neuen Tab:
    $('#TicketHistoryTable > tbody a[href^="http://"]').attr('target', '_blank');
    $(function () {
        $("#LongDescr").sceditor({
            format: "bbcode",
            style: "includes/js/sceditor-2.1.2/minified/jquery.sceditor.default.min.css",
            toolbar: '',
            emoticonsEnabled: false,
            charset: 'ISO-8859-1',
            readOnly: true,
            width: '100%',
            height: '600px',
            resizeEnabled: false,
            locale: ts_lang
        });
    });

    $(".toggleNotification").on("click", function () {
        var Button = $(this);
        var TicketID = Button.data("ticketid");
        var ConnectedTicketID = Button.data("connectedticketid");
        var sentMailtoConnectedTicketID = Button.data("sentmailtoconnectedticketid");

        $.post("index.php?module=ticket&event=toggleSendMail", {ticketid: TicketID, connectedticketid: ConnectedTicketID, sentmailtoconnectedticketid: sentMailtoConnectedTicketID}, function (result) {
            if (result == 1) {
                Button.removeClass('button-green').addClass('button-red').val("Nicht Benachrichtigen");
            } else {
                Button.removeClass('button-red').addClass('button-green').val("Benachrichtigen");
            }

        });
    });



    $("#MajorIncident").on("change", function (e) {
        var isMajorIncident = $('#MajorIncident').is(':checked');
        if (isMajorIncident) {
            conf_string = ts_switchToMajorIncident;
        } else {
            conf_string = ts_switchFromMajorIncident;
        }

        bootbox.confirm(conf_string, function (result) {
            if (result) {
                $.getJSON('index.php?module=ticket&event=toggleMajorIncident', {
                    format: "json",
                    ticketid: TicketID,
                    isMajorIncident: isMajorIncident ? 1 : 0
                }).done(function (data) {
                    if (data.error) {
                        noty({
                            text: ts_MajorIncidentError,
                            //layout: 'top',
                            //theme: 'defaultTheme', // or 'relax'
                            //closeWith: ['click', 'hover'],
                            type: 'error',
                            timeout: notifyTimeout
                        });
                    } else {
                        if (isMajorIncident) {
                            $("#isMajorIncidentImage").attr("src", 'images/isproblem.gif');
                            $("#isProblem").prop('readonly', true).attr('disabled', true);
                            ;
                        } else {
                            $("#isMajorIncidentImage").attr("src", 'images/isincident.gif');
                            $("#isProblem").prop('readonly', false).attr('disabled', false);
                            ;
                        }

                        if (data.hasOwnProperty('groupids')) {
                            var groupidArray = [];
                            $.each(data.groupids, function (i, groupid) {
                                groupidArray.push(groupid);
                            });
                            $('#GroupSelect').val(groupidArray);
                            $('#GroupSelect').trigger('change');
                            showSupporter("#GroupSelect");
                        }
                        if (data.hasOwnProperty('message')) {
                            noty({
                                text: data.message,
                                //layout: 'top',
                                //theme: 'defaultTheme', // or 'relax'
                                //closeWith: ['click', 'hover'],
                                type: 'success',
                                timeout: notifyTimeout
                            });
                        }
                    }
                });
            } else {
                $("#MajorIncident").prop('checked', !isMajorIncident);
            }
        });
    });

    //Quelle: https://vitalets.github.io/x-editable/docs.html
    $.fn.editable.defaults.mode = 'inline';
    $("#ticketdescr").editable();




    $("#contact").select2({theme: 'bootstrap-5',
        language: ts_lang,
        ajax: {
            url: "index.php?module=contact&event=getJsonContacts",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page,
                    cid: $("#contact_id").val(),
                    slaid: ticketSLAid
                };
            },
            processResults: function (data) {
                return {
                    results: data.items
                };
            }
        },
        escapeMarkup: function (markup) {
            return markup;
        }, // let our custom formatter work
//  minimumInputLength: 1,
//  templateResult: formatService // omitted for brevity, see the source of this page
        //templateSelection: formatServiceSelection // omitted for brevity, see the source of this page
    }).on("select2:select", function (e) {
        var data = e.params.data;
//    console.log(data);
        $('#ContactData').hide();

        if (data && data.id != $("#contact_id").val()) {

            bootbox.confirm(ts_ChangeContact, function (result) {
                if (result) {
                    $('#ContactData').empty();
                    $.post("index.php?module=contact&event=editTicketContact&oldcid=" + $("#contact_id").val() + "&tid=" + TicketID + "&newcid=" + data.id + "&save=1&confirmOnHold=hold").done(function (json) {
                        noty({
                            text: json.message,
                            //layout: 'top',
                            //theme: 'defaultTheme', // or 'relax'
                            //closeWith: ['click', 'hover'],
                            type: json.error ? 'error' : 'success',
                            timeout: notifyTimeout
                        });
                    });
                    $.get('index.php?module=ticket&event=getMandantIDByContact&cid=' + data.id, function (mid) {
                        $("#MandantenID").val(mid);
                        url = "index.php?module=ticket&event=changeMandant&tid=" + TicketID + "&MandantenID=" + mid;
                        $.get(url, function (json) {
                            if (json.error) {

//                                noty({
//                                    text: json.ResponseMsg,
//                                    type: 'error',
//                                    timeout: notifyTimeout
//                                });

                            } else {
                                noty({
                                    text: json.ResponseMsg,
                                    type: 'success',
                                    timeout: notifyTimeout
                                });
                            }

                        })
                    });
                    $("#contact_id").val(data.id);
                    $('#ShowIframeContact').attr('src', $('#ShowIframeContact').attr('src'));
                    //document.getElementById('IframeContact').src = 'index.php';
                    //Wenn Kontakt gewechselt wird, die neuen Daten merken:

                    if (data.company && '' !== data.company) {
                        $("#ContactCompany").html("Firma: " + data.company).show();
                        //$("#ContactCompanyDiv").css( "display", "inline");
                    } else {
                        $("#ContactCompany").hide();
                    }
                    if (data.phone && '' !== data.phone) {
                        $("#ContactPhone").html("Telefon: " + data.phone).show();
                        //$("#ContactPhoneDiv").css( "display", "inline");
                    } else {
                        $("#ContactPhone").hide();
                    }
                    if ((data.company && '' !== data.company) || (data.phone && '' !== data.phone)) {
                        $("#ContactAddData").show();
                    } else {
                        $("#ContactAddData").hide();
                    }
                    //loadLocationStructure();
                } else {
                    $("#contact").val($("#contact_id").val()).trigger('change');
                    $('#ContactData').show();
                }

            });
        }
    });

    $("#TicketRefId").select2({theme: 'bootstrap-5',
        theme: "bootstrap",
        language: ts_lang,
        minimumInputLength: 1,
        ajax: {
            url: "index.php?module=ticket&event=autocompleteRefTicketsJson2&td",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page,
                    TicketID: TicketID
                };
            },
            processResults: function (data) {
                //console.log(data);
                return {
                    results: data.results
                };
            }
        }
    }).on("select2:select", function (e) {
        var data = e.params.data;
        if (data && data.id != 0) {

            bootbox.confirm(ts_ChangeMasterticket, function (result) {
                if (result) {/*Wenn True*/
                    var url = "index.php?module=ticketlist&event=RefTickets&tid=" + TicketID + "&TRefID=" + data.id + "&save=1";
                    $.post(url).done(function (json) {
                        noty({
                            text: "Masterticket <strong>" + data.text + "</strong> zugewiesen",
                            //layout: 'top',
                            //theme: 'defaultTheme', // or 'relax'
                            //closeWith: ['click', 'hover'],
                            type: 'success',
                            timeout: notifyTimeout
                        });
                        //console.log( $("#TicketRefId").val());
                        $("#MasterSelect").hide();
                        $("#URLHide").attr("href", "index.php?module=ticket&event=show&id=" + $("#TicketRefId").val());
                        $("#MasterticketHide").html(data.text);
                        $("#MasterShown").show();
                    });
                } else {
                    $("#TicketRefId").val('').trigger('change');
                }
            })
        }
    });

    $("#StoryRefId").select2({theme: 'bootstrap-5',
        theme: "bootstrap",
        language: ts_lang,
        minimumInputLength: 1,
        ajax: {
            url: "index.php?module=ticket&event=autocompleteStoryTicketsJson2&td",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data) {
                //console.log(data);
                return {
                    results: data.results
                };
            }
        }
    }).on("select2:select", function (e) {
        var data = e.params.data;
        if (data && data.id != 0) {

            bootbox.confirm(ts_ChangeStory, function (result) {


                if (result) {
                    var url = "index.php?module=ticket&event=SetStory&TicketID=" + TicketID + "&TicketStoryID=" + data.id + "";
                    $.post(url).done(function () {
                        noty({
                            text: "Story zugewiesen",
                            //layout: 'top',
                            //theme: 'defaultTheme', // or 'relax'
                            //closeWith: ['click', 'hover'],
                            type: 'success',
                            timeout: notifyTimeout
                        });
                        //console.log( $("#TicketRefId").val());
                        $("#StorySelect").hide();
                        $("#StoryURLHide").attr("href", "index.php?module=ticket&event=show&id=" + data.id);
                        $("#StoryHide").html(data.text);
                        $("#StoryShown").show();
                    });
                } else {

                }
            })
        }
    });

    $("#SelectDeviceID").select2({theme: 'bootstrap-5',
        language: ts_lang,
        minimumInputLength: 3,
        ajax: {
            url: "index.php?module=ticket&event=getDeviceJSON&tid=" + TicketID,
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data) {
                //console.log(data);
                return {
                    results: data.results
                };
            }
        }
    }).on("select2:select", function (e) {
        var data = e.params.data;
        if (data && data.id != 0) {

            var url = "index.php?module=ticket&event=changeDeviceTicketSennebogen&tid=" + TicketID + "&div=" + data.id;
            $.post(url).done(function (json) {
                var jdata = JSON.parse(json);
                if (jdata.error) {
                    noty({
                        text: jdata.messages[0],
                        type: 'error',
                        timeout: notifyTimeout
                    });

                } else {
                    noty({
                        text: jdata.messages[0],    
                        type: 'success',
                        timeout: notifyTimeout
                    });
                    if (data.id > 0) {
                        console.log("Data");
                        $.get('index.php?module=ticket&event=getGroupOfDevice&id='+data.id, function(group){
                                                            console.log("GroupID is: "+group);
                                                            if(group !== ""){
                                                            $("#GroupSelect").val(group).trigger('change');
                                                        }
                                                        });
                        $("#DeviceDetailsSennebogen").html('<iframe id="DetailIframe" src="index.php?module=device&event=assetInfo&assetlist=1&id=' + data.id + '" frameBorder="0" style="width: 100%; height: 500px;"></iframe>');
                        $.get('index.php?module=ticket&event=showDeviceNameSennebogen&id=' + TicketID, function (deviceName) {
                            if (deviceName !== "") {
                                $("#DeviceNameSpan").html(deviceName);
                            }
                        });

                        //Ggf. Gruppe des Geräts zufügen
                        $.post("index.php?module=assets&event=jsonGetGroups", {devid: data.id}).done(function (data) {
                            $.each(data, function (index, value) {
                                if (value.groupid > 0) {
                                    //$('#group_id').val(value.groupid).trigger('change');
                                    if ($('#group_id').length && $('#group_id').is(":visible")) {
                                        //TicketNew
                                        ConcatedValues = ($("#group_id").val() && $("#group_id").val().length) ? $("#group_id").val().concat(value.groupid) : value.groupid;
                                        $("#group_id").val(ConcatedValues).trigger("change");
                                    }
                                    if ($('#GroupSelect').length && $('#GroupSelect').is(":visible")) {
                                        //TicketDetails:
                                        ConcatedValues = ($("#GroupSelect").select2("val") && $("#GroupSelect").select2("val").lenght) ? $("#GroupSelect").select2("val").concat(value.groupid) : value.groupid;
                                        $("#GroupSelect").val(ConcatedValues).trigger("change");
                                    }
                                    //                ConcatedValues = $("#group_id").val().lenght ? $("#group_id").val().concat(value.groupid) : value.groupid;
                                    //                $("#group_id").val(ConcatedValues).trigger("change");

                                    noty({
                                        text: value.AddedText,
                                        type: 'success',
                                        timeout: notifyTimeout
                                    });
                                }
                                ;
                            });
                            if (typeof saveGroupSupportersAfterDeviceUpdate === 'function') {
                                saveGroupSupportersAfterDeviceUpdate();
                            }

                        });
                        if (typeof refreshClassificationSelection === 'function') {
                            refreshClassificationSelection();
                        }

                        if (typeof ChangeServiceScheckVisibility === 'function') {
                            ChangeServiceScheckVisibility();
                        }

                        if (typeof loadDeviceTicketPanel === 'function') {
                            loadDeviceTicketPanel();
                        }
                        if (typeof ChangeServiceScheckVisibility === 'function') {
                            ChangeServiceScheckVisibility();
                        }
                    }
                }
            });
        }
    });



    $("#ConnectionTicketID").select2({theme: 'bootstrap-5',
        theme: "bootstrap",
        language: ts_lang,
        minimumInputLength: 1,
        ajax: {
            url: "index.php?module=ticket&event=autocompleteRefTicketsJson2&td",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page,
                    TicketID: tid
                };
            },
            processResults: function (data) {
                //console.log(data);
                return {
                    results: data.results
                };
            }
        }
    }).on("select2:select", function (e) {
        var data = e.params.data;
        if (data && data.id != 0) {
            if ($("input[name=OnHoldFlag]:checked").val() == "1") {
                var url = "index.php?module=ticketlist&event=connectTicket&save=1&ConnTicketID=" + tid + "&ConnectionTicketID=" + $("#ConnectionTicketID").val() + "&OnHoldFlag=" + $("input[name=OnHoldFlag]:checked").val();
                $.post(url).done(function (json) {
                    //console.log(json);
                    noty({
                        text: "Ticket mit Ticket #" + $("#ConnectionTicketID").val() + " mit Zur&uuml;ckstellung verkn&uuml;pften",
                        //layout: 'top',
                        //theme: 'defaultTheme', // or 'relax'
                        //closeWith: ['click', 'hover'],
                        type: 'success',
                        timeout: notifyTimeout
                    });
                });
            } else {
                var url = "index.php?module=ticketlist&event=connectTicket&save=1&ConnTicketID=" + tid + "&ConnectionTicketID=" + $("#ConnectionTicketID").val() + "&OnHoldFlag=" + $("input[name=OnHoldFlag]:checked").val();
                $.post(url).done(function (json) {
                    //console.log(json);
                    noty({
                        text: "Ticket mit Ticket #" + $("#ConnectionTicketID").val() + " ohne Zur&uuml;ckstellung verkn&uuml;pften",
                        //layout: 'top',
                        //theme: 'defaultTheme', // or 'relax'
                        //closeWith: ['click', 'hover'],
                        type: 'success',
                        timeout: notifyTimeout
                    });
                });


            }
        }
    });

    $("#StoryTicketID").select2({theme: 'bootstrap-5',
        theme: "bootstrap",
        language: ts_lang,
        minimumInputLength: 1,
        ajax: {
            url: "index.php?module=ticket&event=autocompleteStoryJson2&td",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data) {
                //console.log(data);
                return {
                    results: data.results
                };
            }
        }
    }).on("select2:select", function (e) {
        var data = e.params.data;
        if (data && data.id !== 0) {
            console.log(TicketID);
            console.log(data.id);
            var url = "index.php?module=ticket&event=SetStory&TicketStoryID=" + TicketID + "&TicketID=" + data.id;
            $.post(url).done(function (json) {
                //console.log(json);
                noty({
                    text: "Ticket #" + data.id + " ist dem Story zugewiesen",
                    //layout: 'top',
                    //theme: 'defaultTheme', // or 'relax'
                    //closeWith: ['click', 'hover'],
                    type: 'success',
                    timeout: notifyTimeout
                });
            });

        }
    });


    /* Masterticketzuweisung*/






    $(".collapse").filter(function (ix, el) {
        // return only the ones with min-height
        return $(el).css("min-height");
    }).each(function (ix, el) {

        var $el = $(el)
                // remember the original min-height
                , minHeight = $el.css("min-height");

        $el.on("hidden.bs.collapse", function () {

            $el.removeClass("collapse")
                    .css({
                        "overflow": "hidden"
                        , "height": minHeight
                    })
        });

        // collapse element on load if it has the class .collapsed
        if ($el.hasClass("collapsed"))
            $el.collapse();
    });


    /*Mandanten wechseln */
    $("#MandantenID").on('change', function () {
        url = "index.php?module=ticket&event=changeMandant&tid=" + TicketID + "&MandantenID=" + $("#MandantenID").val();
        $.get(url, function (json) {
            if (json.error) {

                noty({
                    text: json.ResponseMsg,
                    //layout: 'top',
                    //theme: 'defaultTheme', // or 'relax'
                    //closeWith: ['click', 'hover'],
                    type: 'error',
                    timeout: notifyTimeout
                });

            } else {
                noty({
                    text: json.ResponseMsg,
                    //layout: 'top',
                    //theme: 'defaultTheme', // or 'relax'
                    //closeWith: ['click', 'hover'],
                    type: 'success',
                    timeout: notifyTimeout
                });
            }

        })
    });

});

$(function () {
    $('[data-toggle="tooltip"]').tooltip()
})

function ReturnFalse() {
    return false;
}


function format(item) {
    return item.name;
}
;

if (TicketData['ticketreferenzid'] < 1
        && TicketData['ticketstatusid'] != 3
        && TicketData['ticketstatusid'] != 7
        && bool_hasRight[216]
        && (TicketData['ticketstatusid'] != 9 || bool_hasRight[112])) {

    function nqi_searchSupporter(task, text_name, id_name)
    {
    }
}

function emptyCat2() {
    $("#CategoryID2").val(0);
    $("#CategoryDescr2").val('');
    if ($("#CategoryDescr1").val() == '') {
        $("#CategoryID1").val(0);
    }
    if ($("#CategoryID1").val() == 0) {
        $("#CategoryDescr1").val('');
    }
}


function ShowHide(id) {
    obj = document.getElementsByTagName("div");
    if (obj[id].style.display == 'none') {
        obj[id].style.display = 'block';
        obj[id + '_header'].style.background = '#F2F2F2 url(images/ecke_rechtsunten.png) no-repeat top left';
    } else {
        obj[id].style.display = 'none';
        obj[id + '_header'].style.background = '#F2F2F2 url(images/ecke_rechts.png) no-repeat top left';
    }
}



var CatFormArray = new Array();

if (CategoryFormData['formularid1'] > 0) {
    CatFormArray.push(1);
}
if (CategoryFormData['formularid2'] > 0) {
    CatFormArray.push(2);
}
if (CategoryFormData['formularidtt'] > 0) {
    CatFormArray.push(3);
}
var zaehler = CatFormArray.length;
/*
 function sendNext() {
 if (zaehler >= 0) {
 zaehler--;
 if (zaehler > 0) {
 getFormValues(parent.categoryform2.document.hm);
 } else {
 if (zaehler == 0) {
 ValidateForm(0);
 zaehler = CatFormArray.length;
 }
 }
 return true;
 } else {
 exit;
 }
 }
 
 var xmlHttp = false;
 if (typeof XMLHttpRequest != 'undefined')
 {
 xmlHttp = new XMLHttpRequest();
 }
 if (!xmlHttp)
 {
 try
 {
 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e)
 {
 try
 {
 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 } catch (e)
 {
 xmlHttp = null;
 }
 }
 }
 
 function saveData(str) {
 xmlHttp.open('POST', 'index.php?module=formwizard&event=viewFormular&ajax=true', true);
 xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlHttp.onreadystatechange = messageresponse;
 xmlHttp.send(str);
 }
 
 function messageresponse()
 {
 if (xmlHttp.readyState == 4) {
 if (xmlHttp.status == 200) {
 sendNext();
 }
 }
 }
 
 
 function getFormValues(fobj)
 {
 if (!fobj) {
 return 0;
 }
 var str = "";
 var valueArr = null;
 var val = "";
 var cmd = "";
 for (var i = 0; i < fobj.elements.length; i++)
 {
 switch (fobj.elements[i].type)
 {
 case "text":
 case "textarea":
 case "hidden":
 str += fobj.elements[i].name +
 "=" + escape(fobj.elements[i].value) + "&";
 break;
 
 case "select-one":
 if (fobj.elements[i].selectedIndex >= 0) {
 str += fobj.elements[i].name +
 "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
 }
 break;
 
 case "checkbox":
 case "radio":
 if (fobj.elements[i].checked == true) {
 str += fobj.elements[i].name +
 "=" + escape(fobj.elements[i].value) + "&";
 }
 break;
 }
 }
 str = str.substr(0, (str.length - 1));
 //alert(str);
 saveData(str);
 //return str;
 }
 */

if (bool_AVAGPrioToAccept) {

    function togglePrioAccepted(el) {
        var accepted = el.checked;
        var check = false;

        if (accepted) {
            bootbox.confirm(ts_PrioBestaetigen, function (result) {
                if (result) {
                    var val = (accepted) ? 1 : 0;
                    url = "index.php?module=ticket&event=prioaccepted&tid=" + TicketID + "&value=" + val;
                    makeHttpRequest(url, "updatePrioAccepted", false);
                } else {
                    el.checked = !accepted;
                }
            })
        } else {
            var val = (accepted) ? 1 : 0;
            url = "index.php?module=ticket&event=prioaccepted&tid=" + TicketID + "&value=" + val;
            makeHttpRequest(url, "updatePrioAccepted", false);
        }
    }

    function updatePrioAccepted(xmldoc) {
    }
}

function checkForm_Close(close, bconfirm) {



    if (CategoryFormData['formularid1'] > 0 && (CategoryFormData['required1'] == 1 || CategoryFormData['required1'] == 3)) {
        var formcheck1 = validateForm('GeneratetForm' + CategoryFormData['formularid1']);
    } else {
        var formcheck1 = true;
    }

    if (CategoryFormData['formularid2'] > 0 && (CategoryFormData['required2'] == 1 || CategoryFormData['required2'] == 3)) {
        var formcheck2 = validateForm('GeneratetForm' + CategoryFormData['formularid2']);
    } else {
        var formcheck2 = true;
    }


    if (CategoryFormData['formularidtt'] > 0 && (CategoryFormData['requiredtt'] == 1 || CategoryFormData['requiredtt'] == 3)) {
        var formchecktt = validateForm('GeneratetForm' + CategoryFormData['formularidtt']);
    } else {
        var formchecktt = true;
    }
    if (formcheck1 && formcheck2 && formchecktt && checkUserDefFields()) {
        /*
         if (CategoryFormData['formularid1'] > 0) {
         getFormValues(parent.categoryform1.document.hm);
         } else {
         if (CategoryFormData['formularid2'] > 0) {
         getFormValues(parent.categoryform2.document.hm);
         }
         }
         if (CategoryFormData['formularidtt'] > 0) {
         getFormValues(parent.categoryformtt.document.hm);
         }
         */

        if (NoFutureEvent()) {
            if (bconfirm) {
                if (close == "TicketClose") {
                    check_string = ts_realyCloseTicket;
                } else {
                    check_string = ts_realySetDone;
                }

                bootbox.confirm(check_string, function (result) {
                    if (result) {
                        if (close == "TicketClose") {
                            $('#TicketDone').val(0);
                            $('#TicketClose').val(1);
                            $('#popup').val(1);
                        } else if (close == "TicketDone") {
                            $('#TicketClose').val(0);
                            $('#TicketDone').val(1);

                        }
                        $("#tab-details-form").submit();
                    } else {
                        /*false*/
                    }
                })

            } else {
                if (close == "TicketClose") {
                    $('#TicketDone').val(0);
                    $('#TicketClose').val(1);
                } else if (close == "TicketDone") {
                    $('#TicketClose').val(0);
                    $('#TicketDone').val(1);
                }
            }
        }

    } else {

        return false;
    }
    return true;
}

function checkForm_Close2(close, bconfirm) {

//console.log("CategoryFormData: " + CategoryFormData);
    if (close !== 'TicketStorno') {


        if (CategoryFormData['formularid1'] > 0 && (CategoryFormData['required1'] == 1 || CategoryFormData['required1'] == 3)) {
            var formcheck1 = validateForm('GeneratetForm' + CategoryFormData['formularid1']);
        } else {
            var formcheck1 = true;
        }

        if (CategoryFormData['formularid2'] > 0 && (CategoryFormData['required2'] == 1 || CategoryFormData['required2'] == 3)) {
            var formcheck2 = validateForm('GeneratetForm' + CategoryFormData['formularid2']);
        } else {
            var formcheck2 = true;
        }


        if (CategoryFormData['formularidtt'] > 0 && (CategoryFormData['requiredtt'] == 1 || CategoryFormData['requiredtt'] == 3)) {
            var formchecktt = validateForm('GeneratetForm' + CategoryFormData['formularidtt']);
        } else {
            var formchecktt = true;
        }
    }
    if (close == 'TicketStorno' || (formcheck1 && formcheck2 && formchecktt && checkUserDefFields())) {

        if (NoFutureEvent()) {
            if (bconfirm) {
                if (close == "TicketStorno") {
                    check_string = ts_realyCancelTicket;
                } else if (close == "TicketClose") {
                    check_string = ts_realyCloseTicket;
                } else {
                    check_string = ts_realySetDone;
                }

                bootbox.confirm(check_string, function (result) {
                    if (result) {
                        if (close == "TicketStorno") {
                            $('#TicketDone').val(0);
                            $('#TicketClose').val(4);
                            //$('#popup').val(0);
                        } else if (close == "TicketClose") {
                            $('#TicketDone').val(0);
                            $('#TicketClose').val(1);
                            //$('#popup').val(0);
                        } else if (close == "TicketDone") {
                            $('#TicketClose').val(0);
                            $('#TicketDone').val(1);

                        }
                        $("#tab-details-form").submit();
                    } else {
                        /*false*/
                    }
                })

            } else {
                if (close == "TicketStorno") {
                    $('#TicketDone').val(0);
                    $('#TicketClose').val(4);
                    //$('#popup').val(0);
                } else if (close == "TicketClose") {
                    $('#TicketDone').val(0);
                    $('#TicketClose').val(1);
                    $('#popup').val("1");
                } else if (close == "TicketDone") {
                    $('#TicketClose').val(0);
                    $('#TicketDone').val(1);
                }
            }
        }

    } else {

        return false;
    }
    return true;
}

function returnTrue() {
    return true;
}

function checkForm_Edit() {

    if (CategoryFormData['formularid1'] > 0 && (CategoryFormData['required1'] == 2 || CategoryFormData['required1'] == 3)) {

        var formcheck1 = validateForm('GeneratetForm' + CategoryFormData['formularid1']);
        //console.log("Prüfung " + 'GeneratetForm' + CategoryFormData['formularid1'] + " - liefert: " + formcheck1);
    } else {
        var formcheck1 = true;
    }

    if (CategoryFormData['formularid2'] > 0 && (CategoryFormData['required2'] == 2 || CategoryFormData['required2'] == 3)) {
        var formcheck2 = validateForm('GeneratetForm' + CategoryFormData['formularid2']);
//        console.log("Prüfung " + 'GeneratetForm' + CategoryFormData['formularid2'] + " - liefert: " + formcheck2);
    } else {
        var formcheck2 = true;
    }

    if (CategoryFormData['formularidtt'] > 0 && (CategoryFormData['requiredtt'] == 2 || CategoryFormData['requiredtt'] == 3)) {
        var formchecktt = validateForm('GeneratetForm' + CategoryFormData['formularidtt']);
    } else {
        var formchecktt = true;
    }

    if (formcheck1 && formcheck2 && formchecktt) {
        /*
         if (CategoryFormData['formularid1'] > 0) {
         parent.categoryform1.document.hm.submit();
         }
         if (CategoryFormData['formularid2'] > 0) {
         parent.categoryform2.document.hm.submit();
         }
         if (CategoryFormData['formularidtt'] > 0) {
         parent.categoryformtt.document.hm.submit();
         }
         */
        return true;
    } else {
        if (!formcheck1) {
//            showFrame('Detail', 'CategoryForms1');
        } else if (!formcheck2) {
//            showFrame('Detail', 'CategoryForms2');
        } else {
//            showFrame('Detail', 'CategoryFormsTT');
        }
        //console.log("Formularprüfung liefert false");
        return false;
    }
}

/*
 $("#NewTag").autocomplete(AvailableTagsJSArray, {
 width: 320,
 highlight: false,
 multiple: false,
 scroll: true,
 scrollHeight: 300,
 selectFirst: false,
 matchContains: true
 });
 */


/*** aus viewformular */

var fields = new Array();
var valid_form = true;
var forms = new Array();

function getForm(formid) {
    for (var i = 0; i < forms.length; i++) {
        if (forms[i].formid == formid) {
            return forms[i];
        }
    }
    return null;
}

function form(formid, field) {
    this.formid = formid;
    this.field = field;
}

function field(type, name, required, evaluate)
{
    this.obj = document.getElementById("field_" + name);
    this.err = document.getElementById("field_error_" + name);
    this.type = type
    this.name = name;
    this.required = (required == "Y") ? true : false;
    this.evaluate = evaluate;

    this.errormessage = "";
    this.errorcode = 0
    this.hasError = hasError;
}

function hasError()
{
    return (this.errorcode > 0) ? true : false;
}

function trim(str)
{
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

/*
 * Prüft das Formular aus dem forms-Array und liefert true, wenn alles Stimmt
 */
function validateForm(formid)
{
    console.log("T-newDetails-validateForm");
    console.log("Formular [" + formid + "] aufrufen ");
    error = false;
    if (getForm(formid) != null) {
        var form = getForm(formid);
        fields = form.field;
        //console.log("Formular [" + formid + "] geladen");
        for (i = 0; i < fields.length; i++) {
            var field = fields[i];
            var type = field.type;
            var value = (type != "radio" && type != "checkbox" && field.obj.value)
                    ? trim(field.obj.value) : "";

            fields[i].errorcode = 0;
            fields[i].errormessage = "";
            fields[i].err.style.display = "none";
            fields[i].err.innerHTML = " ";

            if (field.required && type != "select" && type != "radio" && type != "checkbox") {

                if (value.length == 0) {
                    fields[i].errorcode = 404;
                    fields[i].errormessage = "field empty";
                    error = true;
                }
            } else if (field.required && (type == "radio" || type == "checkbox")) {

                var elements = (type == "checkbox")
                        ? document.getElementsByName(field.name + "[]")
                        : document.getElementsByName(field.name);

                var checked = false;

                for (j = 0; j < elements.length; j++) {
                    if (elements[j].checked)
                        checked = true;
                }

                if (!checked) {
                    fields[i].errorcode = 101;
                    fields[i].errormessage = "nothing selected";
                    error = true;
                }

            } else if (field.required) {

                var tmp = fields[i].obj.options.selectedIndex;
                if (tmp < 0) {
                    fields[i].errorcode = 101;
                    fields[i].errormessage = "nothing selected";
                    error = true;
                }
            }

            if (!fields[i].hasError() && value.length != "") {

                if (type == "integer" && !valid_int(value)) {
                    fields[i].errorcode = 201;
                    fields[i].errormessage = "invalid number";
                    error = true;
                }

                if (type == "date" && !valid_date(value)) {
                    fields[i].errorcode = 301;
                    fields[i].errormessage = "invalid date";
                    error = true;
                }

                if (type == "datetime" && !valid_datetime(value)) {
                    fields[i].errorcode = 302;
                    fields[i].errormessage = "invalid datetime";
                    error = true;
                }

                if (type == "text") {

                    switch (field.evaluate) {

                        case "dmY":
                            if (!valid_date(value)) {
                                fields[i].errorcode = 301;
                                fields[i].errormessage = "invalid date";
                                error = true;
                            }
                            break;

                        case "hm":
                            if (!valid_time(value)) {
                                fields[i].errorcode = 303;
                                fields[i].errormessage = "invalid time";
                                error = true;
                            }
                            break;

                        case "dmYhm":
                            if (!valid_datetime(value)) {
                                fields[i].errorcode = 302;
                                fields[i].errormessage = "invalid datetime";
                                error = true;
                            }
                            break;

                        case "Y":
                            if (!valid_year(value)) {
                                fields[i].errorcode = 304;
                                fields[i].errormessage = "invalid year";
                                error = true;
                            }
                            break;

                        case "int":
                            if (!valid_int(value)) {
                                fields[i].errorcode = 201;
                                fields[i].errormessage = "invalid integer";
                                error = true;
                            }
                            break;

                        case "float":
                            if (!valid_float(value)) {
                                fields[i].errorcode = 202;
                                fields[i].errormessage = "invalid float";
                                error = true;
                            }
                            break;

                        case "alpha":
                            if (!valid_alphanumeric(value)) {
                                fields[i].errorcode = 405;
                                fields[i].errormessage = "not alphanumeric";
                                error = true;
                            }
                            break;

                        case "upper":
                            if (!valid_upper(value)) {
                                fields[i].errorcode = 406;
                                fields[i].errormessage = "not uppercase";
                                error = true;
                            }
                            break;

                        case "lower":
                            if (!valid_lower(value)) {
                                fields[i].errorcode = 407;
                                fields[i].errormessage = "not lowercase";
                                error = true;
                            }
                            break;

                        case "url":
                            if (!valid_url(value)) {
                                fields[i].errorcode = 408;
                                fields[i].errormessage = "invalid url";
                                error = true;
                            }
                            break;

                        case "mail":
                            if (!valid_mail(value)) {
                                fields[i].errorcode = 409;
                                fields[i].errormessage = "invalid mail";
                                error = true;
                            }
                            break;

                        default:
                            break;
                    }
                }
            }
            if (fields[i].hasError()) {
                fields[i].err.innerHTML = ErrorMessages[fields[i].errorcode];
                fields[i].err.style.display = "block";
                $(fields[i].obj).css({'background-color': "pink"});
                $("#" + formid).closest(".panel-collapse").collapse("show");
                $('html,body').animate({scrollTop: $("#" + formid).offset().top}, 'fast');
//console.log("Fehler in " + formid);
            } else {
                $(fields[i].obj).css({'background-color': "white"});
            }

        }

        if (!error) {
            //console.log("Formular [" + formid + "] speichern...");
            $('#' + formid).submit();

            /*
             noty({
             text: "Formular wurde gespeichert",
             type: 'success',
             timeout: notifyTimeout
             });
             */
        }
        //console.log("Formular [" + formid + "]  return: " + !error ? 'true' : 'false');
        return !error;
    } else {
        //console.log("Formular [" + formid + "] konnte nicht geladen werden");
    }

    return false;
}

$(document).on('click', "#FormSaveButton", function (e) {
    var check = validateForm($(this).attr("data-formid"));
    /*
     if (check){
     console.log("Senden #GeneratetForm[% $fid %] ..." + $(this).attr("data-formid") );
     $('#' + $(this).attr("data-formid")).submit();
     
     e.preventDefault();
     return true;
     } else {
     console.log("formValidierung liefert false für Formular " + $(this).attr("data-formid"));
     }
     */

})

function valid_datetime(Datum)
{
    if (Datum.length == 16 && Datum.substring(10, 11) == " ") {

        var Zeit = Datum.substring(11, 16);
        var Datum = Datum.substring(0, 10);

        return (valid_date(Datum) && valid_time(Zeit))
                ? true : false;
    }
    return false;
}

function valid_date(Datum)
{
    if (Datum.length == 10 && Datum.substring(2, 3) == "." &&
            Datum.substring(5, 6) == ".") {

        var Day = parseInt(Datum.substring(0, 2), 10);
        var Month = parseInt(Datum.substring(3, 5), 10);
        var Year = parseInt(Datum.substring(6, 10), 10);
        var myDate = new Date(Year, Month - 1, Day);
        var Day2 = myDate.getDate();
        var Year2 = myDate.getFullYear();
        var Month2 = myDate.getMonth() + 1;

        return (Day2 == Day && Month2 == Month && Year2 == Year)
                ? true : false;
    }
    return false;
}

function valid_time(Zeit)
{
    if (Zeit.length == 5 && Zeit.substring(2, 3) == ":") {

        var Hour = parseInt(Zeit.substring(0, 2), 10);
        var Minute = parseInt(Zeit.substring(3, 5), 10);

        return (!isNaN(Hour) && !isNaN(Minute) && Hour >= 0 && Hour < 24 &&
                Minute >= 0 && Minute < 60) ? true : false;
    }
    return false;
}

function valid_int(Nummer)
{
    var regex = /^[+-]{0,1}[0-9]+$/
    return (Nummer.match(regex)) ? true : false;
}

function valid_float(Nummer)
{
    var regex = /^[+-]{0,1}[0-9]+[,.]{0,1}[0-9]+$/;
    return (Nummer.match(regex)) ? true : false;
}

function valid_upper(Str)
{
    return (Str == Str.toUpperCase()) ? true : false;
}

function valid_lower(Str)
{
    return (Str == Str.toLowerCase()) ? true : false;
}

function valid_mail(Mail)
{
    var regex = /^((([a-z]|[A-Z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[A-Z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/
    return (regex.test(Mail)) ? true : false;
}

function valid_url(Url)
{
    var regex = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    return (regex.test(Url)) ? true : false;
}

function valid_alphanumeric(Alpha)
{
    var regex = /^[a-zA-Z0-9_-äöüÄÖÜß]*$/;
    return (Alpha.match(regex)) ? true : false;
}

function valid_year(Year)
{
    var regex = /^[0-9]{4}$/;
    return (Year.match(regex)) ? true : false;
}




/*
 * Zeigt das Ticket-Bearbeitungs-Formular @innereinem Modal an.
 * Das geht nur, wenn die Form-Wizard-Formulare stimmen
 */
$('.ls-modal').on('click', function (e) {
    e.preventDefault();
    if (checkForm_Edit()) {
        $('#TicketDetailModal').modal('show').find('.modal-body').html("loading...").load($(this).attr('href'));
    }
});

$('#TicketDetailModal').on('hidden.bs.modal', function (e) {
    $('#TicketDetailModal').find('.modal-body').html("loading...");
});



function saveGroupSupporters() {
    var GroupIDs = $("#GroupSelect").val();
    var SupporterIDs = $("#SupporterSelect").val();
    //console.log("saveGroupSupporters...");
    //console.log("GroupIDs: " +  JSON.stringify($("#GroupSelect").val()));
    //console.log("SupporterIDs: " +  JSON.stringify(SupporterIDs));
    $.getJSON("index.php?module=ticket&event=changeGroupSupporter&save=1&json=1", {tid: TicketID, GroupIDs: GroupIDs, SupporterIDs: SupporterIDs}, function (json) {
        if (json != '') {
            console.log(json);
        } else {

        }
    });
}

function saveGroupSupportersAfterDeviceUpdate() {
    var GroupIDs = $("#GroupSelect").val();
    var SupporterIDs = $("#SupporterSelect").val();
    $.getJSON("index.php?module=ticket&event=changeGroupSupporter&save=1&json=1&forceGroup=1", {tid: TicketID, GroupIDs: GroupIDs, SupporterIDs: SupporterIDs}, function (json) {
        if (json != '') {
            console.log(json);
        } else {

        }
    });
}


function showSupporter(el) {
    console.log("Load Supporter");
    var GroupIDs = $(el).val();
    makeHttpRequest("index.php?module=user&event=AJAXSupporterList&gid=" + GroupIDs, "buildSupporterList", true);
}



function buildSupporterList(xmldoc) {
    var el = document.getElementById("SupporterSelect");
    if (el) {
        //var UserID = el.options[el.options.selectedIndex].value;
        var UserID = [];
        console.log("buildSupporterList");
        UserID = $('#SupporterSelect').val();
        el.length = 0;
        var users = xmldoc.getElementsByTagName("user");
        if (users.length > 0) {
            for (i = 0; i < users.length; i += 1) {
                //if (users[i].getAttribute('id') == UserID) {
                if (UserID != null && UserID.indexOf(users[i].getAttribute('id')) >= 0) {
                    NewEntry = new Option(users[i].getAttribute('name'), users[i].getAttribute('id'), false, true);
                } else {
                    NewEntry = new Option(users[i].getAttribute('name'), users[i].getAttribute('id'), false, false);
                }
                NewEntry.setAttribute("avatar", users[i].getAttribute('avatar'));
                NewEntry.setAttribute("department", users[i].getAttribute('department'));
                NewEntry.setAttribute("crop", users[i].getAttribute('crop'));
                el.options[el.length] = NewEntry;
            }
        }
        $supporterSelect.trigger('change');
         $('.lazyImg').Lazy({
        // your configuration goes here
        scrollDirection: 'vertical',
        effect: 'fadeIn',
        visibleOnly: true,
        onError: function(element) {
            console.log('error loading ' + element.data('src'));
        }
        });
        $(".lazy-img-circular-group-medium").each(function () {
            $(this).addClass('img-circular-group-medium');
            $(this).removeClass('lazy-img-circular-group-medium');
            var id = $(this).attr('id');
            $(this).attr("id", id.replace('lazy-', ''));
        });

        $(".lazy-img-circular").each(function () {
            $(this).addClass('img-circular');
            var id = $(this).attr('id');
            $(this).attr("id", id.replace('lazy-', ''));
        });
    }
}


function informContact() {
    var ContactID = $('#contact_id').val();
    if (0 < TicketID) {
        bootbox.confirm(ts_ShouldInformContact, function (result) {
            if (result) {
                $('#contact').addClass('loading');
                $.ajax({
                    type: "POST",
                    url: "index.php?module=ticket&event=informcontact",
                    data: {ticketid: TicketID, contactid: ContactID}
                }).done(function (msg) {
                    if (1 == msg) {
                        $('#contact_msg').html('<span class="error">' + ts_InformedContact + '</span>');
                    } else {
                        $('#contact_msg').html('<span class="error">' + ts_CouldNotInformedContact + '</span>');
                    }
                    $('#contact').removeClass('loading');
                });
            }
        })
    }
}

function takeover() {
    if (0 < TicketID) {

        bootbox.confirm(ts_UserAsSupporter, function (result) {
            if (result) {
                $('#user_descr').addClass('loading');
                $.ajax({
                    type: "POST",
                    url: "index.php?module=ticket&event=TicketTakeOver",
                    data: {ticketid: TicketID}
                }).done(function (msg) {
                    if (0 == msg) {
                        $('#supporter_msg').html(ts_TicketCouldNotTakenOver);
                    } else {
                        var result = $.parseJSON(msg);
                        $('#user_id').val(result.SupporterID);
                        $('#user_descr').val(result.SupporterName);
                        $('#group_id').val(result.GroupID);
                        $('#group_descr').val(result.GroupName);

//Select2:
//Gruppen:
                        if (result.emptyGroups) {
                            $("#GroupSelect").val('').trigger("change");
                            //showSupporter("#GroupSelect");
                        }
                        if (result.hasOwnProperty('supporterids')) {
                            var supporterids = [];
                            $.each(result.supporterids, function (i, supporterid) {
                                supporterids.push(supporterid);
                            });
                            // console.log("takeover - supporterids : " + supporterids);
                            //Warten, bis SelectBox gefüllt ist, dann Supporter wählen:
                            setTimeout(function () {
                                $('#SupporterSelect').val(supporterids).trigger("change");
                            }, 500);
                        }
                        var Nachricht = ts_TicketTakenOver;

                        $('#supporter_msg').html('<span class="error">' + Nachricht + '</span>');
                        $('#TicketTakeOverIcon').hide();
                        $('#user_descr').removeClass('loading');
                    }
                });
            }
        })
    }
}

function loadDeviceTicketPanel() {
    $('#DeviceTicketPanel').load('index.php?module=ticket&event=loadDeviceTicketPanel&id=' + TicketID);
}

function ToggleBasket() {
    alert("Die Funktion Merkliste wird in kommenden Versionen entfernt.");
    /*
    $.ajax({
        type: "POST",
        url: "index.php?module=ticket&event=toggleTicketBasket",
        data: { tid: TicketID }
    }).done(function (msg) {
        if ($("#ButtonTicketBasket").hasClass("button-green")) {
            $("#ButtonTicketBasket").removeClass("button-green").addClass("button-red").val("Merkliste -");
        } else {
            $("#ButtonTicketBasket").removeClass("button-red").addClass("button-green").val("Merkliste +");
        }
        location.reload();
        
    });
    */
}
