
var nul_DataClass = Class.create({
    initialize: function() {
        this.views = new Hash();
        this.timeDataIndex = 0;
    },

    mark: function(index, source) {
        this.views.each(function(pair) {
            // Umbiegen des Index wenn ein Einzel Zeitdiagram angezeigt wird
            var markIndex = index;
            if (this.timeDataIndex > 0) {
                if ("time" == pair.key) {
                    if ("table" == source) {
                        markIndex = -1;
                        if (index == this.timeDataIndex) {
                            markIndex = 0;
                        }
                    }
                } else if ("table" == pair.key) {
                    if ("time" == source) {
                        markIndex = this.timeDataIndex;
                    }
                }
            }
            if (markIndex < pair.value.max) {
                pair.value.mark(markIndex);
            }
        }.bind(this));
    },

    unMark: function(index, source) {
        this.views.each(function(pair) {
            var markIndex = index;
            if (this.timeDataIndex > 0) {
                if ("time" == pair.key && "table" == source && index == this.timeDataIndex) {
                    markIndex = 0;
                } else if ("table" == pair.key && "time" == source) {
                    markIndex = this.timeDataIndex;
                }
            }
            pair.value.unMark(markIndex);
        }.bind(this));
    },
    
    initTable: function() {
        if ($("tablecontent")) {
            this.views.set("table", new nul_DataViewTable(this));
        }
    },
    
    initPie: function() {
        if (!$("pieholder")) {
            return;
        }
        new Ajax.Request("index.php?get=piebuilder&data=" + nul_data_pie + "&type=svg", {
            method: "get",
            onSuccess: function(transport) {
                var svgContent = transport.responseText;
                if (Prototype.Browser.IE) {
                    svg_2_silverlight_canvas($("pieholder"), svgContent);
                } else {
                    this.setSvgContent($("pieholder"), svgContent);
                    this.views.set("pie", new nul_DataViewPie(this, "svg"));
                }
            }.bind(this),
            onFailure: nulAjaxFailure,
            onException: nulAjaxException
        });
    },
    initPieSilverlightEvents: function() {
        this.views.set("pie", new nul_DataViewPie(this, "silverlight"));
    },
    
    initTime: function(dataIndex) {
        if (!$("timeholder")) {
            return;
        }
        this.timeDataIndex = dataIndex;
        // nul_data_time.replace(/\&amp\;/g, "&")
        new Ajax.Request("index.php?" + nul_data_time.toQueryString() + "&type=svg", {
            method: "get",
            onSuccess: function(transport) {
                var svgContent = transport.responseText;
                if (Prototype.Browser.IE) {
                    svg_2_silverlight_canvas($("timeholder"), svgContent);
                } else {
                    this.setSvgContent($("timeholder"), svgContent);
                    this.views.set("time", new nul_DataViewTime(this, "svg"));
                }                
            }.bind(this)
        });
    },
    initTimeSilverlightEvents: function() {
        this.views.set("time", new nul_DataViewTime(this, "silverlight"));
    },
    
    setSvgContent: function(object, svg) {
        if (Prototype.Browser.Opera) {
            var parser = new DOMParser();
        	var doc = parser.parseFromString(svg, "image/svg+xml");
        	var root = doc.documentElement;
            var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
            svg.style.width = "100%";
            svg.style.height = "100%";
            object.innerHTML = "";
            object.appendChild(svg);
        	for (var i = 0; i < root.childNodes.length; ++ i) {
        		svg.appendChild(document.importNode(root.childNodes[i], true));
        	}
        } else {
            object.innerHTML = svg;
        }
    }
});

var nul_DataView = Class.create({
    initialize: function(data) {
        this.data = data;
        this.max = Number.MAX_VALUE;
        this.objectDocument = null;
    },

    mark: function() {},

    unMark: function() {}
});

var nul_DataViewTable = Class.create(nul_DataView, {
    initialize: function($super, data) {
        $super(data);
        $("tablecontent").select("tr").invoke("observe", "mouseover", this.mouseOver.bindAsEventListener(this)).invoke("observe", "mouseout", this.mouseOut.bindAsEventListener(this));
    },

    mouseOver: function(event) {
        var index = event.findElement("tr").id.match(/[0-9]+/);
        this.data.mark(index, "table");
    },

    mouseOut: function(event) {
        var index = event.findElement("tr").id.match(/[0-9]+/);
        this.data.unMark(index, "table");
    },
    
    mark: function(index) {
        var datarow = $("datarow" + index);
        if (datarow) {
            datarow.addClassName("over");
        }
    },

    unMark: function(index) {
        var datarow = $("datarow" + index);
        if (datarow) {
            datarow.removeClassName("over");
        }
    }
});

