var DevicePagePos = 0;
var DeviceStructureID = 0;
var DeviceSelected = 0;
var DeviceTicketID = 0;
var DeviceStatusID = 0;
var DevicePopUP = false;
var DeviceSessionID = false;
var DeviceContactID = 0;
var DeviceRemovePossible = true;
function getDeviceStructure() {
    $("#DeviceStructureResult").fancytree({
        source: {
            url: "index.php?module=structure&event=JSONStructureTree&id=0&dev=1"
        },
        checkbox: false,
        autoActivate: true, // Automatically activate a node when it is focused (using keys).
        selectMode: 1, // 1:single, 2:multi, 3:multi-hier
        activeVisible: true,
        activate: function (event, data) {
            // A node was activated: display its title:
            var node = data.node;
            setDeviceStructure(node.key, 0, node.title);
            //$("#echoActive").text(node.title);
            //alert(node.title);
        },
        lazyLoad: function (event, data) {
            var node = data.node;
            // Load child nodes via ajax GET /getTreeData?mode=children&parent=1234
            data.result = {
                url: node.data.src,
                //url: "index.php?module=category&event=json&type=ticket",
                data: {mode: "children", parent: node.key},
                cache: false
            };
        }
    }).show();
}
function showStructureBox() {
    var txtfield = document.getElementById("DeviceStructrueDescr");
    var userbox = document.getElementById("DeviceStructure");

    if (userbox.style.visibility != "visible") {
        var spantop = absTop(txtfield);
        var spanleft = absLeft(txtfield);
        var spanwidth = txtfield.offsetWidth;
        var spanheight = txtfield.offsetHeight;

        spantop = spantop + spanheight;
        spanwidth = spanwidth - 2;

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

        userbox.style.visibility = "visible";
        userbox.style.display = "block";
        getDeviceStructure();
    } else {
        userbox.style.visibility = "hidden";
        userbox.style.display = "none";
    }
}

function setDeviceStructure(sid, childs, name) {
    DeviceStructureID = sid;
    document.getElementById('DeviceStructrueDescr').value = name;
    showStructureBox();
    switchDevicePage(0);
    $("#delDeviceStructrueDescr").show();
}

function clearDeviceStructure() {
    DeviceStructureID = 0;
    document.getElementById('DeviceStructrueDescr').value = '';
    switchDevicePage(0);
    $("#delDeviceStructrueDescr").hide();
}

function switchDevicePage(pos) {
    DevicePagePos = pos;
    getDevices();
}

function switchLDAPDevicePage(pos) {
    DevicePagePos = pos;
    getLDAPDevices();
}

function getDevices() {

    objDeviceList = document.getElementById("Devices");
    sid = (DeviceStructureID > 0) ? "&sid=" + DeviceStructureID : "";
    suche = encodeURIComponent(document.getElementById('DeviceSearch').value);
    var suche = '';
    suche = $("#DeviceSearch").val();

    suche = (suche.length > 0) ? "&search=" + suche : "";
    var owndevices = document.getElementById("DeviceOwner");
    check = (owndevices && owndevices.checked) ? "&owndevices=1" : "";
    tid = (DeviceTicketID > 0) ? "&tid=" + DeviceTicketID : "";
    sessid = (DeviceSessionID == 1) ? "&sessid=1" : "";
    cid = (DeviceContactID > 0) ? "&cid=" + DeviceContactID : "&cid=0";
    var contactdevices = document.getElementById("DeviceContact");
    con = (contactdevices && contactdevices.checked) ? "&con=1" : "";
    var cal = (CalendarModule && CalendarModule == 1) ? "&cal=1" : "";


    //Kontaktid aus Ticketformular verwenden:
    url = "index.php?module=device&event=getDeviceListXML&pos=" + DevicePagePos + sid + suche + check + tid + sessid + cid + con + cal;
    if ('' != con) {
        var ContactID = ($("#contact_id").val()) ? $("#contact_id").val() : parent.$("#contact_id").val();

        if ('cid=' != ContactIDString && 0 < ContactID) {
            var ContactIDString = 'cid=' + ContactID;
            var re = /\.*(cid=[0-9]*)\.*/;
            re.exec(url);

            url = url.replace(re, ContactIDString);
        }
    }

    makeHttpRequest(url, "buildDeviceList", true);
}

function getLDAPDevices() {
    objDeviceList = document.getElementById("Devices");
    sid = (DeviceStructureID > 0) ? "&sid=" + DeviceStructureID : "";
    suche = encodeURIComponent(document.getElementById('LDAPDeviceSearch').value);
    suche = (suche.length > 0) ? "&search=" + suche : "";
    var owndevices = document.getElementById("DeviceOwner");
    check = (owndevices && owndevices.checked) ? "&owndevices=1" : "";
    tid = (DeviceTicketID > 0) ? "&tid=" + DeviceTicketID : "";
    sessid = (DeviceSessionID == 1) ? "&sessid=1" : "";
    cid = (DeviceContactID > 0) ? "&cid=" + DeviceContactID : "&cid=0";
    var contactdevices = document.getElementById("DeviceContact");
    con = (contactdevices && contactdevices.checked) ? "&con=1" : "";
    var cal = (CalendarModule && CalendarModule == 1) ? "&cal=1" : "";

    makeHttpRequest(
            "index.php?module=device&event=ldap_getDeviceListXML&pos=" + DevicePagePos + sid + suche + check + tid + sessid + cid + con + cal,
            "buildLDAPDeviceList", true);
}

