
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) {
    TicketID = (0 < tid) ? tid : TicketID;
    AttachmentList = true;
    objAttachmentList = document.getElementById("AttachmentList");
    objAttachmentList.innerHTML = "";

    if (Activity) {
        makeHttpRequest("index.php?module=upload&event=AJAXUploadList&activityid=" + aid + "&preacts=" + PreActs, "buildAttachmentList", true);
    } else {
        makeHttpRequest("index.php?module=upload&event=AJAXUploadList&tid=" + TicketID, "buildAttachmentList", true);
    }

}

function getActivityAttachments(aid, PreActs) {
    if (PreActs == undefined) {
        addPreActs = "";
    } else {
        addPreActs = "&preacts=" + PreActs
    }
    TicketID = aid;
    Activity = true;
    AttachmentList = true;
    objAttachmentList = document.getElementById("AttachmentList");
    objAttachmentList.innerHTML = "";

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


function buildAttachmentList(xmldoc) {
    console.log("Build attachment list..");
    var attachments = xmldoc.getElementsByTagName("attachment");
    var navigation = xmldoc.getElementsByTagName("navigation")[0];
    var Pages = navigation.getAttribute("pages");
    var Page = navigation.getAttribute("page");
    var pos = navigation.getAttribute("pos");
    var EntriesPerPage = navigation.getAttribute("entriesperpage");
    var Entries = navigation.getAttribute("entries");
    if (parseInt(pos) > 0) {
        posback = parseInt(pos) - 1;
    } else {
        posback = 0;
    }
    if (parseInt(Pages) > 0) {
        lastpage = parseInt(Pages) - 1;
    } else {
        lastpage = 0;
    }
    if (parseInt(pos) < lastpage) {
        nextpage = parseInt(pos) + 1;
    } else {
        nextpage = lastpage;
    }

    if (Entries > 0) {
        $('#DocumentCount').html(Entries);
    }
    if (Pages > 1) {
        navigationString = "<tr><td colspan=\"10\" >&nbsp;&nbsp;<div class=\"navigation\">";
        navigationString += '<ul>';
        navigationString += '<li>Seite:</li>';
        if (parseInt(pos) > 0) {
            navigationString += '<li><a href="#" onclick="switchPage(' + posback + ',' + TicketID + ')" class="button button-grey"><span>&laquo;</span></a></li>';
        }
        if (0 == parseInt(pos)) {
            navigationString += '<li><href="#" onclick="switchPage(0, ' + TicketID + ')" class="button button-green"><span>1</span></a></li>';
        } else {
            navigationString += '<li><href="#" onclick="switchPage(0, ' + TicketID + ')" class="button button-grey"><span>1</span></a></li>';
        }


        if (1 < parseInt(Pages)) {
            if (1 == parseInt(pos)) {
                navigationString += '<li><href="#" onclick="switchPage(1, ' + TicketID + ')" class="button button-green"><span>2</span></a></li>';
            } else {
                navigationString += '<li><href="#" onclick="switchPage(1, ' + TicketID + ')" class="button button-grey"><span>2</span></a></li>';
            }
        }
        ;
        if (2 < parseInt(Pages)) {
            if (2 == parseInt(pos)) {
                navigationString += '<li><href="#" onclick="switchPage(2, ' + TicketID + ')" class="button button-green"><span>3</span></a></li>';
            } else {
                navigationString += '<li><href="#" onclick="switchPage(2, ' + TicketID + ')" class="button button-grey"><span>3</span></a></li>';
            }
        }
        ;
        if (3 < parseInt(Pages)) {
            if (3 == parseInt(pos)) {
                navigationString += '<li><href="#" onclick="switchPage(3, ' + TicketID + ')" class="button button-green"><span>4</span></a></li>';
            } else {
                navigationString += '<li><href="#" onclick="switchPage(3, ' + TicketID + ')" class="button button-grey"><span>4</span></a></li>';
            }
        }
        ;
//        if (4 < parseInt(Pages)) {
//            navigationString += '<li><href="#" onclick="switchPage(4, ' + TicketID + ')" class="button button-grey"><span>5</span></a></li>'
//        };
        if (5 < parseInt(Pages)) {
            navigationString += '<li>...</li>';

            if (pos > 3 && (parseInt(pos) + 1) <= lastpage) {
                navigationString += '<li><a href="#" onclick="switchPage(' + nextpage + ', ' + TicketID + ')" class="button button-green"><span>' + (parseInt(pos) + 1) + '</span></a></li>';
                if (pos < lastpage) {
                    navigationString += '<li>...</li>';
                }

            }
            navigationString += '<li><a href="#" onclick="switchPage(' + lastpage + ', ' + TicketID + ')" class="button button-grey"><span>' + parseInt(Pages) + '</span></a></li>';
            navigationString += '<li><a href="#" onclick="switchPage(' + nextpage + ', ' + TicketID + ')" class="button button-grey"><span>&raquo;</span></a></li>';
        }
        ;

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

    HTMLOutput = "<table class=\"listview footable2\" cellspacing=\"0\">\n";
    HTMLOutput += " <thead>\n";
    HTMLOutput += "     <tr>\n";
    HTMLOutput += "         <th colspan=\"1\">\n";
    HTMLOutput += "             <strong>" + DocHeaders[10] + "</strong>\n";
    HTMLOutput += "         </th>\n";
    HTMLOutput += "         <th colspan=\"10\">\n";
    HTMLOutput += "             <a href=\"#dialog-add-document\" class=\"button button-black dialog\" id=\"addDocumentBtn\" ><span class=\"add\"><strong>+</strong> " + DocHeaders[11] + "</span></a>\n";
    HTMLOutput += "         </th>\n";
    HTMLOutput += "     </tr>\n";
    HTMLOutput += "     <tr class=\"fields\">\n";

    if (Activity) {
        HTMLOutput += "	   <th data-hide=\"phone,tablet\">" + DocHeaders[9] + "</th>\n";
    }

    HTMLOutput += "	   <th data-toggle=\"true\" >" + DocHeaders[0] + "</th>\n	   <th>" + DocHeaders[1] + "</th>\n";
    HTMLOutput += "    <th data-hide=\"phone,tablet\">" + DocHeaders[2] + "</th>\n	   <th data-hide=\"phone,tablet\">" + DocHeaders[3] + "</th>\n";
    HTMLOutput += "	   <th data-hide=\"phone,tablet\">" + DocHeaders[4] + "</th>\n    <th data-hide=\"phone,tablet\">" + DocHeaders[8] + "</th>\n ";

    HTMLOutput += (bool_hasRight[230]) ? "    <th data-hide=\"phone,tablet\">Dateipfad</th>\n\n" : "";

    HTMLOutput += "      <th data-hide=\"phone,tablet\">" + DocHeaders[5] + "</th>\n <th data-hide=\"phone,tablet\">" + DocHeaders[6] + "</th>\n    <th data-hide=\"phone,tablet\">&nbsp;</th>\n";

    HTMLOutput += "     </tr>\n";
    HTMLOutput += " </thead>\n";

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

            row = attachments[i];
            typ = row.getAttribute("typ");
            if (Activity && row.getAttribute("activityid") == TicketID) {
                HTMLOutput += "  <tr class=\"even\">\n"
            } else {
                HTMLOutput += "  <tr class=\"odd\">\n"
            }


            if (row.getAttribute("activityid")) {
                HTMLOutput += "    <td>" + row.getAttribute("activityname") + "(" + row.getAttribute("activityid") + ")";
            }

            if (typ == 1 || row.getAttribute("fname")) {

                if (true || row.getAttribute("thumbnail")) {
                    HTMLOutput += "    <td data-toggle=\"true\" >&nbsp;<a href=\"index.php?module=upload&event=ShowImage&name=" + row.getAttribute("tmpname") + "\" target=\"top\">" + row.getAttribute("fname") + "</a></td>\n";
                } else {
                    HTMLOutput += "    <td data-toggle=\"true\" >&nbsp;<a href=\"index.php?module=upload&event=download&id=" + row.getAttribute("id") + "\" target=\"top\">" + row.getAttribute("fname") + "</a></td>\n";
                }

            } else if (typ == 2 || row.getAttribute("url")) {
                HTMLOutput += "    <td data-toggle=\"true\" >&nbsp;<a href=\"" + row.getAttribute("url") + "\" target=\"top\">" + row.getAttribute("url") + "</a></td>\n";
            } else {
                HTMLOutput += "    <td data-toggle=\"true\" >&nbsp;&nbsp;</td>\n";
            }

            HTMLOutput += "    <td><img src=\"" + row.getAttribute("mime") + "\" /></td>\n";

            HTMLOutput += (row.getAttribute("size")) ?
                    "    <td >" + row.getAttribute("size") + " KB</td>\n" : "    <td>&nbsp;</td>\n";

            HTMLOutput += (row.getAttribute("shortdescr")) ?
                    "    <td >" + row.getAttribute("shortdescr") + "</td>\n" : "    <td>&nbsp;</td>\n";

            HTMLOutput += (row.getAttribute("thumbnail")) ?
                    "    <td><a href=\"index.php?module=upload&event=ShowImage&name=" + row.getAttribute("tmpname") + "\" class=\"ImageDialog\" title=\"" + row.getAttribute("fname") + "\"><img src=\"index.php?module=upload&event=ShowImage&name=" + row.getAttribute("thumbnail") + "\" border=\"0\" title=\"(" + row.getAttribute("width") + "x" + row.getAttribute("height") + ")\" /></td>\n" :
                    "    <td>&nbsp;</td>\n";

            HTMLOutput += (row.getAttribute("thumbnail")) ?
                    "    <td>[hm_img]" + row.getAttribute("tmpname") + "[/hm_img]</td>\n" :
                    "    <td>&nbsp;</td>\n";

            HTMLOutput += (bool_hasRight[230]) ?
                    UncUploadPath :
                    // "    <td>\n\<a href='" + UncUploadPath + row.getAttribute("tmpname") + "' target='_blank' >" + row.getAttribute("tmpname") + "</a> </td>\n" :
                    "";



            HTMLOutput += "    <td>" + row.getAttribute("cdate") + "</td>\n";
            HTMLOutput += "    <td>" + row.getAttribute("cuser") + "</td>\n";

            HTMLOutput += "    <td width=\"50\" style=\"text-align:right !important;white-space:nowrap;\">";

            if (typ == 3 || typ == 2 || typ == 1) {
                HTMLOutput += "<a href=\"index.php?module=upload&event=FileDetails&id=" + row.getAttribute("id") + "\" data-fancybox-type=\"iframe\" class=\"dialog\"><img src=\"images/details.gif\" width=\"16\" height=\"16\" alt=\"\" border=\"0\" align=\"absmiddle\" /></a>";

            }

            if (row.getAttribute("remove") == "true") {
                HTMLOutput += "<a href=\"index.php?module=upload&event=editFileDetails&amp;id=" + row.getAttribute("id") + "&amp;tid=" + TicketID + "\" data-fancybox-type=\"iframe\" class=\"dialog\"><img src=\"images/edit.gif\" width=\"16\" height=\"16\" alt=\"\" border=\"0\" align=\"absmiddle\" /></a>";
                HTMLOutput += "&nbsp;<a href=\"JavaScript:void(0);\" onclick=\"RemoveAttachment(" + row.getAttribute("id") + ");\"><img src=\"images/delete.gif\" height=\"16\" width=\"16\" alt=\"Delete\" border=\"0\" align=\"absmiddle\"></a>";
            }

            HTMLOutput += "&nbsp;<a href=\"JavaScript:void(0);\" onclick=\"RemoveAttachment(" + row.getAttribute("id") + ");\"><span class='fa fa-lock'></span></a>";

            HTMLOutput += "&nbsp;</td>\n";

            // HTMLOutput += "    <td>"+row.getAttribute("cuserid")+"</td>\n";
            HTMLOutput += "  </tr>\n"

        }
    } else {
        HTMLOutput += "  <tr class=\"row1\"><td colspan=\"8\" align=\"center\">" + DocHeaders[7] + "</td></tr>\n";
    }

    HTMLOutput += navigationString + "</table>\n";

    objAttachmentList.innerHTML = HTMLOutput;
    $('.footable2').footable();
}


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 SelectTicketTab(tid) {

    $.ajax({
        type: "POST",
        url: "index.php?module=contact&event=ContactTickets&tid=" + tid,
        contentType: 'Content-type: text/plain; charset=iso-8859-1',
        beforeSend: function (jqXHR) {
            jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
        }
    })
            .done(function (data) {
                $("#LastTicketsFrameContact").html(data);
                $('.footable_LastTickets').footable();
            });


    $.ajax({
        type: "POST",
        url: "index.php?module=device&event=getLastDeviceTickets&tid=" + tid,
        contentType: 'Content-type: text/plain; charset=iso-8859-1',
        beforeSend: function (jqXHR) {
            jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
        }
    })
            .done(function (data) {
                $("#LastTicketsFrameDevices").html(data);
                $('.footable_DeviceTickets').footable();

            });

}

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)
{

    var previus_name = $("#" + text_name).val();
    var previus_id = $("#" + id_name).val();

    $("#" + text_name).autocomplete(task, {
        minChars: 2,
        matchSubset: 1,
        matchContains: 1,
        cacheLength: 1,
        max: 0,
        onItemSelect: selectItem,
        formatItem: formatItem,
        //    		autoFill:1,       //Verfolständigt eingabe beim Tippen
        extraParams: {
            x: function () {
                //$("#"+id_name).val('');
            }    //Leert alten Wert im ID-Feld, wenn Eingabe gemacht wird
        },
        width: 310,
        scroll: true,
        scrollHeight: 180

    });

    if (id_name == 'contact_id') {

        $("#" + text_name).result(function (event, data, formatted) {

            if (data && data[1] != previus_id) {

                var conf2 = confirm(ts_ChangeContact);
                if (conf2) {
                    makeHttpRequest("index.php?module=contact&event=TSearchContact&tid=" + TicketID + "&cid=" + data[1] + "&save=1&confirmOnHold=hold", "ContactChanged", false);
                    $("#" + id_name).val(data[1]);
                    //Wenn Kontakt gewechselt wird, die neuen Daten merken:
                    previus_name = $("#" + text_name).val();
                    previus_id = $("#" + id_name).val();

                    if (data[2] && '' !== data[2]) {
                        $("#ContactCompany").html("Firma: " + data[2]).show();
                        //$("#ContactCompanyDiv").css( "display", "inline");
                    } else {
                        $("#ContactCompany").hide();
                    }
                    if (data[3] && '' !== data[3]) {
                        $("#ContactPhone").html("Telefon: " + data[3]).show();
                        //$("#ContactPhoneDiv").css( "display", "inline");
                    } else {
                        $("#ContactPhone").hide();
                    }
                    if ((data[3] && '' !== data[3]) || (data[2] && '' !== data[2])) {
                        $("#ContactAddData").show();
                    } else {
                        $("#ContactAddData").hide();
                    }
                    if (data[4]) {
                        $("#" + text_name).val(data[4]);
                    }

                } else {
                    //Wenn auf confirm = Nein ist, alte Daten einfüllen:
                    $("#" + text_name).val(previus_name);
                    $("#" + id_name).val(previus_id);
                }

            }
        });
    }

    if (id_name == 'CategoryID1') {

        $("#" + text_name).result(function (event, data, formatted) {

            if (data && data[1] != previus_id) {

                var conf2 = confirm(ts_ChangeCat1);
                if (conf2) {


                    $.getJSON("index.php?module=category&class=select&save=1&Confirmed=1&ajax=1", {tid: TicketID, cid: data[1], }, function (json) {
                        if (json != '') {
                            //var Message = '<span class="error">'+json+'</span><br />';
                            //$('#editCompanyNameMessage').html(Message);
                            $("#TicketDesireDate").val(json.expires);

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

                            $("#" + id_name).val(data[1]);
                            //Wenn Kontakt gewechselt wird, die neuen Daten merken:
                            previus_name = $("#" + text_name).val();
                            previus_id = $("#" + id_name).val();

                        } else {

                        }
                    });
                    /*
                     makeHttpRequest("index.php?module=category&class=select&tid=" + TicketID + "&cid=" + data[1] + "&save=1&Confirmed=1&ajax=1", "Category1Changed", false);
                     $("#" + id_name).val(data[1]);
                     //Wenn Kontakt gewechselt wird, die neuen Daten merken:
                     previus_name = $("#" + text_name).val();
                     previus_id = $("#" + id_name).val();
                     */

                } else {
                    //Wenn auf confirm = Nein ist, alte Daten einfüllen:
                    $("#" + text_name).val(previus_name);
                    $("#" + id_name).val(previus_id);
                }

            }
        });
    }
    if (id_name == 'group_id') {

        $("#" + text_name).result(function (event, data, formatted) {

            if (data && data[1] != previus_id) {
                var conf2 = confirm(ts_ChangeGroup);
                if (conf2) {
                    makeHttpRequest("index.php?module=ticket&event=changeGroupSupporter&tid=" + TicketID + "&GroupID=" + data[1] + "&SupporterID=0&save=1&confirmOnHold=hold", "GroupChanged", false);
                    $("#" + id_name).val(data[1]);
                    //Wenn Kontakt gewechselt wird, die neuen Daten merken:
                    previus_name = $("#" + text_name).val();
                    previus_id = $("#" + id_name).val();

                    $("#user_id").val(0)
                    $("#user_descr").val('')

                } else {
                    //Wenn auf confirm = Nein ist, alte Daten einfüllen:
                    $("#" + text_name).val(previus_name);
                    $("#" + id_name).val(previus_id);
                }

            }
        });
    }
    if (id_name == 'TicketRefId2') {

        $("#" + text_name).result(function (event, data, formatted) {

            if (data && data[1] != previus_id) {
                var conf2 = confirm(ts_ChangeMasterticket);
                if (conf2) {
                    makeHttpRequest("index.php?module=ticketlist&event=RefTickets&tid=" + TicketID + "&TRefID=" + data[1] + "&save=1", "ChangeRefTicket", false);
                    $("#" + id_name).val(data[1]);
                    //Wenn Kontakt gewechselt wird, die neuen Daten merken:
                    previus_name = $("#" + text_name).val();
                    previus_id = $("#" + id_name).val();

                } else {
                    //Wenn auf confirm = Nein ist, alte Daten einfüllen:
                    $("#" + text_name).val(previus_name);
                    $("#" + id_name).val(previus_id);
                }

            }
        });
    }


}

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;
}