var nul_DataViewPie = Class.create(nul_DataView, {
    initialize: function($super, data, type) {
        $super(data);
        this.max = 0;
        if ("svg" == type) {
            this.mark = this.svgMark;
            this.unMark = this.svgUnMark;
            
            var i = -1;
            var pieoverlay = null;
            var pielegend  = null;
            var pielpart   = null;
            do {
                i++;
                pieoverlay = $("pieoverlay" + i);
                if (pieoverlay) {
                    Event.observe(pieoverlay, "mouseover", this.svgMouseOver.bindAsEventListener(this));
                    Event.observe(pieoverlay, "mouseout", this.svgMouseOut.bindAsEventListener(this));
                }
                pielegend = $("pielegend" + i);
                if (pielegend) {
                    Event.observe(pielegend, "mouseover", this.svgMouseOver.bindAsEventListener(this));
                    Event.observe(pielegend, "mouseout", this.svgMouseOut.bindAsEventListener(this));
                }
                pielpart = $("pielpart" + i);
                if (pielpart) {
                    Event.observe(pielpart, "mouseover", this.svgMouseOver.bindAsEventListener(this));
                    Event.observe(pielpart, "mouseout", this.svgMouseOut.bindAsEventListener(this));
                }
            } while (pielegend);
            this.max = i - 1;
            
        } else if ("silverlight" == type) {
            this.mark = this.silverlightMark;
            this.unMark = this.silverlightUnMark;
            this.objectDocument = $("silverlight_pieholder").content;
            this.pieSliceColors = [];
            this.legendColors = [];
            
            var i = -1;
            var pieoverlay = null;
            var pielegend  = null;
            var pielpart   = null;
            do {
                i++;
                pieoverlay = this.objectDocument.findName("pieoverlay" + i);
                if (pieoverlay) {
                    pieoverlay.AddEventListener("MouseEnter", this.silverlightMouseOver.bindAsEventListener(this));
                    pieoverlay.AddEventListener("MouseLeave", this.silverlightMouseOut.bindAsEventListener(this));
                }
                pielegend = this.objectDocument.findName("pielegend" + i);
                if (pielegend) {
                    pielegend.AddEventListener("MouseEnter", this.silverlightMouseOver.bindAsEventListener(this));
                    pielegend.AddEventListener("MouseLeave", this.silverlightMouseOut.bindAsEventListener(this));
                    this.legendColors[i] = pielegend.Foreground.Color;
                }
                pielpart = this.objectDocument.findName("pielpart" + i);
                if (pielpart) {
                    pielpart.AddEventListener("MouseEnter", this.silverlightMouseOver.bindAsEventListener(this));
                    pielpart.AddEventListener("MouseLeave", this.silverlightMouseOut.bindAsEventListener(this));
                    this.pieSliceColors[i] = pielpart.Fill.Color;
                }
            } while (pielegend);
            this.max = i - 1;
        }
    },
    
    svgMouseOver: function (event) {
        var index = event.target.getAttribute("id").match(/[0-9]+/);
        if (index < this.max) {
            this.data.mark(index, "pie");
        } else {
            this.mark(index);
        }
    },
    
    svgMouseOut: function (event) {
        var index = event.target.getAttribute("id").match(/[0-9]+/);
        if (index < this.max) {
            this.data.unMark(index, "pie");
        } else {
            this.unMark(index);
        }
    },
    
    silverlightMouseOver: function (sender) {
        var index = sender.Name.match(/[0-9]+/);
        if (index < this.max) {
            this.data.mark(index, "pie");
        } else {
            this.mark(index);
        }
    },
    
    silverlightMouseOut: function (sender) {
        var index = sender.Name.match(/[0-9]+/);
        if (index < this.max) {
            this.data.unMark(index, "pie");
        } else {
            this.unMark(index);
        }
    },

    svgMark: function(index) {
        var pieslice = $("pieslice" + index);
        if (pieslice) {
            pieslice.setAttribute("class", "over");
        }
        var pielegend = $("pielegend" + index);
        if (pielegend) {
            pielegend.setAttribute("class", "over");
        }
        var pielpart = $("pielpart" + index);
        if (pielpart) {
            pielpart.setAttribute("class", "over");
        }
    },

    svgUnMark: function(index) {
        var pieslice = $("pieslice" + index);
        if (pieslice) {
            pieslice.setAttribute("class", "");
        }
        var pielegend = $("pielegend" + index);
        if (pielegend) {
            pielegend.setAttribute("class", "");
        }
        var pielpart = $("pielpart" + index);
        if (pielpart) {
            pielpart.setAttribute("class", "");
        }
    },

    silverlightMark: function(index) {
        var pieslice = this.objectDocument.findName("pieslice" + index);
        if (pieslice) {
            pieslice.Fill.Color = "#EF3B3B";
        }
        var pielegend = this.objectDocument.findName("pielegend" + index);
        if (pielegend) {
            pielegend.Foreground.Color = "#EF3B3B";
        }
        var pielpart = this.objectDocument.findName("pielpart" + index);
        if (pielpart) {
            pielpart.Fill.Color = "#EF3B3B";
        }
    },

    silverlightUnMark: function(index) {
        var pieslice = this.objectDocument.findName("pieslice" + index);
        if (pieslice) {
            pieslice.Fill.Color = this.pieSliceColors[index];
        }
        var pielegend = this.objectDocument.findName("pielegend" + index);
        if (pielegend) {
            pielegend.Foreground.Color = this.legendColors[index];
        }
        var pielpart = this.objectDocument.findName("pielpart" + index);
        if (pielpart) {
            pielpart.Fill.Color = this.pieSliceColors[index];
        }
    }
});
                