function buildLDAPDeviceList(xmldoc) {

    var HTMLOutput = "";
    var devices = xmldoc.getElementsByTagName("device");
    var navigation = xmldoc.getElementsByTagName("navigation")[0];
    var Pages = navigation.getAttribute("pages");
    var navigationString = "&nbsp;";


    if (Pages > 1) {

        var EntriesPerPage = navigation.getAttribute("entriesperpage");
        var Entries = navigation.getAttribute("entries");
        var Page = navigation.getAttribute("page");
        var pos = navigation.getAttribute("pos");

        posback = (parseInt(pos) > 0) ? parseInt(pos) - 1 : 0;
        lastpage = (parseInt(Pages) > 0) ? parseInt(Pages) - 1 : 0;
        nextpage = (parseInt(pos) < lastpage) ? parseInt(pos) + 1 : lastpage;


        navigationString = "<tr><td colspan=\"10\" >&nbsp;&nbsp;<div class=\"navigation\">";
        navigationString += '<ul class="pagination">';
        navigationString += '<li>Seite: </li>';
        if (parseInt(pos) > 0) {
            navigationString += '<li><a href="#" onclick="switchLDAPDevicePage(' + posback + ')" class="button button-grey"><span>&laquo;</span></a></li>';
        }
        if (0 < parseInt(Pages)) {
            navigationString += '<li><href="#" onclick="switchLDAPDevicePage(0)" class="button button-';
            navigationString += (pos == 0) ? 'green' : 'grey';
            navigationString += '"><span>1</span></a></li>';
        }
        if (1 < parseInt(Pages)) {
            navigationString += '<li><href="#" onclick="switchLDAPDevicePage(1)" class="button button-';
            navigationString += (pos == 1) ? 'green' : 'grey';
            navigationString += '"><span>2</span></a></li>';
        }
        if (2 < parseInt(Pages)) {
            navigationString += '<li><href="#" onclick="switchLDAPDevicePage(2)" class="button button-';
            navigationString += (pos == 2) ? 'green' : 'grey';
            navigationString += '"><span>3</span></a></li>';
        }
        if (3 < parseInt(Pages)) {
            navigationString += '<li><href="#" onclick="switchLDAPDevicePage(3)" class="button button-';
            navigationString += (pos == 3) ? 'green' : 'grey';
            navigationString += '"><span>4</span></a></li>';
        }
        if (4 < parseInt(Pages)) {
            navigationString += '<li><href="#" onclick="switchLDAPDevicePage(4)" class="button button-';
            navigationString += (pos == 4) ? 'green' : 'grey';
            navigationString += '"><span>5</span></a></li>';
        }
        if (5 < parseInt(Pages)) {

            if (5 < pos) {
                navigationString += '<li>...</li>'
            }
            ;
            if (4 < pos && (parseInt(pos) + 1) < Pages) {

                navigationString += '<li><a href="#" onclick="" class="button button-green"><span>' + nextpage + '</span></a></li>';

                navigationString += '<li>...</li>';
            }

            navigationString += '<li><href="#" onclick="switchLDAPDevicePage(' + lastpage + ')" class="button button-';
            navigationString += (pos == lastpage) ? 'green' : 'grey';
            navigationString += '"><span>' + parseInt(Pages) + '</span></a></li>';
            navigationString += '<li><a href="#" onclick="switchLDAPDevicePage(' + nextpage + ')" class="button button-grey"><span>&raquo;</span></a></li>';

        }
        navigationString += '</ul>';
        navigationString += '</div>';
        navigationString += "</td></tr>";
    } else {
        navigationString = "";
    }

    if (devices.length > 0) {
        for (i = 0; i < devices.length; i++) {

            imgNode = devices[i].getElementsByTagName('TypeFileName')[0];
            devidNode = devices[i].getElementsByTagName('DevID')[0];
            devicenameNode = devices[i].getElementsByTagName('DeviceName')[0];
            modelNode = devices[i].getElementsByTagName('Model')[0];
            locationNode = devices[i].getElementsByTagName('Location')[0];
            descrNode = devices[i].getElementsByTagName('Description')[0];
            osNode = devices[i].getElementsByTagName('OS')[0];
            TypeNode = devices[i].getElementsByTagName('Type')[0];

            imgVal = imgNode.firstChild.nodeValue;
            devidVal = devidNode.firstChild.nodeValue;
            devicenameVal = devicenameNode.firstChild.nodeValue;
            modelVal = modelNode.firstChild.nodeValue;
            locationVal = locationNode.firstChild.nodeValue;
            descrVal = descrNode.firstChild.nodeValue;
            osVal = osNode.firstChild.nodeValue;
            typeVal = TypeNode.firstChild.nodeValue;



            HTMLOutput += '<div class="device" onmouseover="this.className=\'device_hover\'" onmouseout="this.className=\'device\'">';
            HTMLOutput += '  <div class="device_img device_' + imgVal + '"><img src="images/blank.gif" height="48" width="48" alt=""></div>';
            HTMLOutput += '  <div class="device_name">' + devicenameVal + ' (' + typeVal + ')';

            if (DevicePopUP) {
                HTMLOutput += '&nbsp;<a href="JavaScript:void(0);" onclick="addLDAPDevice(' + devidVal + ');"><img src="images/add.gif" width="16" height="16" alt="" border="0"  /></a>';
            }

            if ((DeviceRemovePossible && DeviceTicketID > 0 && DeviceStatusID != 3 && DeviceStatusID != 7) || DeviceSessionID == 1) {
                HTMLOutput += '&nbsp;<a href="JavaScript:void(0);" onclick="delLDAPDeviceTicket(' + devidVal + ');"><img src="images/delete2.gif" width="16" height="16" alt="" border="0"  /></a>';
            }

            HTMLOutput += '</div>';
            HTMLOutput += LocationLabel + ': ' + locationVal + ' <br />';

            if (typeVal == 'WS') {
                HTMLOutput += ' OS: ' + osVal + ' <br />';
                HTMLOutput += DescrLabel + ': ' + descrVal;
            } else {
                HTMLOutput += ModelLabel + ': ' + modelVal + ' <br />';
                HTMLOutput += CommentLabel + ': ' + descrVal;
            }

            HTMLOutput += '</div>';

        }
    } else {


        HTMLOutput = NoDevLabel;
    }

    document.getElementById('LDAPDevices').innerHTML = HTMLOutput;
    document.getElementById('LDAPDeviceNavigation').innerHTML = navigationString;
}