var nul_DataViewTime = Class.create(nul_DataView, {
    initialize: function($super, data, type) {
        $super(data);
        this.max = 0;
        if ("svg" == type) {
            this.mark = this.svgMark;
            this.unMark = this.svgUnMark;
            
            var i = -1;
            var timeelement = null;
            var timelegend  = null;
            var timelpart   = null;
            do {
                i++;
                timeelement = $("timeelement" + i);
                if (timeelement) {
                    Event.observe(timeelement, "mouseover", this.svgMouseOver.bindAsEventListener(this));
                    Event.observe(timeelement, "mouseout", this.svgMouseOut.bindAsEventListener(this));
                }
                timelegend = $("timelegend" + i);
                if (timelegend) {
                    Event.observe(timelegend, "mouseover", this.svgMouseOver.bindAsEventListener(this));
                    Event.observe(timelegend, "mouseout", this.svgMouseOut.bindAsEventListener(this));
                }
                timelpart = $("timelpart" + i);
                if (timelpart) {
                    Event.observe(timelpart, "mouseover", this.svgMouseOver.bindAsEventListener(this));
                    Event.observe(timelpart, "mouseout", this.svgMouseOut.bindAsEventListener(this));
                }
            } while (timelegend);
            this.max = i;
            
        } else if ("silverlight" == type) {
            this.mark = this.silverlightMark;
            this.unMark = this.silverlightUnMark;
            this.objectDocument = $("silverlight_timeholder").content;
            this.timeElementColors = [];
            this.legendColors = [];
            
            var i = -1;
            var timeelement = null;
            var timelegend  = null;
            var pielpart   = null;
            do {
                i++;
                timeelement = this.objectDocument.findName("timeelement" + i);
                if (timeelement) {
                    timeelement.AddEventListener("MouseEnter", this.silverlightMouseOver.bindAsEventListener(this));
                    timeelement.AddEventListener("MouseLeave", this.silverlightMouseOut.bindAsEventListener(this));
                }
                timelegend = this.objectDocument.findName("timelegend" + i);
                if (timelegend) {
                    timelegend.AddEventListener("MouseEnter", this.silverlightMouseOver.bindAsEventListener(this));
                    timelegend.AddEventListener("MouseLeave", this.silverlightMouseOut.bindAsEventListener(this));
                    this.legendColors[i] = timelegend.Foreground.Color;
                }
                timelpart = this.objectDocument.findName("timelpart" + i);
                if (timelpart) {
                    timelpart.AddEventListener("MouseEnter", this.silverlightMouseOver.bindAsEventListener(this));
                    timelpart.AddEventListener("MouseLeave", this.silverlightMouseOut.bindAsEventListener(this));
                    this.timeElementColors[i] = timelpart.Fill.Color;
                }
            } while (timelegend);
            this.max = i;
        }
    },
    
    svgMouseOver: function (event) {
        var index = event.target.getAttribute("id").match(/[0-9]+/);
        if (index < this.max) {
            this.data.mark(index, "time");
        } else {
            this.mark(index);
        }
    },
    
    svgMouseOut: function (event) {
        var index = event.target.getAttribute("id").match(/[0-9]+/);
        if (index < this.max) {
            this.data.unMark(index, "time");
        } else {
            this.unMark(index);
        }
    },
    
    silverlightMouseOver: function (sender) {
        var index = sender.Name.match(/[0-9]+/);
        if (index < this.max) {
            this.data.mark(index, "time");
        } else {
            this.mark(index);
        }
    },
    
    silverlightMouseOut: function (sender) {
        var index = sender.Name.match(/[0-9]+/);
        if (index < this.max) {
            this.data.unMark(index, "time");
        } else {
            this.unMark(index);
        }
    },

    svgMark: function(index) {
        var timeelement = $("timeelement" + index);
        if (timeelement) {
            timeelement.setAttribute("class", "over overtrans");
        }
        var timelegend = $("timelegend" + index);
        if (timelegend) {
            timelegend.setAttribute("class", "over");
        }
        var timelpart = $("timelpart" + index);
        if (timelpart) {
            timelpart.setAttribute("class", "over overtrans");
        }
    },

    svgUnMark: function(index) {
        var timeelement = $("timeelement" + index);
        if (timeelement) {
            timeelement.setAttribute("class", "");
        }
        var timelegend = $("timelegend" + index);
        if (timelegend) {
            timelegend.setAttribute("class", "");
        }
        var timelpart = $("timelpart" + index);
        if (timelpart) {
            timelpart.setAttribute("class", "");
        }
    },

    silverlightMark: function(index) {
        var timeelement = this.objectDocument.findName("timeelement" + index);
        if (timeelement) {
            timeelement.Fill.Color = "#80EF3B3B";
        }
        var timelegend = this.objectDocument.findName("timelegend" + index);
        if (timelegend) {
            timelegend.Foreground.Color = "#EF3B3B";
        }
        var timelpart = this.objectDocument.findName("timelpart" + index);
        if (timelpart) {
            timelpart.Fill.Color = "#80EF3B3B";
        }
    },

    silverlightUnMark: function(index) {
        var timeelement = this.objectDocument.findName("timeelement" + index);
        if (timeelement) {
            timeelement.Fill.Color = this.timeElementColors[index];
        }
        var timelegend = this.objectDocument.findName("timelegend" + index);
        if (timelegend) {
            timelegend.Foreground.Color = this.legendColors[index];
        }
        var timelpart = this.objectDocument.findName("timelpart" + index);
        if (timelpart) {
            timelpart.Fill.Color = this.timeElementColors[index];
        }
    }
});