function buildDeviceList(xmldoc) {
    console.log("buildDeviceList in device.js");
    var HTMLOutput = '<ul class="list-group">';
    var devices = xmldoc.getElementsByTagName("device");
    var navigation = xmldoc.getElementsByTagName("navigation")[0];
    var Pages = navigation.getAttribute("pages");
    var navigationString = "&nbsp;";

    if (Pages > 1) {

        var EntriesPerPage = navigation.getAttribute("entriesperpage");
        var Entries = navigation.getAttribute("entries");
        var Page = navigation.getAttribute("page");
        var pos = navigation.getAttribute("pos");

        posback = (parseInt(pos) > 0) ? parseInt(pos) - 1 : 0;
        lastpage = (parseInt(Pages) > 0) ? parseInt(Pages) - 1 : 0;
        nextpage = (parseInt(pos) < lastpage) ? parseInt(pos) + 1 : lastpage;


        navigationString = "<tr><td colspan=\"1\" >&nbsp;&nbsp;<div class=\"navigation\">";
        navigationString += '<ul class="pagination">';
        //navigationString += '<li>Seite: </li>';
        if (parseInt(pos) > 0) {
            navigationString += '<li><a href="#" onclick="switchDevicePage(' + posback + ')" class="button button-grey"><span>&laquo;</span></a></li>';
        }
        if (0 < parseInt(Pages)) {
            navigationString += '<li><a href="#" onclick="switchDevicePage(0)" class="button button-';
            navigationString += (pos == 0) ? 'green' : 'grey';
            navigationString += '"><span>1</span></a></li>';
        }
        if (1 < parseInt(Pages)) {
            navigationString += '<li><a href="#" onclick="switchDevicePage(1)" class="button button-';
            navigationString += (pos == 1) ? 'green' : 'grey';
            navigationString += '"><span>2</span></a></li>';
        }
        if (2 < parseInt(Pages)) {
            navigationString += '<li><a href="#" onclick="switchDevicePage(2)" class="button button-';
            navigationString += (pos == 2) ? 'green' : 'grey';
            navigationString += '"><span>3</span></a></li>';
        }
        if (3 < parseInt(Pages)) {
            navigationString += '<li><a href="#" onclick="switchDevicePage(3)" class="button button-';
            navigationString += (pos == 3) ? 'green' : 'grey';
            navigationString += '"><span>4</span></a></li>';
        }
        if (4 < parseInt(Pages)) {
            navigationString += '<li><a href="#" onclick="switchDevicePage(4)" class="button button-';
            navigationString += (pos == 4) ? 'green' : 'grey';
            navigationString += '"><span>5</span></a></li>';
        }
        if (5 < parseInt(Pages)) {

            if (5 > pos) {
                navigationString += '<li><a href="#">...</a</li>';
            }

            if (4 < pos && (parseInt(pos) + 1) < Pages) {

                navigationString += '<li><a href="#" onclick="" class="button button-green"><span>' + nextpage + '</span></a></li>';

                navigationString += '<li><a href="#">...</a</li>';
            }

            navigationString += '<li><a href="#" onclick="switchDevicePage(' + lastpage + ')" class="button button-';
            navigationString += (pos == lastpage) ? 'green' : 'grey';
            navigationString += '"><span>' + parseInt(Pages) + '</span></a></li>';
            navigationString += '<li><a href="#" onclick="switchDevicePage(' + nextpage + ')" class="button button-grey"><span>&raquo;</span></a></li>';

        }
        navigationString += '</ul>';
        navigationString += '</div>';
        navigationString += "</td></tr>";
    } else {
        navigationString = "";
    }

    if (devices.length > 0) {
        for (i = 0; i < devices.length; i++) {

            imgNode = devices[i].getElementsByTagName('TypeFileName')[0];
            devidNode = devices[i].getElementsByTagName('DevID')[0];
            hostnameNode = devices[i].getElementsByTagName('Hostname')[0];
            devicenameNode = devices[i].getElementsByTagName('DeviceName')[0];
            modelNode = devices[i].getElementsByTagName('Model')[0];
            manufactNode = devices[i].getElementsByTagName('Manufacturer')[0];
            typenameNode = devices[i].getElementsByTagName('TypeName')[0];
            domainNode = devices[i].getElementsByTagName('DomainName')[0];
            ownerNode = devices[i].getElementsByTagName('Owner')[0];
            contactNode = devices[i].getElementsByTagName('Contact')[0];
            imgVal = imgNode.firstChild.nodeValue;
            devidVal = devidNode.firstChild.nodeValue;
            hostnameVal = hostnameNode.firstChild.nodeValue;
            devicenameVal = devicenameNode.firstChild.nodeValue;
            modelVal = modelNode.firstChild.nodeValue;
            manufactVal = manufactNode.firstChild.nodeValue;
            typenameVal = typenameNode.firstChild.nodeValue;
            domainVal = domainNode.firstChild.nodeValue;
            ownerVal = ownerNode.firstChild.nodeValue;
            contactVal = contactNode.firstChild.nodeValue;
            inventorynoNode = devices[i].getElementsByTagName('InventoryNo')[0];
            inventorynoVal = inventorynoNode.firstChild.nodeValue;
            physicalPathNode = devices[i].getElementsByTagName('physicalPath')[0];
            physicalPathVal = physicalPathNode.firstChild.nodeValue;

            /*
             HTMLOutput += '<div class="device" onmouseover="this.className=\'device_hover\'" onmouseout="this.className=\'device\'">';
             HTMLOutput += '  <div class="device_img device_' + imgVal + '"><img src="images/blank.gif" height="48" width="48" alt=""></div>';
             HTMLOutput += '  <div class="device_name">' + hostnameVal + ' (' + typenameVal + ')';
             
             if (contactVal == 1) {
             HTMLOutput += ' <img src="images/hm.gif" width="16" height="16" alt="owner" >';
             }
             
             if (ownerVal == 1) {
             HTMLOutput += ' <img src="images/status_online.gif" width="16" height="16" alt="owner" >';
             }
             
             HTMLOutput += ' <a href="JavaScript:void(0)" onclick="ShowDevDetails(' + devidVal + ');"><img src="images/details.gif" width="16" height="16" border="0" alt="" title="Details" ></a>';
             
             if (DevicePopUP) {
             HTMLOutput += '&nbsp;<a href="JavaScript:void(0);" onclick="addDevice(' + devidVal + ');"><img src="images/add.gif" width="16" height="16" alt="" border="0"  /></a>';
             }
             
             if (CalendarActive && CalendarActive == 1){
             HTMLOutput += '&nbsp;<a href="index.php?module=calendar&event=device&class=event&iframe=1&caldeviceid='+ devidVal + '" class="calDeviceEvent dialog" data-fancybox-type="iframe" ><img src="images/cal.gif" width="16" height="16" alt="Calendar" border="0" title="Reservieren" /></a>';
             }
             
             if ((DeviceRemovePossible && DeviceTicketID > 0 && DeviceStatusID != 3 && DeviceStatusID != 7) || DeviceSessionID == 1) {
             HTMLOutput += '&nbsp;<a href="JavaScript:void(0);" onclick="delDeviceTicket(' + devidVal + ');"><img src="images/delete2.gif" width="16" height="16" alt="" border="0"  /></a>';
             }
             
             HTMLOutput += '</div>';
             
             HTMLOutput += '<div class="pysicalPath">' + physicalPathVal + '</div>';
             
             HTMLOutput += '  ' + domainVal;
             if (domainVal != '' && devicenameVal != '') {
             HTMLOutput += ' / ';
             }
             HTMLOutput += devicenameVal ;
             
             if (devicenameVal != '' && inventorynoVal != '') {
             HTMLOutput += ' / ';
             }
             HTMLOutput += inventorynoVal + '<br />'
             
             HTMLOutput += '  ' + manufactVal;
             if (manufactVal != '' && modelVal != '') {
             HTMLOutput += ' / ';
             }
             HTMLOutput += modelVal + ' <br />';
             
             HTMLOutput += '</div>';
             HTMLOutput += '<div id="Device' + devidVal + '" class="DeviceDetails"></div>';
             
             */

            HTMLOutput += '<li class="list-group-item" id="device_' + devidVal + '"><div class="device">';
            HTMLOutput += '<div class="card panel-default"><div class="card-header">';
            HTMLOutput += '<div class="row"><div class="col-xs-6"><h3 class="card-title">' + hostnameVal + ' (' + typenameVal + ')</h3></div>';
            HTMLOutput += '<div class="col-xs-6 text-end">';
            if (contactVal == 1) {
                HTMLOutput += ' <span class="fa fa-circle-info"></span> ';
            }

            if (ownerVal == 1) {
                HTMLOutput += ' <span class="fa fa-user"></span>';
            }

            //HTMLOutput += ' <a class="btn btn-outline-primary btn-sm" href="JavaScript:void(0)" onclick="ShowDevDetails(' + devidVal + ');" title="Details"><span class="fa fa-info"></span></a>';
            loadAssetDetailsJQString = '$("#Device' + devidVal + '").load("index.php?module=device&event=assetInfo&id=' + devidVal + '");$("#Device' + devidVal + '").toggle();';
            HTMLOutput += '<div class="btn-group">';
            HTMLOutput += ' <a class="btn btn-outline-primary btn-sm" href="JavaScript:void(0)" onclick=\'' + loadAssetDetailsJQString + '\' title="Details"><span class="fa fa-info"></span></a>';


            if ((DeviceRemovePossible && DeviceTicketID > 0 && DeviceStatusID != 3 && DeviceStatusID != 7) || DeviceSessionID == 1) {
                HTMLOutput += '<a class="btn btn-outline-primary btn-sm delDeviceLink lightContrast" href="JavaScript:void(0);"  onclick="delDeviceTicket(' + devidVal + ');"><span class="fa fa-times"></span></a>';
            } else {
                HTMLOutput += ' <a class="btn btn-outline-primary btn-sm addDeviceLink lightContrast" href="JavaScript:void(0);" onclick="addDevice(' + devidVal + ');"><span class="fa fa-plus"></span></a>';
            }

            HTMLOutput += "<a class=\"btn btn-outline-primary btn-sm lightContrast\" href=\"javascript: copyElementToClipboard('table_" + devidVal + "') \" title='" + strCopyAssetDataToClipboard + "'><span class=\"fa fa-copy\"></span></a>";

            HTMLOutput += '</div>';
            HTMLOutput += '</div></div></div><div class="card-body">';
            HTMLOutput += '  <div class="device_img device_' + imgVal + '"><img src="images/blank.gif" height="48" width="48" alt=""></div>';
            HTMLOutput += '<div class="pysicalPath" title="Pfad zum Gerät">' + physicalPathVal + '</div>';
            HTMLOutput += '  <span title="Domäne">' + domainVal + '</span>';
            if (domainVal != '' && devicenameVal != '') {
                HTMLOutput += ' / <span title="Gerätename">';
                HTMLOutput += devicenameVal + '</span>';
            }


            if (devicenameVal != '' && inventorynoVal != '') {
                HTMLOutput += ' / <span title="Inventarnummer">';
                HTMLOutput += inventorynoVal + '</span><br />'
            }


            HTMLOutput += '  <span title="Hersteller">' + manufactVal + '</span>';
            if (manufactVal != '' && modelVal != '') {
                HTMLOutput += ' / <span title="Modell">';
                HTMLOutput += modelVal + '</span>';
            }
            var TableOutPut = '<div style="display:none;" id="table_' + devidVal + '"><p><strong>Assetname:</strong>' + devicenameVal + '</p><p><strong>Assettyp:</strong> ' + typenameVal + '</p>';
            if (domainVal !== '') {
                TableOutPut += '<p><strong>Domäne:</strong>' + domainVal + '</p>';
            }
            if (physicalPathVal !== '') {
                TableOutPut += '<p><strong>Pfad:</strong>' + physicalPathVal + '</p>';
            }
            if (inventorynoVal !== '') {
                TableOutPut += '<p><strong>Inventarnummer:</strong>' + inventorynoVal + '</p>';
            }
            if (manufactVal !== '' && modelVal !== '') {
                TableOutPut += '<p><strong>Hersteller:</strong>' + manufactVal + '</p><p>Modell:' + modelVal + '</p>';
            }
            TableOutPut += '</div>';
            HTMLOutput += TableOutPut;

//            HTMLOutput += '<br />';
            HTMLOutput += '<div id="Device' + devidVal + '" class="DeviceDetails" style="display:none;"></div></div></li>';
        }
    } else {


        HTMLOutput = NoDevLabel;
    }
    HTMLOutput += '<div id="DeviceNavigation">' + navigationString + '</div>';

    document.getElementById('Devices').innerHTML = HTMLOutput;
    //document.getElementById('DeviceNavigation').innerHTML = navigationString;


    ChangeAllDeviceCounters(devices.length);

}


function ChangeAllDeviceCounters(Count) {
    var allElems = document.getElementsByTagName('span');
    for (var i = 0; i < allElems.length; i++) {
        var thisElem = allElems[i];
        if (thisElem.className && thisElem.className == 'DeviceCount') {
            thisElem.innerHTML = Count;
        }
    }
}

function ShowDevDetails(DevID) {

    var divObj = document.getElementById("Device" + DevID);
    divObj.style.display = (divObj.style.display != "block")
            ? "block" : "none";

    DeviceSelected = DevID;

    if (divObj.style.display == "block" && divObj.innerHTML.length == 0) {
        ShowHardware(DevID);
    }
}

function ShowHardware(DevID) {

    DeviceSelected = DevID;
    var divObj = document.getElementById("Device" + DevID);
    switchDeviceTab(DevID, "Hardware");

    if (divObj.innerHTML.length == 0) {

        divObj.innerHTML = '<img src="images/ajax-loader.gif" width="31" height="31" alt="Loading..." title="Loading.." />';

        makeHttpRequest("index.php?module=device&event=getHardwareXML&id=" + DevID,
                "buildDeviceHardware", true);
    }
}

function ShowTickets(DevID) {

    DeviceSelected = DevID;
    var divObj = document.getElementById("DeviceTicket" + DevID);
    switchDeviceTab(DevID, "Ticket");

    //if (divObj.innerHTML.length == 0) {
    {

        divObj.innerHTML = '<img src="images/ajax-loader.gif" width="31" height="31" alt="Loading..." title="Loading.." />';

        //makeHttpRequest("index.php?module=device&event=getDeviceTickets&id=" + DevID,"buildDeviceTickets", false);
        $("#DeviceTicket" + DevID).load("index.php?module=device&event=getDeviceTickets&id=" + DevID);
    }
}