var nul_data = new nul_DataClass();

Event.observe(window, "load", function() {
    nul_data.initTable();
    nul_init_export();
    nul_init_timechart();
    nul_init_unit_select();
    nul_show_error_popup();
});

nul_init_timechart = function () {
    $$("table.style img.timechart").each(function (element) {
        element.observe("click", nul_showTimeChart);
    });
}

nul_showTimeChart = function (evt) {
    if ("undefined" == typeof nul_data_time_default) {
        nul_data_time_default = nul_data_time;
    }
    
    var row_index = 0;
    
    nul_data_time = nul_data_time_default;
    if ("object" == typeof evt) {
        var element = evt.element();
        if (element.alt.match(/element: /)) {
            nul_data_time.set("elements", element.alt.replace(/element: /, ""));
            //nul_data_time = nul_data_time_default.replace(/elements=[^&]+/, "elements="+element.alt.replace(/element: /, ""));
            row_index = 1 * element.up("tr").id.replace(/datarow/, "");
        }
    }
    
    $("timeholder").innerHTML = "";
    
    $("sdpiebox").style.visibility = "hidden";
    $("sdinfobox").style.visibility = "hidden";
    $("sdtimebox").style.visibility = "visible";
    
    nul_data.initTime(row_index);
}
nul_showPieChart = function () {
    $('sdtimebox').style.visibility = 'hidden';
    $('sdinfobox').style.visibility = 'visible';
    $('sdpiebox').style.visibility = 'visible';
}

nul_init_export = function () {
    if (!$("options")) {
        return;
    }
    $("options").select("a.export").each(function(element, index) {
        element.observe("click", function (e) {
            var element = e.findElement("a");
            var max = element.href.match(/limit=([0-9]+)/);
            if (null == max) {
                return;
            }
            e.stop();
            var select = $("exportlimit");
            select.nul_export_href = element.href;
            select.down("span").update(max[1]);
            select.down("input").value = "" + Math.round(max[1] / 100) + "0";
            select.down("img.icon").src = element.down("img").src;
            select.removeClassName("hide");
            select.down("input").focus();
        });
    });
    $("exportlimit").down("input").observe("keyup", function(e) {
        if (e.keyCode == 13) { // ENTER
    	    nul_process_export(e);
    	}
    });
    $("exportlimit").down(".submit").observe("click", nul_process_export);
    $("exportlimit").down(".close").observe("click", function (e) {
        e.stop();
        $("exportlimit").addClassName("hide");
    });
}
nul_process_export = function (e) {
    e.stop();
    var select = e.findElement("div");
    window.location.href = select.nul_export_href.replace(/limit=([0-9]+)/, "limit=" + select.down("input").value);
    $("exportlimit").addClassName("hide");
}

nul_init_unit_select = function () {
    if ($("userconfig_button")) {
        $("userconfig_button").observe("click", function(e) {
            window.location.href = "?get=login&unit_select=user";
        });
    }
    if (!$("unit_form")) {
        return;
    }
    $("unit_form").observe("submit", function(e) {
        var form = e.element();
        if (1 * form.unit_select.value == 0) {
            e.stop();
        }
    });
    $("unit_form").down("select").observe("change", function(e) {
        var select = e.element();
        if (1 * select.value > 0) {
            select.form.submit();
        }
    });
}

nul_setInnerHtmlById = function (id, html) {
    xhtmlInnerHtml($(id), html);
}

/* Table Data Blättern */
function nul_turnOverData(link) {
    if (link.href) {
        var offset = 0;
        var matchoffset = link.href.match(/offset=([0-9]+)/);
        if (matchoffset[1]) {
            offset = matchoffset[1];
        }
        var matchlink = link.href.match(/^([^\?]+)\?(.*)$/);
        if (matchlink[2]) {
            var url = matchlink[1];
            var pars = matchlink[2] + "&table=1";

            var request = new Ajax.Request(
                url,
                {
                    method: 'get',
                    parameters: pars,
                    onComplete: function (req, obj) {
                        xhtmlInnerHtml($("tablecontent"), req.responseText);
                        nul_data.initTable();
                    },
                    onSuccess: nulAjaxSuccess,
                    onFailure: nulAjaxFailure,
                    onException: nulAjaxException
                }
            );
        }
    }
    return false;
}
/* Table Data Blättern End */