function ShowSoftware(DevID) {

    DeviceSelected = DevID;
    var divObj = document.getElementById("DeviceSoftware" + DevID);
    switchDeviceTab(DevID, "Software");

    if (divObj.innerHTML.length == 0) {

        divObj.innerHTML = '<img src="images/ajax-loader.gif" width="31" height="31" alt="Loading..." title="Loading.." />';

        makeHttpRequest("index.php?module=device&event=getSoftwareXML&id=" + DevID,
                "buildDeviceSoftware", true);
    }
}

function ShowCommercialDevData(DevID) {

    DeviceSelected = DevID;
    var divObj = document.getElementById("DeviceCommercialDevData" + DevID);
    switchDeviceTab(DevID, "CommercialDevData");

    if (divObj.innerHTML.length == 0) {

        divObj.innerHTML = '<img src="images/ajax-loader.gif" width="31" height="31" alt="Loading..." title="Loading.." />';

        makeHttpRequest("index.php?module=device&event=getCommercialDevData&id=" + DevID,
                "buildDeviceCommercialDevData", true);
    }
}

function ShowUserDefInfos(DevID) {

    DeviceSelected = DevID;
    var divObj = document.getElementById("DeviceUserDefInfos" + DevID);
    switchDeviceTab(DevID, "UserDefInfos");

    if (divObj.innerHTML.length == 0) {

        divObj.innerHTML = '<img src="images/ajax-loader.gif" width="31" height="31" alt="Loading..." title="Loading.." />';

        makeHttpRequest("index.php?module=device&event=getUserDefInfosXML&id=" + DevID,
                "buildDeviceUserDefInfos", true);
    }
}