/* Visit Table */
function nul_setVisitTableAction() {
    var rows = $("tablecontent").getElementsByTagName("tr");
    for (var i = 0; i < rows.length; i++) {
        if ((/(hide)/i).test(rows[i].className)) {
            rows[i].ondblclick = nulToggleVisitTable;
            rows[i].id = "toggle_row" + i;
            rows[i].nul_toggleId = i;
            if (rows[i - 1]) {
                rows[i - 1].ondblclick = nulToggleVisitTable;
                rows[i - 1].nul_toggleId = i;
                var cols = rows[i - 1].getElementsByTagName("td");
                if (cols[cols.length - 1].className == "toggle") {
                    cols[cols.length - 1].id = "toggle_icon" + i;
                    cols[cols.length - 1].onclick = nulToggleVisitTable;
                    cols[cols.length - 1].nul_toggleId = i;
                }
            }
        }
        var cols = rows[i].getElementsByTagName("th");
        if (cols && cols.length > 0 && cols[cols.length - 1].className == "toggle") {
            cols[cols.length - 1].onclick = nulToggleGroupVisitTable;
        }
    }
}
function nulToggleVisitTable() {
    if (this.nul_toggleId) {
        var toggleRow = $("toggle_row" + this.nul_toggleId);
        var toggleIcon = $("toggle_icon" + this.nul_toggleId);
        if ((/hide/i).test(toggleRow.className)) {
            toggleRow.className = toggleRow.className.replace(/hide/, "showline");
            toggleIcon.className = "togglehide";
        } else {
            toggleRow.className = toggleRow.className.replace(/showline/, "hide");
            toggleIcon.className = "toggle";
        }
    }
}
function nulToggleGroupVisitTable() {
    if ((/togglehide/i).test(this.className)) {
        this.className = "toggle";
    } else {
        this.className = "togglehide";
    }
    var subtbody = this.parentNode.parentNode.nextSibling;
    if (subtbody.nodeName.toLowerCase() != 'tbody') {
        subtbody = subtbody.nextSibling;
    }
    var subtd = subtbody.getElementsByTagName("td");
    for (var i = 0; i < subtd.length; i++) {
        if ((/toggle/i).test(subtd[i].className)) {
            var toggleRow = $("toggle_row" + subtd[i].nul_toggleId);
            var toggleIcon = $("toggle_icon" + subtd[i].nul_toggleId);
            if (this.className == "togglehide") {
                toggleRow.className = toggleRow.className.replace(/hide/, "showline");
                toggleIcon.className = "togglehide";
            } else {
                toggleRow.className = toggleRow.className.replace(/showline/, "hide");
                toggleIcon.className = "toggle";
            }
        }
    }
}

function nulVisitWindow(id, param) {
    var x = window.open('js.open.visit.php?id=' + id, 'nulvw' + id, 'width=500,height=500,left=100,top=60,resizable=1,menubar=0');
    if (!x) {
        return;
    }
}
/* Visit Table End */