function buildDeviceHardware(xmldoc) {

    var divObj = document.getElementById("Device" + DeviceSelected);
    var HTMLOutput = "";
    var Device = xmldoc.getElementsByTagName("Device");
    var TABOutput = "";
    var DIVOutput = "";

    // Device
    if (Device.length > 0 && Device[0].childNodes.length > 0) {

        TABOutput += '<li><a href="JavaScript:void(0);" class="active" id="HardwareTab' + DeviceSelected + '" onclick="ShowHardware(' + DeviceSelected + ');"><span>' + HWLabel + '</span></a></li>';
        HTMLOutput += "<table border=\"0\" cellspacing=\"0\" style=\"display:block;width:100%\" id=\"Hardware" + DeviceSelected + "\" class=\"UserDefInfo\">";
        HTMLOutput += "<tr><th>" + DescrLabel + "&nbsp;</th><th>" + ValueLabel + "&nbsp;</th></tr>";

        for (i = 0; i < Device[0].childNodes.length; i++) {
            if ((Device[0].childNodes[i].nodeType == 1)) {

                tmpNode = Device[0].getElementsByTagName(Device[0].childNodes[i].nodeName)[0];
                tmpVal = (tmpNode.childNodes.length > 0)
                        ? tmpNode.firstChild.nodeValue : "";

                if (Device[0].childNodes[i].nodeName == "swproduct") {

                    if (tmpVal > 0) {
                        TABOutput += '<li><a href="JavaScript:void(0);" id="SoftwareTab' + DeviceSelected + '" onclick="ShowSoftware(' + DeviceSelected + ');"><span>' + SWLabel + '</span></a></li>';
                        DIVOutput += '<div id="DeviceSoftware' + DeviceSelected + '" class=\"SoftwareCatalog\" style=\"display:none;\"></div>';
                    }
                    continue;
                }

                if (Device[0].childNodes[i].nodeName == "userdefinfos") {
                    if (tmpVal > 0) {
                        TABOutput += '<li><a href="JavaScript:void(0);" id="UserDefInfosTab' + DeviceSelected + '" onclick="ShowUserDefInfos(' + DeviceSelected + ');"><span>' + UserDefLabel + '</span></a></li>';
                        DIVOutput += '<div id="DeviceUserDefInfos' + DeviceSelected + '" style=\"display:none;\"></div>';
                    }
                    continue;
                }

                if (Device[0].childNodes[i].nodeName == "commercialdevdata") {
                    if (tmpVal > 0) {
                        TABOutput += '<li><a href="JavaScript:void(0);" id="CommercialDevDataTab' + DeviceSelected + '" onclick="ShowCommercialDevData(' + DeviceSelected + ');"><span>' + CommercialLabel + '</span></a></li>';
                        DIVOutput += '<div id="DeviceCommercialDevData' + DeviceSelected + '" style=\"display:none;\"></div>';
                    }
                    continue;
                }

                //HTMLOutput += "<tr class=\"row0\">";
                if (i % 2 == 0) {
                    HTMLOutput += "<tr class=\"even\">";
                } else {
                    HTMLOutput += "<tr class=\"odd\">";
                }
                HTMLOutput += "<td>" + Device[0].childNodes[i].nodeName + "</td>";
                HTMLOutput += "<td style=\"width:100%;\">" + tmpVal + "&nbsp;</td>";
                HTMLOutput += "</tr>";
            }
        }
        HTMLOutput += "</table>";
        TABOutput += '<li><a href="JavaScript:void(0);" class="active" id="TicketTab' + DeviceSelected + '" onclick="ShowTickets(' + DeviceSelected + ');"><span>' + TicketLabel + '</span></a></li>';
        DIVOutput += '<div id="DeviceTicket' + DeviceSelected + '" style=\"display:none;\">AA</div>';
    }

    HTMLOutput = '<div class="DeviceTabs" id="DeviceTabs' + DeviceSelected + '"><ul>' + TABOutput +
            "</ul><br style=\"clear:both;\"></div>" + HTMLOutput +
            DIVOutput;

    divObj.innerHTML = HTMLOutput;
}

function buildDeviceTickets(xmldoc)
{
    var divObj = document.getElementById("DeviceTicket" + DeviceSelected);
    divObj.innerHTML = xmldoc;
    $('.footable_DeviceTickets').footable();
}

function buildDeviceSoftware(xmldoc) {

    divObj = document.getElementById("DeviceSoftware" + DeviceSelected);

    var HTMLOutput = "";
    var Software = xmldoc.getElementsByTagName("apps");

    if (Software.length > 0) {

        HeaderOutput = "<tr>";
        HTMLOutputSW = "";
        var tmpDescr = '';

        for (i = 0; i < Software.length; i++) {

            evenodd = i % 2;

            HTMLOutputSW += "<tr class=\"row" + evenodd + "\">";


            for (j = 0; j < Software[i].childNodes.length; j++) {

                if ((Software[i].childNodes[j].nodeType == 1)) {

                    tmpNode = Software[i].getElementsByTagName(Software[i].childNodes[j].nodeName)[0];
                    tmpVal = (tmpNode.childNodes.length > 0)
                            ? tmpNode.firstChild.nodeValue
                            : "";

                    HTMLOutputSW += "<td>" + tmpVal + "&nbsp;</td>";

                    if (i == 0) {
                        if (undefined != SoftwareDev[Software[i].childNodes[j].nodeName]) {
                            tmpDescr = SoftwareDev[Software[i].childNodes[j].nodeName];
                        } else {
                            tmpDescr = Software[i].childNodes[j].nodeName;
                        }
                        if (tmpDescr == 'Produktname') {
                            HeaderOutput += "<th data-toggle=\"true\">" + tmpDescr + "</th>";
                        } else {
                            HeaderOutput += "<th data-hide=\"phone,tablet\">" + tmpDescr + "</th>";
                        }

                    }
                }
            }
            HTMLOutputSW += "</tr>";
        }

        HTMLOutput += "<table border=\"0\" cellspacing=\"0\" class=\"footable_DeviceSW\">";
        HTMLOutput += "<thead>" + HeaderOutput + "</tr></thead>";
        HTMLOutput += "<tbody>" + HTMLOutputSW + "</tbody></table>";
    }
    divObj.innerHTML = HTMLOutput;
    $('.footable_DeviceSW').footable();
}