/* Page Configs */
var nul_PageConfig = Class.create({
    initialize: function(type, deleteRight, maxPages) {
        this.type = type;
        this.ajaxGet = this.type + "config";
        if ("startpage" == this.type) {
            this.ajaxGet = "generalsetting";
        }
        this.list = $(this.type + "list");
        this.deleteRight = deleteRight;
        
        this.maxPages = maxPages;
        this.countPages = 0;
        
        this.search = $("searchfield");
        this.searchNav = {"prev": false, "next": false};
        this.searchTerm = "";
        this.searchActiv = false;
        this.searchOffset = 0;
        this.searchTimeout = false;
        
        this.resultList = $("searchresultlist");
        this.resultSelect = null;
        
        this.search.observe("keyup", this.searchAction.bindAsEventListener(this));
        $("searchresultprev").observe("click", this.prev.bindAsEventListener(this));
        $("searchresultnext").observe("click", this.next.bindAsEventListener(this));
    },

    add: function(e) {
        if (null != this.resultSelect) {
            this.resultSelect.removeClassName("highlight");
        }
        this.resultSelect = $(e.findElement("img").parentNode);
        this.resultSelect.addClassName("highlight");
        
        this.addAction();
    },
    
    addAction: function() {
        if (this.countPages >= this.maxPages) {
            $('errorhotspotmax').setStyle({display: "block"});
            return;
        }
        
        if ("hotspot2" == this.type && !$("hotspot2selstart").nulData) {
            $("hotspot2selstart").nulData = this.resultSelect.nulData;
            $("hotspot2selstart").appendChild(this.createPage(this.resultSelect.nulData));
            $("hotspot2start").setStyle({display: "block"});
            $("hotspot2headline").update(nulLang.hotspot2end);
            return;
        }
        
        $("searchloading").addClassName("loading");
        
        if ("hotspot2" == this.type) {
            this.resultSelect.nulData = {
                "id": $("hotspot2selstart").nulData.id,
                "language": $("hotspot2selstart").nulData.language,
                "image": $("hotspot2selstart").nulData.image,
                "name": $("hotspot2selstart").nulData.name,
                "id2": this.resultSelect.nulData.id,
                "language2": this.resultSelect.nulData.language,
                "image2": this.resultSelect.nulData.image,
                "name2": this.resultSelect.nulData.name
            }
        }
        
        var params = new Hash();
        params.set("get", this.ajaxGet);
        params.set("type", this.type);
        params.set("ajax", "add");
        params.set("add", this.resultSelect.nulData.id);
        if (this.resultSelect.nulData.id2) {
            params.set("add2", this.resultSelect.nulData.id2);
        }
        params.set("search", this.searchTerm);
        params.set("offset", this.searchOffset);
        
        new Ajax.Request(
            window.location.protocol + "//" + window.location.hostname + window.location.pathname,
            {
                method: "get",
                parameters: params,
                evalJSON: true,
                onSuccess: function(transport) {
                    $("searchloading").removeClassName("loading");
                    this.resultList.previous("p").setStyle({display: "none"});
                    $('hotspotcounter').update(this.countPages + 1);
                    this.show(this.resultSelect.nulData);
                    this.handleResult(transport.responseJSON);
                    nulAjaxSuccess(transport);
                }.bind(this),
                onFailure: function(transport) {
                    $("searchloading").removeClassName("loading");
                    this.resultList.previous("p").setStyle({display: "block"});
                    nulAjaxFailure(transport);
                }.bind(this),
                onException: nulAjaxException
            }
        );
    },
    
    remove: function(e) {
        var remove = $(e.findElement("img").parentNode);
        
        if (!remove.nulData.id) {
            return;
        }
        $("searchloading").addClassName("loading");
        
        var params = new Hash();
        params.set("get", this.ajaxGet);
        params.set("type", this.type);
        params.set("ajax", "remove");
        params.set("remove", remove.nulData.id);
        if (remove.nulData.id2) {
            params.set("remove2", remove.nulData.id2);
        }

        new Ajax.Request(
            window.location.protocol + "//" + window.location.hostname + window.location.pathname,
            {
                method: "get",
                parameters: params,
                evalJSON: true,
                onSuccess: function(transport) {
                    $("searchloading").removeClassName("loading");
                    remove.remove();
                    this.countPages --;
                    $('hotspotcounter').update(this.countPages);
                    if (this.countPages < this.maxPages) {
                        $('errorhotspotmax').setStyle({display: "none"});
                        return;
                    }
                    nulAjaxSuccess(transport);
                }.bind(this),
                onFailure: function(transport) {
                    $("searchloading").removeClassName("loading");
                    nulAjaxFailure(transport);
                }.bind(this),
                onException: nulAjaxException
            }
        );
    },
    
    show: function(data) {
        this.hideDefault();
        this.countPages ++;
        
        var element = new Element("div", {"class": "element"});
        element.nulData = data;
        if (this.deleteRight) {
            var img = new Element("img", {"class": "delete", "src": "image/page/remove.png"}).observe("click", this.remove.bindAsEventListener(this));
            element.appendChild(img);
        }

        element.appendChild(this.createPage(data));
        
        if ("hotspot2" == this.type) {
            element.appendChild(new Element("img", {"class": "imgpage2", "src": "image/page/hotspot2.png", "alt": ""}));
            var page = {
                "language": data.language2,
                "image": data.image2,
                "name": data.name2
            };
            element.appendChild(this.createPage(page));
        }
        
        this.list.appendChild(element);
    },
    
    createPage: function(page) {
        var div = new Element("div", {"class": "page"});
        
        if (page.image) {
            var lang = new Element("img", {"src": "image/languages/" + page.language + ".png", "alt": page.language})
        } else {
            var lang = document.createTextNode(page.language + " |");
        }
        div.appendChild(lang);
        div.appendChild(document.createTextNode(" "));
        
        var pageParts = page.name.split("~");
        for (var i = 0; i < pageParts.length; i++) {
            if (i > 0) {
                div.appendChild(document.createTextNode(" "));
                var sep = new Element("span", {"class": "p"})
                xhtmlInnerHtml(sep, "&rsaquo;");
                div.appendChild(sep);
                div.appendChild(document.createTextNode(" "));
            }
            div.appendChild(document.createTextNode(pageParts[i]));
        }
        return div;
    },
    
    hideDefault: function() {
        this.list.previous("p").hide();
    },
    
    searchAction: function(e) {
        if (false != this.searchTimeout) {
            window.clearTimeout(this.searchTimeout);
            this.searchTimeout = false;
        }
        if (this.searchActiv) {
            this.search.value = this.searchTerm;
            return;
        }
        
        // Keycodes für Suchergebnisauswahl abfragen
        if (e.keyCode == 40) { // DOWN
            if (null != this.resultSelect) {
                this.resultSelect.removeClassName("highlight");
                this.resultSelect = this.resultSelect.next();
            }
            if (null == this.resultSelect) {
                this.resultSelect = this.resultList.down();
            }
            this.resultSelect.addClassName("highlight");
            return;
            
        } else if (e.keyCode == 38) { // UP
            if (null != this.resultSelect) {
                this.resultSelect.removeClassName("highlight");
                this.resultSelect = this.resultSelect.previous();
            }
            if (null == this.resultSelect) {
                this.resultSelect = this.resultList.lastChild;
            }
            this.resultSelect.addClassName("highlight");
            return;
            
        } else if (e.keyCode == 27) { // ESC
            this.searchReset();
            return;
            
    	} else if (e.keyCode == 13) { // ENTER
    	    this.addAction();
            return;
    	    
    	} else if (e.keyCode == 33) { // PAGEUP
    	    this.prev();
            return;
            
    	} else if (e.keyCode == 34) { // PAGEDOWN
    	    this.next();
            return;
    	}

        if ("" != this.search.value && this.searchTerm != this.search.value) {
            this.searchOffset = 0;
            this.searchTimeout = window.setTimeout(this.searchRequest.bind(this), 250);
        }
    },
    
    searchReset: function() {
        this.search.value = "";
        this.searchTerm = "";
        this.searchOffset = 0;
        this.resultList.update();
        this.resultSelect = null;
        this.resultList.next().removeClassName("turnoverhighlight");
        $("searchresultprev").setStyle({display: "none"});
        $("searchresultnext").setStyle({display: "none"});
        $("searchresultinfo").setStyle({display: "none"});
    },
    
    select: function(e) {
        if (null != this.resultSelect) {
            this.resultSelect.removeClassName("highlight");
        }
        var el = e.element();
        while (el.className != "element") {
            el = el.parentNode;
        }
        
        this.resultSelect = el;
        this.resultSelect.addClassName("highlight");
        this.search.focus();
    },
    
    searchRequest: function() {
        this.searchTimeout = false;
        
        this.searchActiv = true;
        this.searchTerm = this.search.value;
        
        $("searchloading").addClassName("loading");
        
        var params = new Hash();
        params.set("get", this.ajaxGet);
        params.set("type", this.type);
        params.set("ajax", "search");
        params.set("search", this.searchTerm);
        params.set("offset", this.searchOffset);

        new Ajax.Request(
            window.location.protocol + "//" + window.location.hostname + window.location.pathname,
            {
                method: "get",
                parameters: params,
                evalJSON: true,
                onSuccess: function(transport) {
                    $("searchloading").removeClassName("loading");
                    this.resultList.previous("p").setStyle({display: "none"});
                    this.handleResult(transport.responseJSON);
                    nulAjaxSuccess(transport);
                }.bind(this),
                onFailure: function(transport) {
                    $("searchloading").removeClassName("loading");
                    this.resultList.previous("p").setStyle({display: "block"});
                    nulAjaxFailure(transport);
                }.bind(this),
                onException: nulAjaxException
            }
        );
    },
    
    handleResult: function(result) {
        this.searchActiv = false;
        
        this.resultList.update();
        this.resultSelect = null;
        
        if (result.length < 1) {
            if ("hotspot2" == this.type) {
                $("hotspot2headline").update(nulLang.hotspot2start);
                $("hotspot2start").setStyle({display: "none"});
                $("hotspot2selstart").nulData = false;
                $("hotspot2selstart").update();
                this.searchReset();
            }
            return;
        }
        
        this.searchNav = result.shift();
        
        for (var i = 0; i < result.length; i++) {
            var element = new Element("div", {"class": "element"});
            element.nulData = result[i];
            
            var img = new Element("img", {"class": "add", "src": "image/page/add.png"}).observe("click", this.add.bindAsEventListener(this));
            element.appendChild(img);
        
            var page = this.createPage(result[i]);
            if (!Prototype.Browser.IE) {
            page.observe("click", this.select.bindAsEventListener(this));
            page.observe("dblclick", this.add.bindAsEventListener(this));
            }
            element.appendChild(page);
            
            this.resultList.appendChild(element);
        }
        
        this.resultList.next().addClassName("turnoverhighlight");
        $("searchresultprev").setStyle({display: ("boolean" != typeof this.searchNav.prev ? "block" : "none")});
        $("searchresultnext").setStyle({display: ("boolean" != typeof this.searchNav.next ? "block" : "none")});
        
        $("searchresultinfo").update((this.searchOffset + 1) + " - " + (this.searchOffset + result.length));
        $("searchresultinfo").setStyle({display: (result.length > 0 ? "block" : "none")});
    },
    
    prev: function() {
        if ("boolean" != typeof this.searchNav.prev) {
	        this.searchOffset = this.searchNav.prev;
	        this.searchRequest();
	    } else {
	        $("searchresultprev").setStyle({display: "none"});
	    }
	    this.search.focus();
    },
    
    next: function() {
        if ("boolean" != typeof this.searchNav.next) {
	        this.searchOffset = this.searchNav.next;
	        this.searchRequest();
	    } else {
	        $("searchresultnext").setStyle({display: "none"});
	    }
	    this.search.focus();
    }
});

/* Page Configs End */

/* Ajax Layer */

nulAjaxLayer = function (element_id, ajax_params) {
    if ($(element_id)) {
        $(element_id).toggle();
        return false;
    }
    
    var width = 500;
    var top = document.viewport.getScrollOffsets().top + Math.round(document.viewport.getHeight() / 2) - 120;
    var left = Math.round((document.viewport.getWidth() - 987) / 2) + 320;
    
    var layer = new Element("div", {"class": "window_layer", "id": element_id}).setStyle({"position": "absolute", "top": top + "px", "left": left + "px", "width": width + "px"});
    var layerHeader = new Element("div", {"class": "header"});
    
    var layerHeaderLeftCorner = new Element("div", {"class": "left"}).setStyle({"width": "16px"});
    var layerHeaderHeadline = new Element("div", {"class": "headline"}).setStyle({"width": (width - 32).toString() + "px", "left": "16px"});
    var layerHeaderClose = new Element("img", {"src": "image/page/cross.gif", "class": "close"}).observe("click", function() {this.up(".window_layer").hide();});
    var layerHeaderRightCorner = new Element("div", {"class": "right"}).setStyle({"width": "16px", "left": (width - 16).toString() + "px"});
    
    layerHeader.appendChild(layerHeaderLeftCorner);
    layerHeader.appendChild(layerHeaderHeadline);
    layerHeader.appendChild(layerHeaderClose);
    layerHeader.appendChild(layerHeaderRightCorner);
    
    var layerContent = new Element("div", {"class": "content"}).setStyle({"width": (width - 2).toString() + "px"});
    
    var layerContentBlock = new Element("div", {"class": "contentblock"});
    
    layerContent.appendChild(layerContentBlock);
    
    var layerFooter = new Element("div", {"class": "footer"});
    
    var layerFooterLeftCorner = new Element("div", {"class": "left"}).setStyle({"width": "16px"});
    var layerFooterHeadline = new Element("div", {"class": "headline"}).setStyle({"width": (width - 32).toString() + "px", "left": "16px"});
    var layerFooterRightCorner = new Element("div", {"class": "right"}).setStyle({"width": "16px", "left": (width - 16).toString() + "px"});
    
    layerFooter.appendChild(layerFooterLeftCorner);
    layerFooter.appendChild(layerFooterHeadline);
    layerFooter.appendChild(layerFooterRightCorner);
    
    xhtmlInnerHtml(layerHeaderHeadline, "Loading...");
    xhtmlInnerHtml(layerContentBlock, "<p class='loading'><img src='image/page/loading.gif' alt='loading' /><" + "/p>");
    
    layer.appendChild(layerHeader);
    layer.appendChild(layerContent);
    layer.appendChild(layerFooter);
    
    new Draggable(layer, {handle: layerHeader});
    
    document.body.insertBefore(layer, $("holder"));

    new Ajax.Request(
        window.location.protocol + "//" + window.location.hostname + window.location.pathname,
        {
            method: "get",
            parameters: ajax_params,
            evalJSON: true,
            onSuccess: function(transport) {
                if (!transport.responseJSON) {
                    this.remove();
                    return;
                }
                xhtmlInnerHtml(this.down(".headline"), transport.responseJSON.headline ? transport.responseJSON.headline : "");
                xhtmlInnerHtml(this.down(".contentblock"), transport.responseJSON.content ? transport.responseJSON.content : "");
                xhtmlInnerHtml(this.down(".footer .headline"), "<br />");
                xhtmlInnerHtml(this.down(".footer .headline"), "");
                nulAjaxSuccess(transport);
            }.bind(layer),
            onFailure: function(transport) {
                this.remove();
                nulAjaxFailure(transport);
            }.bind(layer),
            onException: nulAjaxException
        }
    );
    
    return false;
}
nulViewPageInfo = function (page_id) {
    
    var params = new Hash();
    params.set("get", "pageinfo");
    params.set("id", page_id);
    
    nulAjaxLayer("page_" + page_id, params);
}