function buildDeviceCommercialDevData(xmldoc) {

    divObj = document.getElementById("DeviceCommercialDevData" + DeviceSelected);

    var HTMLOutput = "";
    var Commercial = xmldoc.getElementsByTagName("CommercialDevData");
    var j = 0;

    // Device
    if (Commercial.length > 0) {

        HTMLOutput += "<table border=\"0\" cellspacing=\"0\"" +
                " style=\"display:block;width:100%\" class=\"UserDefInfo\">";
        HTMLOutput += "<tr><th>" + DescrLabel + "&nbsp;</th>" +
                "<th>" + ValueLabel + "&nbsp;</th></tr>";

        for (i = 0; i < Commercial[0].childNodes.length; i++) {

            if ((Commercial[0].childNodes[i].nodeType == 1)) {
                tmpNode = Commercial[0].getElementsByTagName(
                        Commercial[0].childNodes[i].nodeName)[0];
                tmpVal = (tmpNode.childNodes.length > 0)
                        ? tmpNode.firstChild.nodeValue
                        : "";
                evenodd = j % 2;
                HTMLOutput += "<tr class=\"row" + evenodd + "\">";
                HTMLOutput += "<td>" +
                        CommercialDev[Commercial[0].childNodes[i].nodeName] +
                        "&nbsp;</td>";
                HTMLOutput += "<td style=\"width:100%;\">" + tmpVal + "&nbsp;</td>";
                HTMLOutput += "</tr>";
                j++;
            }
        }

        HTMLOutput += "</table>";
    }
    divObj.innerHTML = HTMLOutput;
}

function buildDeviceUserDefInfos(xmldoc) {

    divObj = document.getElementById("DeviceUserDefInfos" + DeviceSelected);

    var HTMLOutput = "";
    var UserDef = xmldoc.getElementsByTagName("UserDefInfos");

    if (UserDef.length > 0 && UserDef[0].childNodes.length > 0) {

        var j = 0;
        var evenodd = 0;

        HTMLOutput += "<table border=\"0\" cellspacing=\"0\" style=\"width:100%\" class=\"UserDefInfo\">";
        HTMLOutput += "<tr><th>" + DescrLabel + "&nbsp;</th><th>" + ValueLabel + "&nbsp;</th></tr>";

        for (i = 0; i < UserDef[0].childNodes.length; i++) {
            if ((UserDef[0].childNodes[i].nodeType == 1)) {

                evenodd = j % 2;
                tmpNode = UserDef[0].getElementsByTagName(UserDef[0].childNodes[i].nodeName)[0];
                tmpVal = (tmpNode.childNodes.length > 0)
                        ? tmpNode.firstChild.nodeValue
                        : "";

                HTMLOutput += "<tr class=\"row" + evenodd + "\">";
                HTMLOutput += "<td>" + UserDef[0].childNodes[i].nodeName + "</td>";
                HTMLOutput += "<td style=\"width:100%;\">" + tmpVal + "&nbsp;</td>";
                HTMLOutput += "</tr>";
                j++;
            }
        }
        HTMLOutput += "</table>";
    }
    divObj.innerHTML = HTMLOutput;
}

function switchDeviceTab(devid, tab) {

    var divObj = document.getElementById("DeviceTabs" + devid);

    if (divObj) {
        var tabs = divObj.getElementsByTagName("a");
        for (i = 0; i < tabs.length; i++) {
            tabs[i].className = "";
        }

        document.getElementById(tab + "Tab" + devid).className = 'active';

        if (obj = document.getElementById("Hardware" + devid)) {
            obj.style.display = "none";
        }

        if (obj = document.getElementById("DeviceTicket" + devid)) {
            obj.style.display = "none";
        }

        if (obj = document.getElementById("DeviceSoftware" + devid)) {
            obj.style.display = "none";
        }

        if (obj = document.getElementById("DeviceUserDefInfos" + devid)) {
            obj.style.display = "none";
        }

        if (obj = document.getElementById("DeviceCommercialDevData" + devid)) {
            obj.style.display = "none";
        }

        tab = (tab !== "Hardware")
                ? "Device" + tab + devid : tab + devid;

        if (obj = document.getElementById(tab)) {
            obj.style.display = "block";
        }
    }
}

function copyToClipboard(html) {
    // Create container for the HTML
    // [1]
    var container = document.createElement('div')
    container.innerHTML = html;

    // Hide element
    // [2]
    container.style.position = 'fixed';
    container.style.pointerEvents = 'none';
    container.style.opacity = 0;

    // Detect all style sheets of the page
    var activeSheets = Array.prototype.slice.call(document.styleSheets)
            .filter(function (sheet) {
                return !sheet.disabled;
            })

    // Mount the container to the DOM to make `contentWindow` available
    // [3]
    document.body.appendChild(container);

    // Copy to clipboard
    // [4]
    window.getSelection().removeAllRanges();

    var range = document.createRange();
    range.selectNode(container);
    window.getSelection().addRange(range);

    // [5.1]
    document.execCommand('copy');

    // [5.2]
    for (var i = 0; i < activeSheets.length; i++) {
        activeSheets[i].disabled = false;
    }

    // [5.3]
    document.execCommand('copy');

    // [5.4]
    for (var i = 0; i < activeSheets.length; i++) {
        activeSheets[i].disabled = false;
    }

    // Remove the container
    // [6]
    document.body.removeChild(container);
}

function copyElementToClipboard(element) {
    $("#" + element).show();
    window.getSelection().removeAllRanges();
    let range = document.createRange();
    range.selectNode(typeof element === 'string' ? document.getElementById(element) : element);
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    $("#" + element).hide();
    noty({
        text: "[% $user->gettext('Assetdaten wurden in die Zwischenablage kopieren') %]",
        type: 'success',
        timeout: notifyTimeout
    });
}