/* Ajax Layer */


xhtmlInnerHtml = function(object, html) {
    if (!Prototype.Browser.IE && !Prototype.Browser.Opera) {
        var parser = new DOMParser();
    	var doc = parser.parseFromString('<div xmlns="http://www.w3.org/1999/xhtml">' + html.replace(/&nbsp;/g, "&#160;").replace(/&rsaquo;/g, "&#8250;") + '<\/div>', 'application/xhtml+xml');
    	var root = doc.documentElement;
        object.innerHTML = "";
    	for (var i = 0; i < root.childNodes.length; ++ i) {
    		object.appendChild(document.importNode(root.childNodes[i], true));
    	}
    } else {
        object.innerHTML = html;
    }
}

// Hilfe popup
function nulHelpWindow(href) {
    var x = window.open(href + "&p=1", "netupdater_help", "width=750,height=600,left=100,top=60,resizable=1,scrollbars=1,menubar=0");
    return false;
}

// Error popup
function nul_show_error_popup() {
    if (typeof nul_show_error != "string") {
        return;
    }
    if (!nul_show_error) {
        return;
    }
    if (nul_show_error.match(/^-\![\w\d]+\!-$/)) {
        return;
    }
    alert(nul_show_error);
}

// Debug
var nul_debugRowSwitch = false;
function nulAjaxSuccess(req) {
    if (nul_debug) {
        nulSetDebugMessage('Success: ' + req.status + ' ' + req.statusText + '<br />' + req.getAllResponseHeaders());
    }
}
function nulAjaxFailure(req) {
    if (nul_debug) {
        nulSetDebugMessage('Failure: ' + req.status + ' ' + req.statusText + '<br />' + req.getAllResponseHeaders());
    }
}
function nulAjaxException(ajaxReq, exc) {
    if (nul_debug) {
        var ex = $H(exc);
        nulSetDebugMessage('Exception: ' + ex.inspect().escapeHTML());
    }
}
function nulSetDebugMessage(message) {
    if (!nul_debug) {
        return;
    }
    $('ajaxrequestdebug').style.display = 'block';
    newTr = document.createElement("tr");
    if (nul_debugRowSwitch == false) {
        newTr.style.background = "#eeeeee";
        nul_debugRowSwitch = true;
    } else {
        newTr.style.background = "#fafafa";
        nul_debugRowSwitch = false;
    }
    newTd1 = document.createElement("td");
    newTd1.style.verticalAlign = "top";
    newTd1.style.width = "160px";
    newTd1.innerHTML = new Date().toLocaleString();
    newTr.appendChild(newTd1);
    newTd2 = document.createElement("td");
    newTd2.innerHTML = message;
    newTr.appendChild(newTd2);
    $('ajaxrequestdebugtable').appendChild(newTr);
}
// Debug End
