var filesystem = false; // are we in filesystem management?
var static;
window.addEvent('domready', function() {
    $$('img').each(function(img) {
        if(!img.getParent('.bodycontent_container')) {
            if(img.src.indexOf('/static/') > -1) {
                static = img.src.split('/static/')[0] + '/static';
            }
            if(img.src.indexOf('/sys_static/') > -1) {
                static = img.src.split('/sys_static/')[0] + '/sys_static';
            }
        }
    });
    var first_column = $$('.folder_view > tbody > tr');
    if(first_column) {
        first_column.each(function(el, i) {
            if(!el.hasClass('row_panel')) {
                el.addEvent('mouseenter', function() {
                    if(mousedown == false) {
                        movePanel(this);
                        el.addClass('hover');
                    }
                });

                el.addEvent('mouseleave', function() {
                    el.removeClass('hover');
                });
            }
        });

        initClickableRows();
        initPanel();
        initThumbnails();
        initDragDrop();
        initDynamicFields();
        initRenamingSystem();
        initFormSubmitCheck();
    }

    // update filesystem variable
    filesystem = $$('.filesystem').length;

    // label hack - if they wrap, they wrap nicely now
    if($$('fieldset label, .dynamic_fields label')) {
        $$('fieldset label, .dynamic_fields label').each(function(el) {
            var div = new Element('div');
            div.addClass('clear');
            div.inject(el, 'bottom');
        });
    }

    // inactive objects
    if($$('tr.inactive')) {
        $$('tr.inactive img').setStyles({
            opacity: 0.2
        });
    }

    var cms_title = $('cms_title');
    if (cms_title && cms_title.hasClass('list_tickets')) {
        var ticket_request = new XMLHttpRequest();
        ticket_request.open('GET', 'http://intranet.atikon.at/intranet/recent_tickets/14', true);
        ticket_request.onreadystatechange = function () {
            if (ticket_request.readyState == 4 && ticket_request.status == 200)
                cms_title.innerHTML += ticket_request.responseText;
        };
        ticket_request.send();
    }

    // quick breadcrumb fix
    if($('breadcrumb_path')) {
        var crumbs = $$('#breadcrumb_path a').length;
        var bread_width = 0;
        $$('#breadcrumb_path a').each(function(el, i) {
            // if there are too many breadcrumbs, cut out the middle parts
            if(crumbs >= 7) {
                if(i == 0) {
                    el.getNext().innerHTML += ' ... ' + el.getNext().innerHTML; // add some spacing
                }
                if(i > 0 && i < crumbs - 3) {
                    el.getNext().dispose(); // remove span
                    el.dispose();
                }
            }
            bread_width += el.getWidth();
        });
        $$('#breadcrumb_path a').each(function(el, i) {
            if(el.innerHTML.length > 20 && bread_width > document.body.offsetWidth - 250) {
                el.title = el.innerHTML.split('&amp;').join('&');
                el.innerHTML = el.innerHTML.substr(0, 20) + ' ...';
            }
        });
    }

    // quick folder names fix
    if($$('.folder_view .manage_link').length) {
        var maxSize = 30;
        if($$('.manageproperties').length > 0) maxSize = 20;
        $$('.folder_view .manage_link span').each(function(el, i) {
            if(el.innerHTML.length > maxSize) {
                el.title = el.innerHTML.split('&amp;').join('&');
                el.innerHTML = el.innerHTML.substr(0, maxSize) + ' ...';
            }
        });

        // hide panel when outside
        $$('table.folder_view')[0].getParent().addEvent('mouseleave', function() {
            hidePanel();
        });
    }

    // file system filename fix for bodyContentZMSCustom_ files
    if(filesystem) {
        $$('span.filename').each(function(el, i) {
            if(el.innerHTML.indexOf('bodyContentZMSCustom_') > -1) {
                el.title = el.innerHTML;
                el.innerHTML = '... ' + el.innerHTML.substr(21);
            }
        });
    }

    // quick fix for double scrollbars in templates
    if($$('.file_editor').length) {
        $(document.body).style.paddingTop = '0';
        $(document.body).style.paddingBottom = '0';
    }

    // adjust all firstcolumns in manageproperties (container objects list of sub-objects)
    if($$('.manageproperties').length > 0) {
        // figure out which one's the widest column
        var widestwidth = 0;
        $$('.firstcol').each(function(col) {
            widestwidth = col.getWidth() > widestwidth ? col.getWidth() : widestwidth;
        });
        // set all to widest width
        $$('.firstcol').each(function(col) {
            col.setStyle('width', widestwidth + 'px');
        });
    }

    // quick navigation fix for ... Eigenwartungen
    if($$('.manage_page_menu').length) {
        $$('.manage_page_menu a').each(function(el) {
            if(el.innerHTML.length > 20 && !el.getParent('.cms_actions')) {
                el.title = el.innerHTML;
                el.innerHTML = el.innerHTML.substr(0, 20) + ' ...';
            }
        });
        $$('.manage_page_menu').setStyles({ display: 'block' });
        // Eigenwartung mit user als normaler ZMSAuthor hat contentnode klassen im menü
        if($$('.contentnode').length) {
            if($$('.manage_page_menu')[0].getWidth() + 180 > $(document.body).getWidth()) {
                // truncate nodes and display a nice menu instead
                var li = new Element('li');
                li.innerHTML = '<a href="#">Inhalte</a>';
                li.getElement('a').addEvent('click', function(e) {
                    var event = new Event(e).stop();

                    // display contentnodes
                    var contentnav = $('contentnav');
                    if(!contentnav) {
                        contentnav = new Element('div');
                        contentnav.inject($(document.body), 'bottom');
                        contentnav.id = 'contentnav';
                        contentnav.innerHTML = '<ul></ul>';
                        $$('.manage_page_menu .contentnode').inject(contentnav.getElement('ul'), 'top');
                        contentnav.setStyles({
                            top: ($$('.manage_page_menu')[0].getTop() + $$('.manage_page_menu')[0].getHeight()) + 'px',
                            left: ($$('.manage_page_menu')[0].getLeft() + 2) + 'px'
                        });
                    }
                    if(contentnav.style.display == 'block') {
                        contentnav.style.display = 'none';
                    }
                    else {
                        contentnav.style.display = 'block';
                    }
                    $$('li.contentnode').setStyles({
                        display: 'block'
                    });
                });
                li.inject($$('.manage_page_menu')[0], 'top');
                $$('li.contentnode').setStyles({
                    display: 'none'
                });
            }
        }
    }

    if (navigator.appVersion.indexOf("MSIE") > -1) {
        // IE needs a fix for columns for some reason...
        $$('.propertiescol').each(function(el, i) {
            if(el.getElement('a')) {
                el.getNext().style.width = (el.getNext().getWidth() + el.getWidth() - 32) + 'px';
            }
        });
    }

    // expand bodycontent divs
    initBodyContentExpanders();

    // meta object usage
    if($('more_usage')) {
        $('more_usage').addEvent('click', function(e) {
            var event = new Event(e).stop();
            var myHTMLRequest = new Request.HTML({
                onComplete: function(tree, eles, html, js) {
                    this.loader.removeClass('loading');
                    if(fetchLoginScreen(html))
                        return;
                    var found_link = 0;
                    eles.each(function(el) {
                        if(el.id == 'meta_object_usage_table') {
                            //el.id = '';
                            //el.inject($('meta_object_usage').getLast('table'), 'after');
                            el.getElements('tr').each(function(row_el) {
                                if(row_el.getParent().get('tag') != 'thead') {
                                    row_el.inject($('meta_object_usage_table').getElement('tbody'));
                                }
                            });
                        }
                        if(el.id == 'more_usage') {
                            el.id = '';
                            $('more_usage').href = el.href;
                            found_link = 1;
                        }
                    });
                    if(found_link == 0) {
                        $('more_usage').dispose();
                    }
                }
            }).get(this.href);
            this.addClass('loading');
            myHTMLRequest.loader = this;
        });
    }

    // meta objects ajax deletion
    if($$('a.delete_metaobject, a.delete_package').length) {
        $$('a.delete_metaobject, a.delete_package').each(function(a) {
            a.addEvent('click', function(e) {
                if( (this.hasClass('delete_package') && confirm("Soll dieses Paket und alle enthaltenen Objekte wirklich gelöscht werden?"))
                    || this.hasClass('delete_metaobject') ) {
                    var event = new Event(e).stop();
                    var request = new Request.HTML({
                        onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                            var clicker = $(this.clicker);
                            clicker.removeClass('loading');
                            clicker.getElement('img').removeClass('hidden');

                            if(fetchLoginScreen(responseHTML))
                                return;

                            responseElements.each(function(el) {
                                if(el.hasClass('message')) {
                                    el.inject($$('table.spec_obj_overview')[0], 'before');
                                    el.setStyles({
                                        position: 'absolute'
                                    });
                                    el.setStyles({
                                        top: clicker.getParent('tr').getTop() + 'px',
                                        left: (clicker.getLeft() + clicker.getWidth() + 25) + 'px',
                                        margin: 0,
                                        cursor: 'pointer'
                                    });
                                    el.addEvent('click', function() {
                                        this.dispose();
                                    });
                                }
                            });

                            if($$('p.message').length) {
                                return;
                            }
                            else {
                                if(clicker.hasClass('delete_package')) {
                                    var tr = clicker.getParent('tr');
                                    var next_tr = tr.getNext();
                                    while(next_tr && next_tr.getElement('span.package')) {
                                        var to_delete = next_tr;
                                        next_tr = next_tr.getNext();
                                        to_delete.dispose();
                                    }
                                }
                                clicker.getParent('tr').dispose();
                            }
                        }
                    }).get(this.href);
                    request.clicker = this;
                    this.addClass('loading');
                    this.getElement('img').addClass('hidden');
                    $$('p.message').dispose();
                }
            });
        });
    }

    // general ajax deletion
    $$('a.cms_delete_dict_entry, a.cms_delete_user_node').each(function(a) {
        a.addEvent('click', function(e) {
            var event = new Event(e).stop();
            var request = new Request.HTML({
                onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                    var clicker = $(this.clicker);
                    clicker.removeClass('loading');
                    clicker.getElement('img').removeClass('hidden');

                    if(fetchLoginScreen(responseHTML))
                        return;

                    clicker.getParent('tr').dispose();
                }
            }).get(this.href);
            request.clicker = this;
            this.addClass('loading');
            this.getElement('img').addClass('hidden');
        });
    });

    // cropping images
    $$('.image_crop').each(function(el, i) {
        el.addEvent('click', function(e) {
            var event = new Event(e).stop();

            var imagelink = this.getPrevious('.thumbnail_link');
            var imageinput = findParentLabel(this).getElement('input[type=file]');
            if(imagelink && imageinput) {
                removeImageManipulator();
                var cropdiv = $('cropdiv');
                if(!cropdiv) {
                    cropdiv = new Element('div');
                    cropdiv.id = 'cropdiv';
                }
                cropdiv.innerHTML = '<div class="manip_description">Bitte wählen Sie den gewünschten Bereich aus und drücken Sie anschließend auf übernehmen.</div><img id="to_crop" src="' + imagelink.href + '?' + Math.random() + '" alt="" /><div><a href="#" class="save_manipulation">Übernehmen</a> <a href="#" class="cancel_manipulation">Abbrechen</a></div><div class="clear"></div>';
                cropdiv.inject(findParentLabel(imagelink), 'after');
                cropdiv.getElement('.cancel_manipulation').addEvent('click', function(e) {
                    var event = new Event(e).stop();
                    removeImageManipulator();
                });
                cropdiv.imgmaniptoolbar = new Element('div').inject(cropdiv.getElement('.save_manipulation'), 'before').addClass('imgmaniptoolbar');
                cropdiv.imgmaniptoolbar.innerHTML = '<span>X: </span><span id="update_x"></span><span>Y: </span><span id="update_y"></span>' +
                                                    '<span>Breite: </span><span id="update_width"></span><span>Höhe: </span><span id="update_height"></span><div class="clear"></div>';
                cropdiv.getElement('.save_manipulation').addEvent('click', function(e) {
                    var event = new Event(e).stop();
                    if(!this.hasClass('loading')) {
                        this.addClass('loading');
                        var form = this.getParent('form');
                        // don't let resize values get in our way
                        $('cropdiv').croppingFor.getElement('.resize_width').value = '';
                        $('cropdiv').croppingFor.getElement('.resize_height').value = '';
                        var url = document.location.href.split('?')[0];
                        url += '?save_and_back_to_properties=1';
                        var myHTMLRequest = new Request.HTML({
                            url: url,
                            onComplete: function(tree, eles, html, js) {
                                this.clicker.removeClass('loading');
                                if(fetchLoginScreen(html))
                                    return;
                                removeImageManipulator();
                                var img = this.manipulatingImage.getElement('img.thumbnail');
                                img.style.background = 'url(' + img.style.backgroundImage.split('url(').join('').split(')').join('').split('"').join('') + '?' + Math.random() + ')  #eee center center no-repeat';
                            }
                        }).post(form);
                        myHTMLRequest.manipulatingImage = $('cropdiv').croppingFor;
                        myHTMLRequest.clicker = this;
                    }
                });

                cropdiv.croppingFor = findParentLabel(imagelink);
                $('to_crop').addEvent('load', function() {
                    $('cropdiv').cropper = new Lasso.Crop('to_crop',{
                            //ratio: '1,1',
                            preset: [0, 0, this.getWidth(), this.getHeight()],
                            //preset: [(this.getWidth()/2)-(this.getWidth()/3), (this.getHeight()/2)-(this.getHeight()/3), (this.getWidth()/2)+(this.getWidth()/3), (this.getHeight()/2)+(this.getHeight()/3),],
                            min: [0,0],
                            handleSize: 8,
                            opacity: .6,
                            color: '#7389AE',
                            border: static + '/images/layout/crop_background.gif',
                            onResize: updateCropCoords
                    });
                });
            }
        });
    });

    // resizing images
    $$('.image_resize').each(function(el, i) {
        el.addEvent('click', function(e) {
            var event = new Event(e).stop();

            var imagelink = this.getPrevious('.thumbnail_link');
            var imageinput = findParentLabel(this).getElement('input[type=file]');
            if(imagelink && imageinput) {
                removeImageManipulator();
                var cropdiv = $('cropdiv');
                if(!cropdiv) {
                    cropdiv = new Element('div');
                    cropdiv.id = 'cropdiv';
                }
                cropdiv.innerHTML = '<div class="manip_description">Bitte verändern Sie die Größe des Bildes und drücken Sie anschließend auf übernehmen.</div><img id="to_crop" src="' + imagelink.href + '?' + Math.random() + '" alt="" /><div><a href="#" class="save_manipulation">Übernehmen</a> <a href="#" class="cancel_manipulation">Abbrechen</a></div><div class="clear"></div>';
                cropdiv.inject(findParentLabel(imagelink), 'after');
                cropdiv.getElement('.cancel_manipulation').addEvent('click', function(e) {
                    var event = new Event(e).stop();
                    removeImageManipulator();
                });
                cropdiv.imgmaniptoolbar = new Element('div').inject(cropdiv.getElement('.save_manipulation'), 'before').addClass('imgmaniptoolbar');
                cropdiv.imgmaniptoolbar.innerHTML = '<span>Breite: </span><span id="update_width"></span><span>Höhe: </span><span id="update_height"></span><div class="clear"></div>';
                cropdiv.getElement('.save_manipulation').addEvent('click', function(e) {
                    var event = new Event(e).stop();
                    if(!this.hasClass('loading')) {
                        this.addClass('loading');
                        var form = this.getParent('form');
                        var url = document.location.href.split('?')[0];
                        url += '?save_and_back_to_properties=1';
                        // don't let cropping values get in our way
                        $('cropdiv').croppingFor.getElement('.crop_x').value = '';
                        $('cropdiv').croppingFor.getElement('.crop_y').value = '';
                        $('cropdiv').croppingFor.getElement('.crop_width').value = '';
                        $('cropdiv').croppingFor.getElement('.crop_height').value = '';
                        var myHTMLRequest = new Request.HTML({
                            url: url,
                            onComplete: function(tree, eles, html, js) {
                                this.clicker.removeClass('loading');
                                if(fetchLoginScreen(html))
                                    return;
                                removeImageManipulator();
                                var img = this.manipulatingImage.getElement('img.thumbnail');
                                img.style.background = 'url(' + img.style.backgroundImage.split('url(').join('').split(')').join('').split('"').join('') + '?' + Math.random() + ')  #eee center center no-repeat';
                            }
                        }).post(form);
                        myHTMLRequest.manipulatingImage = $('cropdiv').croppingFor;
                        myHTMLRequest.clicker = this;
                    }
                });

                cropdiv.croppingFor = findParentLabel(imagelink);
                $('to_crop').addEvent('load', function() {
                    if(this.getWidth() > 1000) {
                        this.setStyle('width', 1000);
                    }
                    var resizer = new MooResize('to_crop', {
                        handleSize: 8,
                        maxSize: {
                            x: 1000,
                            y: 1000
                        },
                        handleStyle: {
                            background: '#eee'
                        },
                        onStart: function() {
                            $(this).setStyle('opacity', 0.8);
                        },
                        onComplete: function(size) {
                            $(this).setStyle('opacity', 1);
                            $('cropdiv').croppingFor.getElement('.resize_width').value = $('update_width').innerHTML = size.x;
                            $('cropdiv').croppingFor.getElement('.resize_height').value = $('update_height').innerHTML = size.y;
                        },
                        onResize: function(size) {
                            $('cropdiv').croppingFor.getElement('.resize_width').value = $('update_width').innerHTML = $('to_crop').getWidth();
                            $('cropdiv').croppingFor.getElement('.resize_height').value = $('update_height').innerHTML = $('to_crop').getHeight();
                            if($('cropdiv').croppingFor.getElement('.img_dimensions')) {
                                $('cropdiv').croppingFor.getElement('.img_dimensions').innerHTML = $('to_crop').getWidth() + ' x ' + $('to_crop').getHeight();
                            }
                        }
                    });
                    resizer.setRatio('true');
                    $('update_width').innerHTML = this.getWidth();
                    $('update_height').innerHTML = this.getHeight();
                });
            }
        });
    });

    // restoring images
    $$('.image_restore').each(function(el, i) {
        el.addEvent('click', function(e) {
            var event = new Event(e).stop();

            findParentLabel(this).getElement('input.restore').checked = 'checked';

            removeImageManipulator();
            var form = this.getParent('form');
            var url = document.location.href.split('?')[0];
            url += '?save_and_back_to_properties=1';
            this.addClass('loading');
            var myHTMLRequest = new Request.HTML({
                url: url,
                onComplete: function(tree, eles, html, js) {
                    var img = this.manipulatingImage.getElement('img.thumbnail');
                    img.style.background = 'url(' + img.style.backgroundImage.split('url(').join('').split(')').join('').split('"').join('') + '?' + Math.random() + ')  #eee center center no-repeat';
                    this.link.removeClass('loading');
                    if(fetchLoginScreen(html))
                        return;

                    $$('input.restore').each(function(input) {
                        input.checked = false;
                    });
                }
            }).post(form);
            myHTMLRequest.manipulatingImage = findParentLabel(this);
            myHTMLRequest.link = this;
        });
    });

    // date(time)picker
    var datepick_days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
    var datepick_months = ['Jänner', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
    $$('.cms_datetimepick, .cms_datepick').each(function(input) {
        var button = input.getNext('a.button');
        if(!button)
            return;
        button.addEvent('click', function(e) {
            new Event(e).stop();
        });
        var dateandtime = input.hasClass('cms_datetimepick');
        if(input.value.indexOf(':') == -1 && input.value.indexOf('-') > -1) {
            input.value = input.value + ' 12:00:00';
        }
        new DatePicker(input, {
            days: datepick_days,
            months: datepick_months,
            pickerClass: 'datepicker',
            timePicker: dateandtime,
            format: dateandtime ? 'd.m.Y H:i' : 'd.m.Y',
            inputOutputFormat: 'Y-m-d H:i:s',
            //debug: true,
            allowEmpty: true,
            toggleElements: button
        });
    });

    // timepicker
    $$('input.timepick').each(function(input) {
        var button = input.getNext('a.button');
        if(!button)
            return;

        new DatePicker(input, {
            pickerClass: 'datepicker',
            timePickerOnly: true,
            format: 'H:i',
            inputOutputFormat: 'Y-m-d H:i:s',
            //debug: true,
            allowEmpty: true,
            toggleElements: input.getNext('.button')
        });
    });

    // alternative way to manage multiselects
    $$('.cms_multiselect').each(function(select, i) {
        if(select.options.length == 0) {
            var italic = new Element('i').inject(select, 'after');
            italic.innerHTML = 'Keine Daten zur Auswahl vorhanden.';
            italic.addClass('gray');
            return;
        }

        var ul = new Element('ul').inject(select, 'after');
        ul.addClass('cms_multiselect_helper list');
        for(o=0; o<select.options.length; o++) {
            var li = new Element('li').inject(ul, 'bottom');
            li.innerHTML = '<input type="checkbox" />';
            var input = li.getElement('input');
            input.myoption = select.options[o];
            input.checked = input.myoption.selected;
            input.setProperty('disabled', (select.getProperty('readOnly') ? 'disabled' : false));
            input.original_checked = input.checked;
            var span = new Element('span').inject(li, 'bottom');
            span.innerHTML = input.myoption.innerHTML;
            if(select.getProperty('readOnly'))
                continue;
            input.addEvent('change', function() {
                this.myoption.selected = this.checked;
                if(this.myoption.selected)
                    this.getParent('li').addClass('cms_multiselect_checked');
                else
                    this.getParent('li').removeClass('cms_multiselect_checked');
            });
            input.fireEvent('change');
            input.addEvent('mousedown', function() {
                this.checked = !this.checked;
            });
            li.addEvent('click', function() {
                this.getElement('input').click();
                this.getElement('input').fireEvent('change');
            });
        }

        if(select.getProperty('readOnly'))
            return;

        var myLittlePanel = new Element('div').inject(ul, 'after');
        myLittlePanel.addClass('clear cms_multiselect_panel');

        var selectall = new Element('img').inject(myLittlePanel, 'bottom');
        selectall.myul = ul;
        selectall.src = static + '/images/icons/new/selectall_small.png';
        selectall.title = 'Alles auswählen';
        selectall.addEvent('click', function() {
            this.myul.getElements('input').each(function(checkbox) {
                checkbox.checked = true;
                checkbox.fireEvent('change');
            });
        });

        var selectnone = new Element('img').inject(myLittlePanel, 'bottom');
        selectnone.myul = ul;
        selectnone.src = static + '/images/icons/new/selectnone_small.png';
        selectnone.title = 'Nichts auswählen';
        selectnone.addEvent('click', function() {
            this.myul.getElements('input').each(function(checkbox) {
                checkbox.checked = false;
                checkbox.fireEvent('change');
            });
        });

        var undo = new Element('img').inject(myLittlePanel, 'bottom');
        undo.myul = ul;
        undo.src = static + '/images/icons/new/undo.png';
        undo.title = 'Ursprüngliche Auswahl wiederherstellen';
        undo.addEvent('click', function() {
            this.myul.getElements('input').each(function(checkbox) {
                checkbox.checked = checkbox.original_checked;
                checkbox.fireEvent('change');
            });
        });

        var search = new Element('img').inject(myLittlePanel, 'bottom');
        search.myul = ul;
        search.src = static + '/images/icons/new/search_small.png';
        search.title = 'Suchen';
        search.myinput = new Element('input').inject(search, 'after');
        search.myinput.style.display = 'none';
        search.myinput.myul = ul;
        search.myinput.addEvent("keydown", function(event) {
            if(event.key == "esc") {
                this.value = '';
                this.style.display = 'none';
                this.myul.getElements('li').setStyle('display', 'block');
            }
            if(event.key == "enter") {
                new Event(event).stop();
                return false;
            }
        });
        search.myinput.addEvent("keyup", function(event) {
            var allowedkeys = "abcdefghijklmnopqrstuvwxyz1234567890";
            if(allowedkeys.indexOf(event.key) > -1 || event.key == 'backspace') {
                var inputvalue = this.value;
                var found = 0;
                this.myul.getElements('li').each(function(li, i) {
                    var span = li.getElement('span');
                    if(span.innerHTML.toLowerCase().indexOf(inputvalue.toLowerCase()) > -1) {
                        li.setStyle('display', 'block');
                        found++;
                    }
                    else if(inputvalue.length > 0) {
                        li.setStyle('display', 'none');
                    }
                    else {
                        li.setStyle('display', 'block');
                    }
                });
            }
        });
        search.addEvent('click', function() {
            if(search.myinput.style.display == 'block') {
                search.myinput.value = '';
                search.myinput.style.display = 'none';
                this.myul.getElements('li').setStyle('display', 'block');
            }
            else {
                search.myinput.style.display = 'block';
                search.myinput.focus();
            }
        });
    });

    // sidebar browser
    if($('cms_sidebar_browser')) {
        var sidebar = $('cms_sidebar_browser');
        if(document.location.href.indexOf('#cms_sidebar_browser_popup') > -1) {
            sidebar.addClass('cms_sidebar_browser_popup');
            $$('html, body').setStyle('overflow', 'hidden');
        }
        sidebar.domain = sidebar.title;
        sidebar.rooturl = document.location.href.split($('cms_sidebar_browser').domain)[0] + $('cms_sidebar_browser').domain + '/manage';
        sidebar.contenturl = sidebar.rooturl.split('/manage')[0] + '/content/manage';
        sidebar.getElement('.cms_sidebar_title').innerHTML = sidebar.domain;
        sidebar.content = sidebar.getElement('.cms_sidebar_browser_content');
        sidebar.sidekick = $$('.filesystem, .contentsystem, .file_editor, .file_uploader, .manage_languages, .manage_metaobjects, .metaobject_edit, .manage_authorization')[0];
        sidebar.popout = sidebar.getElement('.cms_sidebar_popout');
        sidebar.popout.addEvent('click', function(e) {
            $('cms_sidebar_browser').mypopup = window.open($('cms_sidebar_browser').contenturl + '#cms_sidebar_browser_popup', 'CMSSidebarPopup', 'width=300,height=400,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no');
        });

        sidebar.init = function() {
            $('cms_sidebar_browser').addClass('browserloading');
            $('cms_sidebar_browser').load($('cms_sidebar_browser').rooturl, $('cms_sidebar_browser').content);
        }
        sidebar.load = function(url, obj) {
            var request = new Request.HTML({
                update: obj,
                onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                    var content = '<ul>';
                    var browser = $('cms_sidebar_browser');
                    browser.removeClass('browserloading');
                    var filenames = this.obj.getElements('span.filename');
                    filenames.each(function(span) {
                        var img = span.getPrevious('img');
                        var a = span.getParent();
                        content += '<li><a href="#" class="' + (img.src.indexOf('folder') > -1 || a.hasClass('expandable') ? 'cms_browse' : 'cms_browse browse_silent') + '"><img src="' + img.src.replace('.png', '_small.png') + '" alt="" /></a> <a class="cms_manage" href="' + a.href + '">' + span.innerHTML + '</a></li>';
                    });
                    content += '</ul>';
                    this.obj.getParent().getElements('.loading').removeClass('loading');
                    var browser_clicker = this.obj.getPrevious('.cms_browse');
                    if(filenames.length) {
                        if(browser_clicker) { // there are children, so we no longer have to be silent about them
                            browser_clicker.removeClass('browse_silent');
                            browser_clicker.addClass('expanded');
                        }
                        this.obj.innerHTML = content;
                    }
                    else {
                        if(browser_clicker) { // there are no children, keep silent
                            browser_clicker.addClass('browse_silent');
                        }
                        this.obj.dispose();
                    }

                    browser.initLinks();
                }
            }).get(url + (url.indexOf('?') > -1 ? '&' : '?') + 'refresh=' + Math.random());
            request.obj = obj;
        }

        sidebar.initLinks = function() {
            $('cms_sidebar_browser').getElements('a.cms_browse').each(function(a, i) {
                a.removeEvents('click').addEvent('click', function(e) {
                    var event = new Event(e).stop();
                    var url = this.getNext('a').href;
                    if(this.getParent().getElement('div')) {
                        this.getParent().getElement('div').dispose();
                        this.removeClass('expanded');
                    }
                    else {
                        var div = new Element('div').inject(this.getParent(), 'bottom');
                        if(url.indexOf('/content') > -1) {
                            if(url.indexOf('/manage?') > -1) {
                                url = url.replace('/manage', '/manage_tree') + '&for_browser=1';
                            }
                            else {
                                url = url.replace('/manage', '/manage_tree?for_browser=1');
                            }
                        }
                        $('cms_sidebar_browser').load(url, div);
                        this.getNext().addClass('loading');
                    }
                });
                a.getParent('ul').getLast('li').addClass('end');
            });

            $('cms_sidebar_browser').getElements('a.cms_manage').each(function(a, i) {
                a.removeEvents('click').addEvent('click', function(e) {
                    if($('cms_sidebar_browser').hasClass('cms_sidebar_browser_popup')) {
                        window.opener.location.href = this.href;
                        var event = new Event(e).stop();
                    }
                });
            });
        }

        if(sidebar.hasClass('cms_sidebar_browser_popup')) {
            if(sidebar.content.getElements('*').length == 0) {
                window.setTimeout("$('cms_sidebar_browser').init()", 300);
            }
            else {
                sidebar.initLinks();
            }
        }

        sidebar.morph = new Fx.Morph(sidebar, {
            duration: 350,
            wait: false,
            onComplete: function() {
            }
        });
        sidebar.sidekickmorph = new Fx.Morph(sidebar.sidekick, {
            duration: 350,
            wait: false,
            onComplete: function() {
            }
        });

        if(!$('cms_sidebar_browser').hasClass('cms_sidebar_browser_popup')) {
            $('cms_sidebar_browser').getElement('.cms_sidebar_stripe').addEvent('click', function(e) {
                hidePanel();
                var browser = $('cms_sidebar_browser');
                if(!browser.hasClass('expanded')) {
                    browser.morph.start({
                        marginLeft: 0
                    });
                    browser.sidekickmorph.start({
                        marginLeft: '285px'
                    });
                    browser.addClass('expanded');

                    if(browser.content.getElements('*').length == 0) {
                        window.setTimeout("$('cms_sidebar_browser').init()", 300);
                    }
                    else {
                        browser.initLinks();
                    }
                }
                else {
                    browser.morph.start({
                        marginLeft: '-285px'
                    });
                    browser.sidekickmorph.start({
                        marginLeft: 0
                    });
                    browser.removeClass('expanded');
                }
            });
        }
    }
    else if($$('.contentsystem').length > 0) {
        $$('.contentsystem')[0].style.paddingLeft = 0;
    }

    // Authorization quicklinks
    $$('.cms_user_delete').each(function(el) {
        el.addEvent('click', function(e) {
            var event = new Event(e).stop();
            if(confirm('Soll dieser Benutzer wirklich gelöscht werden?')) {
                this.addClass('loading');
                var request = new Request.HTML({
                    onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                        this.link.removeClass('loading');
                        if(fetchLoginScreen(responseHTML))
                            return;

                        this.link.getParent('.cms_user').dispose();
                    }
                }).get(this.href);
                request.link = this;
            }
        });
    });
    $$('.cms_user').each(function(el) {
        el.addEvent('click', function(e) {
            document.location.href = this.getElement('.cms_edit_user').href;
        });
    });

    // Atikon Logo
    if($('atikon_logo') && $$('.contentsystem').length) {
        $('atikon_logo').style.bottom = '52px';
    }

    // Generation Status
    generationStatus();

    initTableEditor();
    initTableHover();
    initPasteButton();
    initAJAXTextEditor();
});

function initBodyContentExpanders(expander) {
    if($$('.expander')) {
        var expanders = new Array();
        if(expander) {
            expanders.push(expander); // we're given an expander link, so we only want to check this one bodycontent
        }
        else {
            expanders = $$('.expander'); // otherwise - just check 'em all
        }
        expanders.each(function(a) {
            // see if the size actually matters
            var bodycontentcontainer = a.getParent('.secondcol').getElement('.bodycontent_container');
            bodycontentcontainer.setStyles({
                height: 'auto'
            });
            var realsize = bodycontentcontainer.getHeight();
            bodycontentcontainer.setStyles({
                height: '34px'
            });
            if(realsize <= 34) {
                a.style.display = 'none';
            }
            else {
                a.style.display = 'block';
                a.removeEvents('click').addEvent('click', function(e) {
                    new Event(e).stop();
                    this.getParent('.secondcol').fireEvent('dblclick');
                });
            }
            // check for images and check this object again when images are loaded
            if(!expander) {
                bodycontentcontainer.getElements('img').each(function(img) {
                    img.addEvent('load', function() {
                        initBodyContentExpanders(this.getParent('.secondcol').getElement('a.expander'));
                    });
                });
            }
            // auto expand notes
            if(bodycontentcontainer.getElement('.cms_note')) {
                bodycontentcontainer.setStyles({
                    height: 'auto'
                });
                bodycontentcontainer.getParent('.bodycontent').expanded = 1;
                bodycontentcontainer.getParent('td').addClass('expanded');
            }
        });
    }
}

/* Generation Status */
function generationStatus() {
    if($$('.generation_status').length) {
        var action_link;
        $$('.cms_actions a').each(function(a) {
            if(a.href.indexOf('?action=generate') > -1) {
                action_link = a;
            }
        });

        if(!action_link)
            return false;

        var request = new Request.HTML({
            onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                if(fetchLoginScreen(responseHTML)) {
                    window.setTimeout('generationStatus()', 5000);
                    return;
                }

                var queues = new Array();
                responseElements.each(function(el) {
                    if(el.hasClass('generation_overview')) {
                        queues.push(el);
                    }
                });
                if(queues.length > 0) {
                    var first_overview = $$('.contentsystem .generation_overview')[0];
                    queues.each(function(queue) {
                        queue.inject(first_overview, 'before');
                    });
                    first_overview.getAllNext('.generation_overview').dispose();
                    first_overview.dispose();

                    $$('.generation_status_expander').each(function(a) {
                        a.addEvent('click', function() {
                            if($$('.contentsystem')[0].hasClass('expand_generation_status')) {
                                $$('.contentsystem').removeClass('expand_generation_status');
                            }
                            else {
                                $$('.contentsystem').addClass('expand_generation_status');
                            }
                            hidePanel();
                        });
                    });

                    window.setTimeout('generationStatus()', 2000);

                    if(queues.length > 1) {
                        queues.each(function(queue, i) {
                            if(i > 0) {
                                queue.style.display = 'none';
                            }
                        });
                        var message = new Element('div');
                        message.addClass('more_queued');
                        message.inject(queues[0], 'bottom');
                        message.innerHTML = (queues.length - 1) + ' weitere Generierung' + (queues.length == 2 ? '' : 'en');
                    }
                }
                else {
                    $$('.generation_status_text span')[0].innerHTML = 'Generierung abgeschlossen!';
                    $$('.generation_status_percent')[0].innerHTML = '100%';
                    $$('.generation_status_bar')[0].style.width = '100%';
                    if($$('.generation_overview').getNext('.generation_overview')) {
                        $$('.generation_overview').getAllNext('.generation_overview').dispose();
                    }
                }
            }
        }).get(action_link.href);
    }
}

/* Image Cropping Update Function */
function updateCropCoords(pos) {
    if($('cropdiv')) {
        $('cropdiv').croppingFor.getElement('.crop_x').value = $('update_x').innerHTML = pos.x;
        $('cropdiv').croppingFor.getElement('.crop_y').value = $('update_y').innerHTML = pos.y;
        $('cropdiv').croppingFor.getElement('.crop_width').value = $('update_width').innerHTML = pos.w;
        $('cropdiv').croppingFor.getElement('.crop_height').value = $('update_height').innerHTML = pos.h;
        if($('cropdiv').croppingFor.getElement('.img_dimensions')) {
            $('cropdiv').croppingFor.getElement('.img_dimensions').innerHTML = pos.w + ' x ' + pos.h;
        }
    }
}
/* Image Cropping/Resizing Disposal Function */
function removeImageManipulator() {
   if($('cropdiv')) {
        $('cropdiv').croppingFor.getElement('.resize_width').value = '';
        $('cropdiv').croppingFor.getElement('.resize_height').value = '';
        $('cropdiv').croppingFor.getElement('.crop_x').value = '';
        $('cropdiv').croppingFor.getElement('.crop_y').value = '';
        $('cropdiv').croppingFor.getElement('.crop_width').value = '';
        $('cropdiv').croppingFor.getElement('.crop_height').value = '';
        $('cropdiv').dispose();
    }
}
/* Image Label Parent Finder */
function findParentLabel(obj) {
    return obj.getParent('label') ? obj.getParent('label') : obj.getParent('div.label');
}

/* New Simple Drag & Drop */
window.addEvent('keydown', function(event){
    var event = new Event(event);
    if (event.key == 'esc') {
        // cancel dragging on ESC
        mousedown = false;
        $$('tr').setStyles({
            opacity: 1
        });
        $$(',to_move').removeClass('to_move');
        $$('.moveto_hover').removeClass('moveto_hover');
        $$('.mousedown').removeClass('mousedown');
    }
});

function initDragDrop() {
    // new simple drag & drop
    $(document).addEvent('selectstart', function() {
        if(mousedown == true) {
            return false;
        }
    });
    $$('.folder_view .secondcol').addEvent('mousedown', function() {
        if(!this.hasClass('expanded')) {
            this.addClass('mousedown');
            mousedown = true;
            return false;
        }
    });
    $$('.folder_view .secondcol, .row_top .rightcol, .folder_view .firstcol').addEvent('mouseenter', function() {
        if(mousedown == true) {
            if(this.getParent().hasClass('row_top')) {
                return;
            }
            var last_moveto_hover = $$('.moveto_hover')[0];
            $$('.moveto_hover').removeClass('moveto_hover');
            $$('.moveintofolder_hover').removeClass('moveintofolder_hover');
            var moveto_hover = this.getParent();
            while(moveto_hover.hasClass('.checked') || moveto_hover.getElement('.mousedown') || moveto_hover.hasClass('to_move')) {
                if(moveto_hover.getPrevious()) {
                    moveto_hover = moveto_hover.getPrevious();
                }
                else {
                    break;
                }
            }
            moveto_hover.addClass('moveto_hover');

            if(this.hasClass('firstcol') && !this.getParent('.attr_object')) {
                var folder_link = this.getElement('a.manage_type_zms_folder span');
                if(folder_link) {
                    var info = $('cms_move_info');
                    if(!info) {
                        info = new Element('div');
                        info.id = 'cms_move_info';
                    }
                    info.inject(this, 'top');
                    info.setStyle('display', 'block');
                    info.innerHTML = "<div>In den Ordner " + folder_link.innerHTML + " verschieben</div>";
                    this.addClass('moveintofolder_hover');
                    return;
                }
            }
            $$('#cms_move_info').setStyle('display', 'none');

            var movetarget = $$('.moveto_hover')[0];
            if(movetarget) {
                var toMove = $$('.checked');
                if(toMove.length == 0) {
                    toMove = $$('.mousedown').getParent('tr');
                }
                toMove.each(function(moveEl, i) {
                    moveEl.setStyles({
                        opacity: 0.3
                    });
                    moveEl.addClass('to_move');
                });

                // figure out index of objects
                var myindex = 0;
                var myprevious = toMove[0].getPrevious();
                while(myprevious) {
                        myprevious = myprevious.getPrevious();
                        myindex++;
                        if(myindex > 500)
                                break;
                }
                var targetindex = 0;
                var targetprevious = movetarget.getPrevious();
                while(targetprevious) {
                        targetprevious = targetprevious.getPrevious();
                        targetindex++;
                        if(targetindex > 20)
                                break;
                }
                if(!this.getParent().hasClass('to_move')) {
                    // this is some magic to make the moving item appear always where the mouse cursor is
                    if(targetindex > myindex) {
                            var prev; // inject seems to inject the list node for node so the list would get reversed
                            toMove.each(function(element) {
                                    element.inject(prev ? prev : movetarget, 'after');
                                    prev = element;
                            });
                    }
                    else if(targetindex < myindex) {
                            toMove.each(function(element) {
                                element.inject(movetarget, 'before');
                            });
                    }
                }
            }
        }
    });
    $$('.folder_view .secondcol, .row_top .rightcol, body').addEvent('mouseup', function() {
        mousedown = false;

        var toMoveIDs = "";
        var toMove = $$('.checked');
        if(toMove.length == 0) {
            toMove = $$('.mousedown').getParent('tr');
        }
        toMove.each(function(moveEl, i) {
            var ID     = moveEl.id.split('row_').join('');
            var prefix = ($('prefix_' + ID)) ? $('prefix_' + ID).value : '';

            toMoveIDs += ";id=" + ID;
            if (prefix)
                toMoveIDs += ";prefix=" + prefix
        });

        var targetCutEl = $$('.moveintofolder_hover')[0]; // move stuff into folders
        if(targetCutEl) {
            //manage_paste?origin=/kittl-deggendorf.de/content;id=2288;after=2288;prefix=
            var link = targetCutEl.getElement('a.manage_link');
            var origin = document.location.href.split('/manage');
            origin = origin[0].split('/content');
            origin = '/content' + origin[1];
            moveURL = link.href.split('/manage')[0] + '/manage_paste?del_orig=1;origin=/' + getDomain() + origin + toMoveIDs;
            link.addClass('loading');
            var request = new Request.HTML({
                onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                    if(fetchLoginScreen(responseHTML)) {
                        return;
                    }
                    this.link.removeClass('loading');
                    showButtonResponse(this.link);
                }
            }).get(moveURL);
            toMove.dispose();
            request.link = link;
        }
        else {
            var moveURL = "manage_move_children_after?" + toMoveIDs;
            var targetEl = $$('.moveto_hover')[0];
            if(targetEl) {
                if(targetEl.hasClass('row_top') || !toMove[0].getPrevious()) {
                    //no 'after' means we're injecting objects on top
                }
                else if(targetEl.id.indexOf('row') > -1) {
                    moveURL += ";after=" + targetEl.id.replace('row_', '');
                }

                //alert(moveURL);
                document.location.href = moveURL;
            }
        }

        $$('#cms_move_info').setStyle('display', 'none');
        $$('.moveintofolder_hover').removeClass('moveintofolder_hover');
        $$('.moveto_hover').removeClass('moveto_hover');
        $$('.mousedown').removeClass('mousedown');
    });
}

// Metaobject Edit Link
function showMetaobjectProperties() {
    var link = $$('tr.haspanel .firstcol a.manage_link, tr.haspanel .leftcol a')[0];
    if(link) {
        var classes = link.className.split(' ');
        var type;
        for(i=0; i<classes.length; i++) {
            if(classes[i].indexOf('manage_type') > -1) {
                type = classes[i].split('manage_type_')[1];
            }
            if(classes[i].indexOf('top_') > -1) {
                type = classes[i].split('top_')[1];
            }
        }
        if(type && $$('.manage_page_menu .metaobjects a').length > 0) {
            $$('.panel .edit_metaobject').setProperty('href', $$('.manage_page_menu .metaobjects a')[0].href + '/' + type);
        }
        return false;
    }
}

/* Clickable Rows */
var clickTimer;
var mousedown = false;
function initClickableRows() {
    // bodycontent clicks and panel tricks
    $$('.secondcol').each(function(td, i) {
        if(td) {
            td.morph = new Fx.Morph(td.getElement('.bodycontent_container'), {
                duration: 500,
                wait: false,
                onComplete: function() {
                    movePanel();
                }
            });

            td.addEvents({
                'click': function(){
                    $clear(clickTimer);
                    clickTimer = (function(){
                        checkBox(this.parentNode);
                    }).delay(10, this);
                },
                'dblclick': function(e) {
                    $clear(clickTimer);
                    if(this.hasClass('bodycontent')) {
                        // expand bodycontent
                        if(this.expanded) {
                            var realsize = this.getElement('.bodycontent_container').getHeight();
                            this.morph.pause().start({
                                height: [realsize, '34px']
                            });
                            this.expanded = 0;
                            this.removeClass('expanded');
                        }
                        else {
                            this.getElement('.bodycontent_container').setStyles({
                                height: 'auto'
                            });
                            var realsize = this.getElement('.bodycontent_container').getHeight();
                            this.getElement('.bodycontent_container').setStyles({
                                height: '34px'
                            });

                            this.morph.pause().start({
                                height: realsize + 'px'
                            });
                            this.expanded = 1;
                            this.addClass('expanded');

                            hidePanel();
                        }
                        checkBox(this.parentNode, 'off');
                    }

                    // clear selection
                    if ( Browser.opera ) window.getSelection().collapse( mouseEvent.target, 0 );
                    else if ( window.document.selection && window.document.selection.empty ) window.document.selection.empty();
                    else if ( window.getSelection ) window.getSelection().removeAllRanges();
                }
            });

            var selectbox = $(td.parentNode).getElement('.selectionbox');
            if(selectbox) {
                if(selectbox.checked) {
                    checkBox(td.parentNode, 'on');
                }

                selectbox.addEvent('change', function() {
                    if(this.checked) {
                        checkBox(this.parentNode.parentNode, 'on');
                    }
                    else {
                        checkBox(this.parentNode.parentNode, 'off');
                    }
                });
            }
        }
    });
}

/* Nine Inch Thumbnails */
function initThumbnails() {
    var thumbs = $$('.thumbnail');
    thumbs.each(function(el, i) {
        if(el.getWidth() > 100) {
            el.setStyle('width', 100);
        }
    });
    var thumblinks = $$('.thumbnail_link');
    thumblinks.each(function(el, i) {
        el.addEvent('click', function(e) {
            var event = new Event(e).stop();
            showHTMLPopup('<div style="overflow: hidden"><img src="' + this.href + '?' + Math.random() + '" alt="" /></div>');
        });
    });
}

/* Dynamic Fields */
function initDynamicFields() {
    var trs = $$('table.oddevenrows tr');
    trs.each(function(el, i) {
        if(i%2 == 0) {
            el.addClass('odd');
        }
        else {
            el.addClass('even');
        }
    });
}

/* Renaming function of File System Management */
function initRenamingSystem() {
    if($$('.renamecol').length > 0) {
        $$('.renamecol a').each(function(link, i) {
            link.addEvent('click', function(e) {
                var event = new Event(e);
                event.stop();

                $$('.file_system_browser tr.hover').each(function(tr, b) {
                    var a = tr.getElement('.renamecol a');
                    var renamer = $('renamer');
                    renamer.setStyles({
                        top: a.getTop()-7,
                        left: a.getLeft()+a.getWidth(),
                        display: 'block'
                    });
                    if(tr.getElement('.filename').innerHTML.indexOf('...') == 0)
                        tr.getElement('.filename').innerHTML = tr.getElement('.filename').title;
                    $('renamer_filename').value = $('renamer_oldfilename').value = tr.getElement('.filename').innerHTML;
                    $('renamer_response').innerHTML = '';
                    $('renamer_filename').focus();
                    $('renamer_filename').setStyle('width', tr.getElement('.filename').getWidth()+10);
                });
            });
        });

        $('renamer').getElement('form').addEvent('submit', function(e) {
            new Event(e).stop();
            this.action = this.action + '?' + Math.random();
            var myHTMLRequest = new Request.HTML({
                url: this.action,
                onComplete: function(tree, eles, html, js) {
                    if(fetchLoginScreen(html)) {
                        $('renamer_response').innerHTML = '';
                        return;
                    }
                    if(html.indexOf('Success!') > -1) {
                        $('renamer').setStyle('display', 'none');

                        var oldname = $('renamer_oldfilename').value;
                        var newname = $('renamer_filename').value;
                        $$('.filename').each(function(span, i) {
                            if(span.innerHTML == oldname) {
                                span.innerHTML = newname;
                                // set new name within link so the user can click on it and not /manage the old filename
                                var parentlink = span.getParent();
                                var splitlink = parentlink.href.split('/');
                                splitlink[splitlink.length-2] = newname;
                                parentlink.href = splitlink.join('/');
                            }
                        });
                    }
                    $('renamer_response').innerHTML = '<p>' + html + '</p>';
                }
            }).post(this);
            $('renamer_response').innerHTML = "<br/>Saving ...";
        });
        $('renamer_filename').addEvent("keydown", function(event) {
            if(event.key == "esc") {
                fs_rename_close();
            }
        });
    }
}

/* Form Submit Checks */
function initFormSubmitCheck() {
    try {
        $$('form.submitcheck').each(function(form, i) {
            form.addEvent('submit', function(e) {
                var valid = true;
                var error_msg = new Array();
                this.getElements('.invalid').removeClass('invalid');
                this.getElements('.required').each(function(input, i) {
                    if(input.get('tag') == 'select') {
                        if(!input.getSelected() || input.value == "") {
                            valid = false;
                            error_msg.push("Für <b>" + input.title + "</b> muss eine Auswahl getroffen werden!");
                            if(input.getStyle('display') == 'none') { // multiselect, add class to next element (ul)
                                input.getNext().addClass('invalid');
                            }
                            else {
                                input.addClass('invalid');
                            }
                        }
                    }
                    else {
                        if(input.value == "" && input.style.display != 'none') {
                            valid = false;
                            error_msg.push("<b>" + input.title + "</b> darf nicht leer sein!");
                            input.addClass('invalid');
                        }
                    }
                });

                if(valid) {
                    // go on as if nothing happened
                }
                else {
                    $$('.message').each(function(msg, i) {
                        msg.destroy();
                    });
                    var notification = new Element('div');
                    notification.addClass('message');
                    notification.inject(this, 'before');
                    notification.set('html', error_msg.join('<br/>'));
                    notification.setStyles({
                        opacity: 0
                    });
                    var oldheight = notification.offsetHeight;
                    var morph = new Fx.Morph(notification, {
                            duration: 250
                    }).start({
                        opacity: 1
                    });
                    //alert(error_msg.join('\n'));
                    new Event(e).stop();
                }
            });
        });
        // set focus to the first required field
        if(document.getElements('.properties input.required').length) {
            var requiredinputs = document.getElements('.properties input.required');
            requiredinputs[0].focus();
        }
    } catch(e) {
        // do nothing!
    }
}

/* AJAX Login Screen */
function fetchLoginScreen(html) {
    if(!html)
        return html;

    var result = new Element('div');
    result.inject($(document.body), 'bottom');
    result.innerHTML = html;
    if(result.getElement('#login')) {
        var login_again_bg = new Element('div').inject($(document.body), 'bottom').addClass('login_again_bg').setStyle('opacity', 0.3);
        var login_again = new Element('div');
        result.getElement('#login').inject(login_again);
        login_again.addClass('login_again');
        login_again.inject($(document.body), 'bottom');
        login_again.getElement('input').focus();
        var message = new Element('div').inject(login_again).addClass('cms_login_again_msg').set('html', "Ihre Session ist abgelaufen! Bitte loggen Sie sich erneut ein.");
        login_again.getElement('form').addEvent('submit', function(e) {
            new Event(e).stop();
            var loginrequest = new Request.HTML({
                url: document.location.href,
                onComplete: function(tree, eles, html, js) {
                    $$('.login_again, .login_again_bg').dispose();
                    fetchLoginScreen(html);
                }
            }).post($('login').getElement('form'));
            $$('.login_again input')[0].addClass('loading');
        });
    }
    result.dispose();
    return $$('.login_again').length;
}

/* Textarea Tiny_MCE */

function initTinyMCE() {
    var css_colors = new Array();
    var additional_css_content = $('tinymce_content_css_files');
    if(additional_css_content) {
        css_colors = parseCSSColors(additional_css_content.innerHTML);
        var css_colors_hex = new Array();
        for(c=0; c<css_colors.length; c++) {
            css_colors_hex.push(css_colors[c]['hex_code']);
        }
        css_colors = css_colors_hex;
        css_colors.sort();
        additional_css_content.dispose();
    }

    tinyMCE.init({
        theme_advanced_text_colors: css_colors.length ? css_colors : 0,
        theme_advanced_default_foreground_color: css_colors.length ? '#' + css_colors[0] : 0,
        theme_advanced_background_colors: css_colors.length ? css_colors : 0,
        theme_advanced_default_background_color: css_colors.length ? '#' + css_colors[0] : 0,
        theme     : "advanced",
        language : 'de',
        languages : 'de',
        mode      : "textareas",
        plugins   : "link_image_browser,paste,save,searchreplace,preview,insertdatetime,table,spellchecker,fullscreen,media,inlinepopups",
        theme_advanced_toolbar_location : "top",
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,removeformat",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,visualaid,|,sub,sup,|,charmap,media,fullscreen",
        //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
        convert_urls : false,
        entities : '38,amp,60,lt,62,gt', // TinyMCE by default replaces many characters with named entities: http://www.tinymce.com/wiki.php/Configuration:entities
        setup : function(editor) {
            editor.onInit.add(function(editor) {
                if($('editor_text'))
                    $('editor_text').setStyles({ visibility: 'visible' });
            });
            editor.onPostProcess.add(function(editor, o) {
                o.content = o.content.replace(/<ul[^>]*>[^<]*<\/ul>/g, '');
                o.content = o.content.replace(/<ol[^>]*>[^<]*<\/ol>/g, '');
            });
        }
    });
}

/* AJAX Text Editor */
var codemirror_editor;
function initAJAXTextEditor() {
    var css, parser;

    if($('ajax_editor')) {
        $('ajax_editor').addEvent('submit', function(e) {
            new Event(e).stop();

            if (codemirror_editor)
                $('textedit').value = codemirror_editor.getCode();

            var myHTMLRequest = new Request.HTML({
                url: 'manage',
                onComplete: function(tree, eles, html, js) {
                    if(fetchLoginScreen(html)) {
                        $('save_result').innerHTML = '';
                    }
                    else {
                        $('save_result').innerHTML = html;
                    }
                }
            }).post($('ajax_editor'));
            $('save_result').innerHTML = "Sende Daten ...";
        });

        var content_type = $('content_type');
        if (content_type) {
            content_type = content_type.innerHTML;
            if (content_type == "text/css") {
                var button = new Element('input');
                button.type = "button";
                button.onclick = function() { checkCSS(); }
                button.value = "Farben auslesen";
                button.inject($('save_result'), 'before');
            }
            css = {'text/css': 'csscolors.css', 'text/plain': 'csscolors.css', 'text/html': 'xmlcolors.css', 'text/x-python': 'pythoncolors.css', 'application/x-python': 'pythoncolors.css', 'application/javascript': 'jscolors.css'}[content_type];
            parser = {'text/css': 'parsecss.js', 'text/plain': 'parsecss.js', 'text/html': 'parsexml.js', 'text/x-python': 'parsepython.js', 'application/x-python': 'parsepython.js', 'application/javascript': ['tokenizejavascript.js', 'parsejavascript.js']}[content_type];
        }

        ajax_txt_editor_size();

        if (parser) {
            codemirror_editor = CodeMirror.fromTextArea('textedit', {
                parserfile: parser,
                stylesheet: codemirror_css + css,
                path: codemirror_path,
                continuousScanning: 500,
                indentUnit: 4,
                tabMode: 'shift'
            });
        }
    }
}

function ajax_txt_editor_size() {
    if($('textedit')) {
        var txt = $('textedit');

        var newHeight = window.getHeight().toInt() - 200;
        if(newHeight < 10)
            newHeight = 10;
        txt.setStyle('height', newHeight);
    }
}

window.addEvent('resize', function() {
    ajax_txt_editor_size();
});

/* Table Editor */
var original_table_code = false;
function initTableEditor() {
    if($('table_editor')) {
        var table_content = $('table_content').value;
        if(original_table_code == false) {
            // save only the first time this function is called
            original_table_code = table_content;
        }

        table_content = createTableCodeFromEval(table_content); // try to eval the saved data, returns the same data if nothing happens

        var table_type = $$('select[name="type"]')[0].value;
        var table_cols = $$('input[name="cols"]')[0].value;
        var table_rows = $$('input[name="rows"]')[0].value;

        /*
            Differences between types:
            Type 1: Has table, thead, tr, th, tbody tr, td setup
            Type 2: Difference: thead > tr > th always has colspan of max cols
            Type 3: Only first col are always th; And no thead
            Type 4: Upper left is normal td with NO value; rest of thead is th; in tbody first col is always th
            Type 5: No thead, all cells are td
        */
        var content_parser = new Element('div');
        content_parser.innerHTML = table_content;
        /* Tables are built like this:
            LIST (table)
                ITEM (tr)
                    LIST
                        ITEM (td)
                            DICTIONARY
                                ITEM (with key = colspan/content/format/tag)
        */
        var thead = new Element('thead');
        var tbody = new Element('tbody');

        var newtable = false;

        if($('table_content').value != "" && $('table_content').value.indexOf('<list>') > -1) {
            var xmlDoc;
            if (window.ActiveXObject) {
                //for IE
                var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async="false";
                xmlDoc.loadXML(table_content);
            }
            else if (document.implementation && document.implementation.createDocument) {
                //for Webkit browsers
                var parser = new DOMParser();
                xmlDoc = parser.parseFromString(table_content,"text/xml");
            }

            if(xmlDoc) {
                var actual_rows = xmlDoc.firstChild.childNodes.length;
                var actual_cols = table_cols;
                var myrows = xmlDoc.firstChild.childNodes;
                for(i=0; i<myrows.length; i++) {
                    var el = myrows[i];
                    var tr = new Element('tr');
                    actual_cols = el.firstChild.childNodes.length;

                    var mycols = el.firstChild.childNodes;
                    for(o=0; o<mycols.length; o++) {
                        var obj = mycols[o];
                        var obj_children = obj.firstChild.childNodes;

                        var td_tag, td_colspan, td_content, override_tag;
                        override_tag = "";
                        for(c=0; c<obj_children.length; c++) {
                            switch (obj_children[c].getAttributeNode('key').nodeValue) {
                                case "tag":
                                    td_tag = obj_children[c].firstChild.nodeValue;
                                    break;
                                case "colspan":
                                    td_colspan = obj_children[c].firstChild.nodeValue;
                                    break;
                                case "content":
                                    td_content = obj_children[c].firstChild.nodeValue;
                                    break;
                                case "overridetag":
                                    override_tag = obj_children[c].firstChild.nodeValue;
                                    break;
                            }
                        }

                        var td = createNewTableCell(td_tag, td_colspan, td_content, override_tag);
                        tr.grab(td);
                    }

                    // table types 3 and 5 don't have thead
                    if(i == 0 && table_type != 3 && table_type != 5) {
                        thead.grab(tr);
                    }
                    else {
                        tbody.grab(tr);
                    }
                }
                table_cols = $$('input[name="cols"]')[0].value = actual_cols;
                table_rows = $$('input[name="rows"]')[0].value = actual_rows;
            }
        }
        else { // create new table from scratch
            newtable = true;
            for(i=1; i<=table_rows; i++) {
                var tr = new Element('tr');
                for(b=0; b<table_cols; b++) {
                    var td = createNewTableCell('td', 1, '');
                    if(table_type == 2) {
                        if(i == 1) {
                            if(b == 0) {
                                // add colspan for table type 2, only grab one cell for this row
                                td.colSpan = table_cols;
                                tr.grab(td);
                            }
                        }
                        else {
                            tr.grab(td);
                        }
                    }
                    else {
                        tr.grab(td);
                    }
                }

                // table types 3 and 5 don't have thead
                if(i == 0 && table_type != 3 && table_type != 5) {
                    thead.grab(tr);
                }
                else {
                    tbody.grab(tr);
                }
            }
        }

        var colgroup = new Element('colgroup');
        for(i=1; i<=table_cols; i++) {
            var col = new Element('col');
            colgroup.grab(col);
        }

        var table = new Element('table');

        table.grab(colgroup);
        if(table_type != 3 && table_type != 5) {
            table.grab(thead);
        }
        table.grab(tbody);

        $('table_editor').innerHTML = '';
        $('table_editor').grab(table);

        drawTableInterface();

        if(newtable) {
            createTableCode();
        }

        content_parser.dispose();

        $$('select[name="type"]')[0].removeEvents('change').addEvent('change', function() {
            // here's the thing, only type 2 uses a colSpan of total columns for the first row/first cell
            var table_cols = $$('input[name="cols"]')[0].value;
            var table_rows = $$('input[name="rows"]')[0].value;
            var tr = $$('#table_editor table tr')[0];
            var tds = tr.getChildren('*');

            if(this.value == 2) {
                if(tds.length >= table_cols) {
                    // dispose of all tds except the first one
                    for(i=1; i<tds.length; i++) {
                        tds[i].dispose();
                    }
                }
                tds[0].colSpan = table_cols;
            }
            else {
                // add columns to first row
                tds[0].colSpan = 1;
                var createcount = table_cols - tds.length;
                for(i=0; i<createcount; i++) {
                    var td = createNewTableCell('td', 1, '');
                    tr.grab(td);
                }
            }

            // show example
            $$('.tableexample div').setStyles({ display: 'none' });
            $$('.tableexample .example' + this.value)[0].setStyles({ display: 'block' });

            createTableCode();
            initTableEditor();
        });

        $('new_table').removeEvents('click').addEvent('click', function() {
            $('table_content').value = '';
            initTableEditor();
        });

        $('revert_table').removeEvents('click').addEvent('click', function() {
            document.location.href = document.location.href.split('#')[0]; // no location.reload, cause firefox remembers values
            //$('table_content').value = original_table_code;
            //initTableEditor();
        });
    }
}

function createNewTableCell(td_tag, td_colspan, td_content, override_tag) {
    var td_tag = td_tag;
    var td_colspan = td_colspan;
    var td_content = td_content;
    var override_tag = override_tag;

    var td = new Element(td_tag);
    td.colSpan = td_colspan;
    td.overrideTag = override_tag; // used to display a different tag in template, override the default tag!

    var textarea = new Element('textarea');
    textarea.value = td_content;
    textarea.addEvent('keyup', function() {
        createTableCode();
    });
    td.grab(textarea);
    return td;
}

function drawTableInterface() {
    var cols = $$('#table_editor table colgroup col').length;
    var rows = $$('#table_editor table tr').length;

    // create buttons for managing cols
    if($('toppanel')) {
        $('toppanel').dispose();
    }
    var toppanel = new Element('div');
    toppanel.id = 'toppanel';
    var table = new Element('table');
    var tr = new Element('tr');
    for(i=0; i<=cols; i++) {
        var td = new Element('td');

        // add new cols
        var a = new Element('a');
        a.innerHTML = "<span>[+]</span>";
        a.colIndex = i;
        a.href = '#';
        a.addClass('new');
        a.addEvent('click', function(e) {
            var event = new Event(e).stop();
            var colIndex = this.colIndex;
            $$('#table_editor tr').each(function(el, i) {
                var tds = el.getChildren('*'); // can be th or td
                if(tds.length < cols) { // this line probably has a colspan
                    tds[0].colSpan = cols + 1;
                }
                else {
                    var td = createNewTableCell(tds[0].tagName.toLowerCase(), 1, '');
                    if(colIndex >= cols) {
                        td.inject(tds[colIndex-1], 'after');
                    }
                    else {
                        td.inject(tds[colIndex], 'before');
                    }
                }
            });
            // update input fields at the top
            $$('input[name="cols"]')[0].value = cols + 1;
            $$('input[name="rows"]')[0].value = rows;

            createTableCode(); // compile code
            initTableEditor(); // redraw everything
        });
        a.addEvent('mouseover', function(e) {
            tableEditorHighlightCol(this.colIndex);
        });
        td.grab(a);

        if(i > 0) {
            // delete rows
            var a_delete = new Element('a');
            a_delete.colIndex = i;
            a_delete.href = '#';
            a_delete.addClass('delete');
            a_delete.innerHTML = '<span>[X]</span>';
            a_delete.addEvent('click', function(e) {
                var event = new Event(e).stop();
                var colIndex = this.colIndex;
                $$('#table_editor tr').each(function(el, i) {
                    if(el.getChildren('*').length > 1) {
                    el.getChildren('*')[colIndex-1].dispose();
                    }
                });

                // update input fields at the top
                $$('input[name="cols"]')[0].value = cols - 1;
                $$('input[name="rows"]')[0].value = rows;

                createTableCode(); // compile code
                initTableEditor(); // redraw everything
            });
            a_delete.addEvent('mouseover', function(e) {
                tableEditorHighlightCol(this.colIndex-1, 'noborder');
            });

            td.grab(a_delete);
        }

        if(i > 1) {
            // move column left
            var a_left = new Element('a');
            a_left.innerHTML = "<span><</span>";
            a_left.colIndex = i-1;
            a_left.href = '#';
            a_left.addClass('left');
            a_left.addEvent('click', function(e) {
                var event = new Event(e).stop();
                var colIndex = this.colIndex;
                $$('#table_editor tr').each(function(el, i) {
                    var tds = el.getChildren('*'); // can be th or td
                    if(tds.length < cols) { // this line probably has a colspan
                        // do nothing
                    }
                    else {
                        // copy content from this td to the left and other way around
                        var this_content = tds[colIndex].getElement('textarea').value;
                        var left_content = tds[colIndex-1].getElement('textarea').value;
                        tds[colIndex].getElement('textarea').value = left_content;
                        tds[colIndex-1].getElement('textarea').value = this_content;
                    }
                });

                createTableCode(); // compile code
                initTableEditor(); // redraw everything
            });
            a_left.addEvent('mouseover', function(e) {
                tableEditorHighlightCol(this.colIndex, 'noborder');
            });
            td.grab(a_left);
        }

        if(i > 0 && i < cols) {
            // move column right
            var a_right = new Element('a');
            a_right.innerHTML = "<span>></span>";
            a_right.colIndex = i - 1;
            a_right.href = '#';
            a_right.addClass('right');
            a_right.addEvent('click', function(e) {
                var event = new Event(e).stop();
                var colIndex = this.colIndex;
                $$('#table_editor tr').each(function(el, i) {
                    var tds = el.getChildren('*'); // can be th or td
                    if(tds.length < cols) { // this line probably has a colspan
                        // do nothing
                    }
                    else {
                        if(colIndex < tds.length - 1) {
                            // copy content from this td to the right and other way around
                            var this_content = tds[colIndex].getElement('textarea').value;
                            var right_content = tds[colIndex+1].getElement('textarea').value;
                            tds[colIndex].getElement('textarea').value = right_content;
                            tds[colIndex+1].getElement('textarea').value = this_content;
                        }
                    }
                });

                createTableCode(); // compile code
                initTableEditor(); // redraw everything
            });
            a_right.addEvent('mouseover', function(e) {
                tableEditorHighlightCol(this.colIndex, 'noborder');
            });
            td.grab(a_right);
        }

        tr.grab(td);
    }
    table.grab(tr);
    toppanel.grab(table);
    //toppanel.getElements('td').setStyle('width', (100/cols) + '%');
    toppanel.inject($('table_editor'), 'before');
    if(rows > 0) {

    }

    // create buttons for managing rows
    if($('leftpanel')) {
        $('leftpanel').dispose();
    }
    var leftpanel = new Element('div');
    leftpanel.id = 'leftpanel';
    var table = new Element('table');
    for(i=0; i<rows; i++) {
        var tr = new Element('tr');
        var td = new Element('td');

        // add new rows
        var a = new Element('a');
        a.innerHTML = "<span>[+]</span>";
        a.rowIndex = i;
        a.href = '#';
        a.addClass('new');
        a.addEvent('click', function(e) {
            var event = new Event(e).stop();
            var rowIndex = this.rowIndex;
            var new_tr = new Element('tr');
            for(c=0; c<cols; c++) {
                var td = createNewTableCell('td', 1, '');
                new_tr.grab(td);
            }
            new_tr.inject($$('#table_editor table tr')[rowIndex], 'after');

            // update input fields at the top
            $$('input[name="cols"]')[0].value = cols;
            $$('input[name="rows"]')[0].value = rows + 1;

            createTableCode(); // compile code
            initTableEditor(); // redraw everything
        });
        a.addEvent('mouseover', function(e) {
            tableEditorHighlightRow(this.rowIndex);
        });
        td.grab(a);

        // delete rows
        var a_delete = new Element('a');
        a_delete.rowIndex = i;
        a_delete.href = '#';
        a_delete.innerHTML = '<span>[X]</span>';
        a_delete.addClass('delete');
        a_delete.addEvent('click', function(e) {
            var event = new Event(e).stop();
            var rowIndex = this.rowIndex;
            $$('#table_editor table tr')[rowIndex].dispose();

            // update input fields at the top
            $$('input[name="cols"]')[0].value = cols;
            $$('input[name="rows"]')[0].value = rows - 1;

            createTableCode(); // compile code
            initTableEditor(); // redraw everything
        });
        a_delete.addEvent('mouseover', function(e) {
            tableEditorHighlightRow(this.rowIndex, 'noborder');
        });
        td.grab(a_delete);

        if(i < rows - 1) {
            // move column down
            var a_down = new Element('a');
            a_down.innerHTML = "<span>v</span>";
            a_down.rowIndex = i;
            a_down.href = '#';
            a_down.addClass('down');
            a_down.addEvent('click', function(e) {
                var event = new Event(e).stop();
                var rowIndex = this.rowIndex;
                var trs = $$('#table_editor tr');

                // copy content from this tr to the one underneath and other way around
                var this_textareas = trs[rowIndex].getElements('textarea');
                var down_textareas = trs[rowIndex+1].getElements('textarea');

                this_textareas.each(function(el, i) {
                    var down_content = down_textareas[i].value;
                    down_textareas[i].value = el.value;
                    el.value = down_content;
                });

                createTableCode(); // compile code
                initTableEditor(); // redraw everything
            });
            a_down.addEvent('mouseover', function(e) {
                tableEditorHighlightRow(this.rowIndex, 'noborder');
            });
            td.grab(a_down);
        }

        if(i > 0) {
            // move column up
            var a_up = new Element('a');
            a_up.innerHTML = "<span>^</span>";
            a_up.rowIndex = i;
            a_up.href = '#';
            a_up.addClass('up');
            a_up.addEvent('click', function(e) {
                var event = new Event(e).stop();
                var rowIndex = this.rowIndex;
                var trs = $$('#table_editor tr');

                // copy content from this tr to the one above and other way around
                var this_textareas = trs[rowIndex].getElements('textarea');
                var up_textareas = trs[rowIndex-1].getElements('textarea');

                if(up_textareas.length == this_textareas.length) {
                    this_textareas.each(function(el, i) {
                        var up_content = up_textareas[i].value;
                        up_textareas[i].value = el.value;
                        el.value = up_content;
                    });
                }

                createTableCode(); // compile code
                initTableEditor(); // redraw everything
            });
            a_up.addEvent('mouseover', function(e) {
                tableEditorHighlightRow(this.rowIndex, 'noborder');
            });
            td.grab(a_up);
        }

        tr.grab(td);
        table.grab(tr);
    }
    leftpanel.grab(table);
    leftpanel.inject($('table_editor'), 'before');

    // remove stuff that was added when highlighting panel links
    $$('#leftpanel a, #toppanel a').each(function(a, i) {
        a.addEvent('mouseout', function() {
            $$('#table_editor tr').each(function(tr, t) {
                var tds = tr.getChildren('*');
                tds.setStyles({
                    'border': 0,
                    'background': '#ddd'
                });
            });
        });
    });

    adjustTableEditor();
    moveIndividualCells();
    tableCellSettings();
}

function tableCellSettings() {
    if($('table_editor')) {
        $$('#table_editor table td, #table_editor table th').each(function(td, i) {
            td.addEvent('mousedown', function() {
                var settings = $('tablecellsettings');
                if(!settings) {
                    settings = new Element('div');
                    settings.id = 'tablecellsettings';
                    settings.inject($(document.body), 'bottom');
                    settings.innerHTML = 'Zellentyp: <select name="overrider"><option value="">Standard</option><option value="td">TD</option><option value="th">TH</option></select>';
                    settings.getElement('select').addEvent('change', function() {
                        this.getParent().myclient.overrideTag = this.value;
                        createTableCode();
                    });
                }
                settings.myclient = this; // this is the cell I'll be servicing today
                var overrideTag = this.overrideTag;
                if(!overrideTag) {
                    overrideTag = "";
                }
                settings.getElements('option').each(function(option, o) {
                    if(option.value == overrideTag) {
                        option.selected = 'selected';
                    }
                });
                if($$('select[name="type"]')[0].value == 5) {
                    settings.setStyles({
                        position: 'absolute',
                        padding: '5px',
                        border: '1px solid gray',
                        background: 'white',
                        display: 'block',
                        fontSize: '10px'
                    });
                    settings.setStyles({
                        top: this.getTop() + this.getHeight() - settings.getHeight(),
                        left: this.getLeft() + this.getWidth() - settings.getWidth()
                    });
                }
                else {
                    settings.setStyles({
                        display: 'none'
                    });
                }
            });
        });
    }
}

function adjustTableEditor() {
    if($('table_editor')) {
        var rows = $$('#table_editor table tr').length;
        // adjust size of cols and rows
        $$('#leftpanel a, #toppanel a').addClass('button');
        if(rows > 0) {
            $$('#toppanel td').each(function(td, i) {
                if(i > 0) {
                    var tds = $$('#table_editor table tr')[rows-1].getElements('td, th');
                    if(tds.length > 1) {
                        td.setStyle('width', tds[i-1].getWidth() + 'px');
                    }
                }
            });
            $$('#leftpanel tr td').setStyle('height', $$('#table_editor table tr')[rows-1].getHeight() + 'px');
            $$('#leftpanel tr td').setStyle('height', ($$('#table_editor table tr')[rows-1].getHeight() - ($$('#leftpanel tr td')[0].getHeight()-$$('#table_editor table tr')[rows-1].getHeight())) + 'px');
            $('toppanel').setStyle('width', ($('leftpanel').getWidth() + $('table_editor').getElement('table').getWidth()) + 'px');
        }
        $$('#toppanel td')[0].setStyle('width', ($('leftpanel').getElement('td').getWidth()-10) + 'px');
        $$('#table_editor textarea').setStyle('opacity', 0.9);
    }
}

// swap individual cells
var currentCell = false;
function moveIndividualCells() {
    $$('#table_editor tr > *').addEvent('mousedown', function(e) {
        var swapinfo = $('swapinfo');
        if(!(swapinfo)) {
            swapinfo = new Element('div');
            swapinfo.id = 'swapinfo';
            swapinfo.innerHTML = 'Auf Zelle klicken, mit der der Inhalt ausgetauscht werden soll.';
            swapinfo.inject($(document.body), 'bottom');
        }

        if(currentCell != false) {
            var currenttextarea = currentCell.getElement('textarea');
            var newtextarea = this.getElement('textarea');
            var currentvalue = currenttextarea.value;
            currenttextarea.value = newtextarea.value;
            newtextarea.value = currentvalue;
            currentCell.getElement('textarea').removeClass('activecell');
            currentCell.getElement('textarea').mousein = false;
            currentCell = false;
            swapinfo.setStyles({
                'display': 'none'
            });
            createTableCode();
        }
        else {
            if(!this.getElement('textarea').mousein) {
                currentCell = this;
                currentCell.getElement('textarea').addClass('activecell');

                swapinfo.setStyles({
                    'display': 'block',
                    'top': (currentCell.getTop()+5) + 'px',
                    'left': (currentCell.getLeft()+50) + 'px',
                    'opacity': 0.8
                });
            }
        }
    });
    $$('#table_editor textarea').addEvent('mouseup', function() {
        currentCell = false;
        this.removeClass('activecell');
    });
    $$('#table_editor textarea').addEvent('mouseover', function() {
        this.mousein = true;
    });
    $$('#table_editor textarea').addEvent('mouseout', function() {
        this.mousein = false;
    });
}

function tableEditorHighlightRow(rowIndex, noborder) {
    var table_type = $$('select[name="type"]')[0].value;
    var trs = $$('#table_editor tr');
    if(noborder == undefined) {
        trs[rowIndex].getChildren('*').setStyle('borderBottom', '10px solid #fba800');
    }
    else {
        trs[rowIndex].getChildren('*').setStyle('background', '#8eadde');
    }
}

function tableEditorHighlightCol(colIndex, noborder) {
    var table_type = $$('select[name="type"]')[0].value;
    var trs = $$('#table_editor tr').each(function(el, i) {
        var tds = el.getChildren('*');
        if(table_type == 2 && i == 0 && colIndex > 0) {
            // do nothing, there's only one cell with colSpan
        }
        else {
            if(colIndex == tds.length) {
                if(noborder == undefined) {
                    tds[colIndex-1].setStyle('borderRight', '10px solid #fba800');
                }
                else {
                    tds[colIndex-1].setStyle('background', '#8eadde');
                }
            }
            if(colIndex < tds.length) {
                if(noborder == undefined) {
                    tds[colIndex].setStyle('borderLeft', '10px solid #fba800');
                }
                else {
                    tds[colIndex].setStyle('background', '#8eadde');
                }
            }
        }
    });
}

function createTableCode() {
    // piece this thing together
    var trs = $$('#table_editor tr');
    var new_table_content = "<list>";
    trs.each(function(el, i) {
        new_table_content += '<item type="list"><list>';
        var kids = el.getChildren();
        kids.each(function(child, c) {
            var colspan = child.colSpan;
            var overrideTag = child.overrideTag != undefined ? child.overrideTag : '';
            new_table_content += '<item type="dictionary"><dictionary>';
            new_table_content += '<item key="colspan" type="int">' + colspan + '</item>';
            new_table_content += '<item key="content"><![CDATA[' + child.getElement('textarea').value + ']]></item>';
            new_table_content += '<item key="format"><![CDATA[body]]></item>';
            new_table_content += '<item key="tag"><![CDATA[' + child.tagName.toLowerCase() + ']]></item>';
            new_table_content += '<item key="overridetag"><![CDATA[' + overrideTag + ']]></item>';
            new_table_content += '</dictionary></item>';
        });
        new_table_content += '</list></item>';
    });
    new_table_content += '</list>';
    $('table_content').value = new_table_content;
}

function createTableCodeFromEval(data) {
    // tries to eval the given data, some tables seem to have a parse-able data handy
    if(data.indexOf('[[') > -1 && data.indexOf("'content'") > -1) {
        eval("var rows = " + data);
        var new_table_content = "<list>";
        rows.each(function(kids, i) {
            new_table_content += '<item type="list"><list>';
            kids.each(function(child, c) {
                var colspan = child['colspan'];
                var overrideTag = child['tag'];
                new_table_content += '<item type="dictionary"><dictionary>';
                new_table_content += '<item key="colspan" type="int">' + colspan + '</item>';
                new_table_content += '<item key="content"><![CDATA[' + child['content'] + ']]></item>';
                new_table_content += '<item key="format"><![CDATA[body]]></item>';
                new_table_content += '<item key="tag"><![CDATA[' + overrideTag + ']]></item>';
                new_table_content += '<item key="overridetag"><![CDATA[' + overrideTag + ']]></item>';
                new_table_content += '</dictionary></item>';
            });
            new_table_content += '</list></item>';
        });
        new_table_content += '</list>';
        $('table_content').value = new_table_content;
        return new_table_content;
    }
    else {
        return data;
    }
}

/* Table Hover */
function initTableHover() {
    var tables = $$('table');
    tables.each(function(el, i) {
        if(el.className.indexOf("hoverrows") > -1) {
            var trs = el.getElements('tbody tr');
            trs.each(function(tr, p) {
                tr.addEvent('mouseover', function() {
                    this.addClass('hover');
                });

                tr.addEvent('mouseout', function() {
                    this.removeClass('hover');
                });
            });
        }
    });
}

/* Checking Checkboxes */
function checkBox(tr, override) {
    if(override == undefined)
        var override = '';

    var checkbox = tr.getElement('.selectionbox');
    if(checkbox) {
        if(checkbox.checked && override == '' || override == 'off') {
            checkbox.checked = false;
            tr.removeClass('checked');
        }
        else if(!checkbox.checked && override == '' || override == 'on') {
            checkbox.checked = true;
            tr.addClass('checked');
        }
    }
}

/* Get Selections */
function getSelectedIDs() {
    var container = new Array();
    var tr = $$('.folder_view tr');
    tr.each(function(el, i) {
        var checkbox = el.getElement('.selectionbox');
        if(checkbox) {
            if(checkbox.checked) {
                container.push(el.id.replace("row_", ""));
            }
        }
    });

    return container;
}

function getSelectedOrActiveIDs() {
    var selectedIDs = getSelectedIDs();
    if(selectedIDs.length == 0 && $$('.haspanel').length > 0) {
        var activeRow = $$('.haspanel')[0];
        if(activeRow.id.indexOf('row') > -1) {
            selectedIDs.push(activeRow.id.replace('row_', ''));
        }
    }
    return selectedIDs;
}

function getDomain() {
    var location = document.location.href;
    var splitloc = location.split('/content');
    splitloc = splitloc[0].split('/');
    return splitloc[ splitloc.length-1 ];
}

function getAdr(prefix, postfix, text) {
    document.write('<a href="mailto:' + prefix + '@' + postfix + '">' + (text ? text.replace(/&quot;/g, '"').replace(/%EMAIL%/, prefix + '@' + postfix) : prefix + '@' + postfix) + '</a>');
}

/* Paste Button */
function initPasteButton() {
    if( (Cookie.read('copyobjects') && $$('.folder_view').length > 0)
        || (Cookie.read('fs_copyobjects') && $$('.filesystem').length > 0)
            || (Cookie.read('attrs_copy') && $$('.metaobject_edit').length > 0)) {
        setPasteButton(1);
    }

    var pasteButton = document.getElements('.button.paste');
    if(pasteButton) {
        var pasteHover = $('pastehover');
        if(!pasteHover) {
            pasteHover = new Element('div');
            pasteHover.setStyles({
                position: 'absolute',
                border: '1px solid gray',
                background: '#fff',
                opacity: 0.9,
                display: 'none',
                padding: 10
            });
            pasteHover.inject(document.body, 'bottom');
            pasteHover.id = 'pastehover';
        }

        pasteButton.addEvent('mouseover', function() {
            var fs_copystring = Cookie.read('fs_copyobjects');
            if(fs_copystring && $$('.filesystem').length > 0) {
                var pasteHover = $('pastehover');
                var cpstring_split = fs_copystring.split('&file=');
                cpstring_split.shift();
                pasteHover.innerHTML = cpstring_split.join('<br>').replace("&del_origin=1", "");
                pasteHover.style.display = 'block';
                if($(this).getParent('.panel_bottom')) {
                    pasteHover.setStyles({
                        position: 'fixed',
                        top: this.getTop()-pasteHover.getHeight(),
                        left: this.getLeft()
                    });
                }
                else {
                    pasteHover.setStyles({
                        position: 'absolute',
                        top: this.getTop()+this.getHeight(),
                        left: this.getLeft()
                    });
                }
            }
            var copydescription = Cookie.read('copyobjects_description');
            if(copydescription && $$('.filesystem').length == 0) {
                var pasteHover = $('pastehover');
                var objectnames = copydescription.split('||');
                var uniquenames = new Object();
                for(n=0; n<objectnames.length; n++) {
                    if(uniquenames[objectnames[n]])
                        uniquenames[objectnames[n]]++;
                    else
                        uniquenames[objectnames[n]] = 1;
                }
                var newhtml = "";
                for(name in uniquenames) {
                    newhtml += name;
                    if(uniquenames[name] > 1) {
                        newhtml += ' <span class="gray">(' + uniquenames[name] + ')</span>';
                    }
                    newhtml += '<br/>';
                }
                pasteHover.innerHTML = newhtml;
                pasteHover.style.display = 'block';
                if($(this).getParent('.panel_bottom')) {
                    pasteHover.setStyles({
                        position: 'fixed',
                        top: this.getTop()-pasteHover.getHeight(),
                        left: this.getLeft()
                    });
                }
                else {
                    pasteHover.setStyles({
                        position: 'absolute',
                        top: this.getTop()+this.getHeight(),
                        left: this.getLeft()
                    });
                }
            }
        });
        pasteButton.addEvent('mouseout', function() {
            var pasteHover = $('pastehover');
            pasteHover.innerHTML = '';
            pasteHover.setStyle('display', 'none');
        });
    }
}

function setPasteButton(to) {
    var state = 1;
    if(to == 1)
        state = 0;

    var pasteButton = document.getElement('.paste img');

    if(pasteButton)
        pasteButton.src = pasteButton.src.replace(state+'.png', to+'.png');
}

/* Copy / Cut / Paste / Delete / Move for content management */
function copy(origin, button, del_origin) {
    if ($(button).hasClass('state0')) return;

    var selectedIDs = getSelectedOrActiveIDs();
    var copyDescription = new Array();
    var copyString = "origin=" + origin + ";";
    if(del_origin) {
        copyString = "del_orig=1;" + copyString;
    }

    selectedIDs.each(function(el, i) {
        if(el != "top") {
            copyString += "id=" + el + ";";
            copyDescription.push($('row_' + el).getElement('.firstcol a span').innerHTML);
        }
    });

    setPasteButton(1);

    if(selectedIDs.length) {
        Cookie.write('copyobjects', copyString, { path: '/' });
        Cookie.write('copyobjects_description', copyDescription.join('||'), { path: '/' });
        showButtonResponse(button);
    }
}

function cut(origin, button) {
    copy(origin, button, 1);
}

function paste(button, prefix) {
    if ($(button).hasClass('state0')) return;

    //read IDs from cookie and execute manage_paste?id...&after=...&projectid=...
    var copyString = Cookie.read('copyobjects');
    var after = '';
    if(activeCol) {
        after = activeCol.indexOf('row_') == -1 ? '' : activeCol.replace('row_', '');
    }

    prefix = (prefix) ? prefix : '';

    if(copyString)
        document.location.href = 'manage_paste?' + copyString + 'after=' + after + ';prefix=' + prefix;
}

function toggle_active(button, prefix) {
    var selectedIDs = getSelectedOrActiveIDs();
    var toggleActiveString = "";

    if($$('.row_top.haspanel').length) {
        selectedIDs.push($$('.row_top.haspanel')[0].id.split('title_')[1]);
    }

    selectedIDs.each(function(el, i) {
        toggleActiveString += "id=" + el + ";";
    });

    if(selectedIDs.length) {
        document.location.href = 'manage_toggle_active?' + toggleActiveString;
    }
}

function showButtonResponse(button) {
    var img = new Element('img').inject($(document.body), 'bottom');
    img.src = static + '/images/icons/new/okay_small.png';
    img.setStyles({
        position: 'absolute',
        top: button.getTop() + 'px',
        left: (button.getLeft() + button.getWidth()) + 'px',
        zIndex: 1000
    });
    if(button.getParent('.panel_bottom')) {
        img.style.position = 'fixed';
    }
    var morpher = new Fx.Morph(img, {
        duration: 1000,
        wait: false,
        onComplete: function() {
            this.img.dispose();
        }
    }).start({
        marginTop: '-20px',
        opacity: Browser.Engine.trident ? 1 : 0
    });
    morpher.img = img;
}

function del(button) {
    if ($(button).hasClass('state0')) return;

    var selectedIDs = getSelectedOrActiveIDs();

    if(selectedIDs.length == 0)
        return;

    var deleteURL = "manage_delete?";
    selectedIDs.each(function(el, i) {
        deleteURL += "id=" + el + ";";
    });

    // tell the user that objects will be removed in all languages, not in only the current one
    if($('language_selection') && $$('#language_selection option').length > 1) {
        var confirmstring = "Sind Sie sicher, dass Sie " + (selectedIDs.length > 1 ? "die ausgewählten Objekte" : "das ausgewählte Objekt") + " in allen Sprachen löschen möchten?";
        if(!confirm(confirmstring)) {
            return;
        }
    }

    document.location.href = deleteURL;
}

/* Copy & Paste for attribute management */
function copy_attr(object_id, attr_id) {
    var copyString = "?object_id=" + object_id + "&attr_id=" + attr_id;
    Cookie.write('attrs_copy', copyString, { path: '/' });
    setPasteButton(1);
}

function paste_attr(uri_paste) {
    var copyString = Cookie.read('attrs_copy');
    if(copyString)
        document.location.href = uri_paste + copyString;
}


/* Show Action/Objects Dialogue */
function showDiv(id, link) {

    if ($(link).hasClass('state0')) return;

    var allDivs = new Array('actions', 'objects');
    allDivs.each(function(el, i) {
        if (el != id) {
            var elements = link.getParent().getElements('.' + el);
            if (elements && elements.length)
                elements[0].setStyle('display', 'none');
        }
    });

    var actions = link.getParent().getElements('.' + id)[0];
    // if there's only one link, use it
    if (actions.getElements('ul a').length == 1) {
        var after = '';
        if (activeCol) {
            if (activeCol.indexOf('row') > -1) {
                after += "&after=" + activeCol.replace('row_', '');
            }
        }
        document.location.href = actions.getElement('ul a').href + after;
        return;
    }
    if (actions.style.display == 'block') {
        actions.setStyle("display", "none");
    }
    else {
        actions.setStyle("display", "block");
        var select = actions.getElement('select');
        var input = actions.getElement('input');
        if(select) {
            select.getElement('option').selected = true;
            select.focus();
        }
        else if(input) {
            input.focus();
            input.value = "";
            input.marked = -1;
            var ul = input.getParent().getParent().getElement('ul');
            var lis = ul.getElements('li');
            lis.each(function(li, i) {
                li.addClass('found'); //initially all elements are "found"
                li.removeClass('marked'); //initially all elements are not "marked"
                li.setStyle('display', 'block');
            });

            var scroll = new Fx.Scroll(ul, {
                wait: false,
                duration: 300,
                offset: {'x': 0, 'y': 0},
                transition: Fx.Transitions.Quad.easeInOut
            }).toTop();

            input.removeEvents("keydown");
            input.removeEvents("keyup");
            input.addEvent("keydown", function(event) {
                if(event.key == "esc") {
                    this.getParent().getParent().setStyle("display", "none");
                    this.marked = 0;
                }
                if(event.key == "down") {
                    this.marked++;
                    var ul = this.getParent().getParent().getElement('ul');
                    var lis = ul.getElements('li');
                    lis.each(function(li, i) {
                        li.removeClass('marked');
                    });
                    var foundelements = ul.getElements('.found');
                    if(foundelements.length) {
                        if(this.marked >= foundelements.length)
                            this.marked = 0;
                        foundelements[this.marked].addClass('marked');
                    }
                }
                if(event.key == "up") {
                    this.marked--;
                    var ul = this.getParent().getParent().getElement('ul');
                    var lis = ul.getElements('li');
                    lis.each(function(li, i) {
                        li.removeClass('marked');
                    });
                    var foundelements = ul.getElements('.found');
                    if(foundelements.length) {
                        if(this.marked < 0)
                            this.marked = foundelements.length-1;
                        foundelements[this.marked].addClass('marked');
                    }
                }

                if(event.key == "enter") {
                    var marked = this.getParent().getParent().getElement('.marked');
                    if(marked) {
                        var after = '?';
                        if(activeCol) {
                            if(activeCol.indexOf('row') > -1) {
                                after += "&after=" + activeCol.replace('row_', '');
                            }
                        }

                        document.location.href = marked.getElement('a').href + after;
                    }
                }
            });
            input.addEvent("keyup", function(event) {
                var allowedkeys = "abcdefghijklmnopqrstuvwxyz";
                if(allowedkeys.indexOf(event.key) > -1 || event.key == 'backspace') {
                    this.marked = 0;
                    var inputvalue = this.value;
                    var ul = this.getParent().getParent().getElement('ul');
                    var lis = ul.getElements('li');
                    var found = 0;
                    lis.each(function(li, i) {
                        li.removeClass('marked');
                        var a = li.getElement('a');
                        if(a.innerHTML.toLowerCase().indexOf(inputvalue.toLowerCase()) > -1) {
                            li.setStyle('display', 'block');
                            if(found == 0) {
                                li.addClass('marked');
                            }
                            else {
                                li.removeClass('marked');
                            }
                            li.addClass('found');
                            found++;
                        }
                        else if(inputvalue.length > 0) {
                            li.setStyle('display', 'none');
                            li.removeClass('found');
                        }
                        else {
                            li.setStyle('display', 'block');
                            li.addClass('found');
                        }
                    });
                }

                if(this.getParent().getElements('.marked').length) {
                    var scroll = new Fx.Scroll(this.getParent().getElement('ul'), {
                        wait: false,
                        duration: 100,
                        offset: {'x': 0, 'y': 0},
                        transition: Fx.Transitions.Quad.easeInOut
                    }).toElement(this.getParent().getElement('.marked'));
                }
            });
        }
    }
}

function closeDiv(link) {
    link.getParent().getParent().setStyle('display', 'none');
    return false;
}

/* Execute action chosen in object/action dialogue */
function executeSelectedAction(obj) {
    if(obj.value != "") {
        var activeID = activeCol.replace('row_', '');
        if(activeID == 'top')
            activeID = "";

        document.location.href = obj.value + "?id=" + activeID;
    }
}

/* Initialize panel */
function initPanel() {
    if($$('.panel').length) {
        $$('.panel .objects a').each(function(a, i) {
            a.removeEvents('click');
            a.addEvent('click', function(e) {
                var event = new Event(e).stop();
                var after = '?';
                if(activeCol.indexOf('row') > -1) {
                    after += "&after=" + activeCol.replace('row_', '');
                }

                document.location.href = this.href + after;
            });
        });
        // copy panel to the bottom of the page
        var panel_bottom = $$('.panel_bottom')[0];
        if($$('.manageproperties, .properties').length == 0) { // in properties of container objects we don't need any buttons other than the expanders
            panel_bottom.innerHTML = $$('.panel')[0].innerHTML;
            panel_bottom.getElements('a').removeProperty('accesskey');
        }

        // add expanders
        var expandall = new Element('a').inject(panel_bottom);
        expandall.href = '#';
        expandall.addClass('button');
        expandall.innerHTML = '<img src="' + static + '/images/icons/new/expandall.png" alt="Expand all" />';
        expandall.title = "Alle Objekte ausklappen [W]";
        expandall.setProperty('accesskey', 'w');
        expandall.addEvent('click', function(e) {
            var event = new Event(e).stop();
            $$('td.bodycontent').each(function(td) {
                if(!td.hasClass('expanded') && td.getElement('.bodycontent_container').innerHTML != "") {
                    td.getElement('.bodycontent_container').setStyles({
                        height: 'auto'
                    });
                    td.expanded = 1;
                    td.addClass('expanded');
                }
            });
            hidePanel();
        });
        var collapseall = new Element('a').inject(panel_bottom);
        collapseall.href = '#';
        collapseall.addClass('button');
        collapseall.innerHTML = '<img src="' + static + '/images/icons/new/collapseall.png" alt="Collapse all" />';
        collapseall.title = "Alle Objekte zuklappen [E]";
        collapseall.setProperty('accesskey', 'e');
        collapseall.addEvent('click', function(e) {
            var event = new Event(e).stop();
            $$('td.bodycontent').each(function(td) {
                if(td.hasClass('expanded') && td.getElement('.bodycontent_container').innerHTML != "") {
                    td.getElement('.bodycontent_container').setStyles({
                        height: '34px'
                    });
                    td.expanded = 0;
                    td.removeClass('expanded');
                }
            });
            hidePanel();
        });
    }
    if($$('.filesystem .actions').length) {
        // copy panel to the bottom of the page
        var panel_bottom = $$('.panel_bottom')[0];
        panel_bottom.innerHTML = $$('.filesystem .actions')[0].innerHTML;
        panel_bottom.getElements('a').removeProperty('accesskey');
    }
}

// hide all panels
function hidePanel() {
    $$('.panel').each(function(panel) {
        panel.setStyles({
            display: 'none'
        });
    });
    $$('tr.haspanel').removeClass('haspanel');
}

/* Move panel in content management to active row */
var activeCol = 0;
var activeTable = 0;
function movePanel(tr) {
    if($$('.panel').length) {
        if(!tr) {
            tr = $(document.body).getElement('.checked.haspanel');
        }
        if(!tr)
            return;
        if(tr.id.indexOf('row_') == -1 && !tr.hasClass('row_top')
            || tr.getElement('.expanded')) {
            $$('.panel').setStyle('display', 'none');
            $$('tr.haspanel').removeClass('haspanel');
            return;
        }

        $$('.haspanel').removeClass('haspanel');
        tr.addClass('haspanel');
        var table = tr.getParents('table')[0];
        var td = tr.getElements('td')[2];
        if(tr.getElements('td').length == 2 || tr.hasClass('row_top')) {
            td = tr.getElements('td')[1]; // for sub-objects or top rows
        }
        if (td) {
            var panel = tr.getParent().getElements('.panel')[0];
            if (panel) {
                $$('.panel').each(function(el, i) {
                    el.style.display = 'none';
                });
                if(table.hasClass('attr_object') && td.getChildren().length == 0) {
                    panel.style.top = td.getTop() + 'px';
                }
                else {
                    panel.style.top = (td.getTop() + 0) + 'px';
                }
                panel.style.left = (td.getLeft()+30) + 'px';
                if(tr.hasClass('row_top')) {
                    panel.style.left = (td.getLeft()+130) + 'px';
                }
                panel.style.display = 'block';

                showMetaobjectProperties();
            }

            $$('.panel .actions, .panel .objects, .panel_bottom .actions, .panel_bottom .objects').each(function(el, i) {
                el.style.display = 'none';
            });

            activeCol = tr.id;
            activeTable = table.id;
        }
        else {

        }
    }
}

/* Add Folder */
function addFolder() {
    var after = activeCol ? (activeCol.indexOf('row_') == -1 ? '' : activeCol.replace('row_', '')) : '';

    document.location.href = 'manage_add_zms_folder?after=' + after;
}

/* Selection */
function selectAll(element) {
    var tr = getSelectElements(element);
    tr.each(function(el, i) {
        var checkbox = el.getElement('.selectionbox');
        if(checkbox) {
            checkbox.checked = true;
            tr.addClass('checked');
        }
    });

    var selectAllButton = getSelectButton(element, 'all');
    var selectNoneButton = getSelectButton(element, 'none');
    if(selectAllButton && selectNoneButton) {
        selectAllButton.setStyle('display', 'none');
        selectNoneButton.setStyle('display', 'block');
    }
}

function selectNone(element) {
    var tr = getSelectElements(element);
    tr.each(function(el, i) {
        var checkbox = el.getElement('.selectionbox');
        if(checkbox) {
            checkbox.checked = false;
            tr.removeClass('checked');
        }
    });

    var selectAllButton = getSelectButton(element, 'all');
    var selectNoneButton = getSelectButton(element, 'none');
    if(selectAllButton && selectNoneButton) {
        selectAllButton.setStyle('display', 'block');
        selectNoneButton.setStyle('display', 'none');
    }
}

function getSelectElements(element) {
    if (element != undefined) {
        var table = $(element).getParents('table')[0];
        return table.getElements('tr');
    }
    return $$('.folder_view tr, .file_system_browser tr');
}

function getSelectButton(element, type) {
    if (element != undefined) {
        var table = $(element).getParents('table')[0];
        return table.getElements('.select' + type)[0];
    }
    return $$('.select' + type);
}

/* Ajax Browser */
function showBrowser(obj) {
    obj = $(obj);
    var browser = $('selector');
    if(!browser) {
        browser = new Element('div');
        browser.inject(document.getElement('body'), 'bottom');
    }

    var html = "<div class=\"title\">Link auswählen</div>";
    html += "<div class=\"browser browserloading\"></div>";
    html += "<a class=\"closer\" href=\"javascript:closeBrowser()\"></a>";
    browser.innerHTML = html;
    browser.id = "selector";
    browser.setStyles({
        position: "absolute",
        top: obj.getTop(),
        left: obj.getLeft()+obj.getWidth()+2,
        width: 300,
        height: 1,
        display: 'block',
        overflow: 'hidden'
    });

    if(obj.getLeft() + obj.getWidth() + 300 > document.body.offsetWidth) {
        browser.setStyles({
            top: obj.getTop() + obj.getHeight() + 2,
            left: document.body.offsetWidth - 320
        });
    }

    browser.setStyle('width', 1);

    browser.morph = new Fx.Morph(browser, {
        duration: 250
    });
    browser.morph.start({
        width: 300,
        height: 400
    });

    if(browser.opener)
        browser.opener.removeClass('active');

    if(obj.getParent('label')) {
        browser.opener = obj.getParent('label');
    }
    else {
        browser.opener = obj.getParent();
    }

    browser.opener.addClass('active');

    var init = '';
    var path = '';

    var inputValue = browser.opener.getElement('input').get('value');
    if(inputValue != '' && inputValue.match(/^{\$(.*)}$/)) {
        path = RegExp.$1;
        init = '&init=1';
    }

    var delimiter = document.location.href.indexOf('system') > -1 ? 'system' : 'content';

    var url = document.location.href.split(delimiter)[0] + 'content/' + path + '/manage_tree?show_root=1&pages=1&for_url=1' + init;
    if(browser.linkrequest)
        browser.linkrequest.cancel();
    browser.linkrequest = new Request.HTML({
        update: $('selector').getElement('.browser'),
        onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
            if(!responseHTML) {
                if(!$('selector').getElement('.cms_url_error')) {
                    var divnote = new Element('div').inject($('selector').getElement('.browser'), 'before');
                    divnote.innerHTML = 'Der angegebene Link existiert nicht!';
                    divnote.addClass('cms_url_error');
                    $('selector').morph.cancel().start({
                        width: 300,
                        height: (400 + divnote.getHeight()) + 'px'
                    });
                    $('selector').opener.getElement('input').value = "";
                    var url = $('selector').linkrequest.url;
                    url = url.split('/content/')[0] + '/content/manage_tree' + url.split('/manage_tree')[1];
                    window.setTimeout("$('selector').linkrequest.cancel().get('" + url + "');", 100);
                }
                else {
                    // seems like we already came to that conclusion, so stop trying to reload for now
                    $('selector').getElements('.browserloading').removeClass('browserloading');
                }
            }
            else {
                $('selector').getElements('.browserloading').removeClass('browserloading');
            }
            selectorIE7Fix();
            initSelectorLinks()
        }
    }).get(url);
    browser.linkrequest.url = url;
}

function initSelectorLinks() {
    if($('selector')) {
        $('selector').getElements('a.cms_selector_create_link').each(function(a) {
            a.removeEvents('click').addEvent('click', function(e) {
                new Event(e).stop();
                CreateLink(this, this.href);
            });
        });
        $('selector').getElements('a.cms_selector_choose_url').each(function(a) {
            a.removeEvents('click').addEvent('click', function(e) {
                new Event(e).stop();
                chooseURL(this.href);
            });
        });
        // disable all dragging of links into texteditor
        $$('#selector a').each(function(a) {
            a.removeEvents('mousedown').addEvent('mousedown', function(e) {
                return false;
            });
        });
    }
}

function selectorIE7Fix() {
    if(navigator.userAgent.indexOf('MSIE 7') == -1 && navigator.userAgent.indexOf('MSIE 8') == -1)
        return;
    if($('selector')) {
        $('selector').getElements('a').each(function(a) {
            a.removeEvents('click').addEvent('click', function(e) {
                var event = new Event(e).stop();
                var onclick = this.onclick;
                if(onclick) {
                    if(onclick.indexOf('chooseURLorImage') > -1) {
                        var spliturl = onclick.split("chooseURLorImage(this, '");
                        var spliturl = spliturl[1].split("')")[0];
                        chooseURLorImage(this, spliturl);
                    }
                    else if(onclick.indexOf('chooseURL') > -1) {
                        var spliturl = onclick.split("chooseURL('");
                        var spliturl = spliturl[1].split("')")[0];
                        chooseURL(spliturl);
                    }
                    else if(onclick.indexOf('showTree') > -1) {
                        var spliturl = onclick.split("showTree(this, '");
                        var spliturl = spliturl[1].split("')")[0];
                        showTree(this, spliturl);
                    }
                    else if(onclick.indexOf('CreateLink') > -1) {
                        var spliturl = onclick.split("CreateLink(this, '");
                        var spliturl = spliturl[1].split("')")[0];
                        CreateLink(this, spliturl);
                    }
                }
                if(this.href.indexOf('closeBrowser') > -1) {
                    closeBrowser();
                }
            });
        });
    }
}

function closeBrowser() {
    $('selector').setStyle('display', 'none');
    if($('selector').opener)
        $('selector').opener.removeClass('active');
}

function showSelectOptions(obj, id) {
    obj = $(obj);
    var browser = $('selector');
    if(!browser) {
        browser = new Element('div');
        browser.inject(document.getElement('body'), 'bottom');
    }

    browser.addClass('select_options');
    browser.innerHTML = $(id).innerHTML;
    browser.contentID = id;
    browser.getElement('textarea').addEvent('keyup', function() {
        $( $('selector').contentID ).getElement('textarea').innerHTML = this.get('value');
    });

    browser.set('id', "selector");
    browser.setStyles({
        position: "absolute",
        top: obj.getTop() + 'px',
        left: (obj.getLeft()+obj.getWidth()+2) + 'px',
        width: 500 + 'px',
        height: 1 + 'px',
        display: 'block',
        overflow: 'hidden'
    });

    if(obj.getLeft() + obj.getWidth() + 500 > document.body.offsetWidth) {
        browser.setStyles({
            top: obj.getTop() + obj.getHeight() + 2,
            left: document.body.offsetWidth - 520
        });
    }

    browser.setStyle('width', 1);

    var morph = new Fx.Morph(browser, {
            duration: 250
        }).start({
            width: 500,
            height: 400
        });

    if(browser.opener)
        browser.opener.removeClass('active');

    if(browser.opener)
        browser.opener.removeClass('active');

    if(obj.getParent('label')) {
        browser.opener = obj.getParent('label');
        browser.opener.addClass('active');
    }
}

function closeSelectOptions() {
    $( $('selector').contentID ).getElement('textarea').innerHTML = $('selector').getElement('textarea').get('value');
    $('selector').setStyle('display', 'none');
    if($('selector').opener)
        $('selector').opener.removeClass('active');
}

function showTree(link, url) {
    var li = link.getParent();
    var existingDiv = li.getElement('div');

    if(existingDiv != null && existingDiv.get('class') == 'subtree') {
        existingDiv.destroy();
        link.removeClass('expanded');
    }
    else {
        var div = new Element('div');
        div.addClass('subtree');
        div.inject(li);
        var request = new Request.HTML({
            update: div,
            onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                this.link.removeClass('loading');
                if(div.getElements('ul *').length) {
                    this.link.getPrevious().addClass('expanded');
                    div.getElements('span').each(function(span) {
                        if(span.innerHTML.length > 20) {
                            span.title = span.innerHTML.split('&amp;').join('&');
                            span.innerHTML = span.innerHTML.substr(0, 20) + ' ...';
                        }
                    });
                }
                else {
                    div.destroy();
                }
                selectorIE7Fix();
                initSelectorLinks();
            }
        }).get(url);
        link.getNext('a').addClass('loading');
        request.link = link.getNext('a');
    }
}

function chooseURLorImage(a, url) {
    // Show option to either add as image or link
    var img = a.getElementsByTagName('img')[0];
    var properties = img.title.split(' - ');
    var thumb_url = img.src; // remember thumbnail url
    a.url = url; // remember url to actual image

    removeZMSGraphicInterface();
    var interface = document.createElement('div');
    interface.id = "browser_zms_graphic_interface";
    interface.a = a;
    a.parentNode.appendChild(interface);
    interface.innerHTML = '<div style="background: url(' + thumb_url + ') no-repeat center center"></div>'
                    + '<a class="close" href="#">X</a>'
                    + '<span title="' + img.title + '">' + properties[0] + '<br/><i>' + properties[1] + '</i></span>'
                    + '<a href="#">Als Bild einfügen</a>'
                    + '<a href="#">Als Link einfügen</a>';

    var close = interface.getElementsByTagName('a')[0];
    var as_img = interface.getElementsByTagName('a')[1];
    var as_link = interface.getElementsByTagName('a')[2];
    as_img.clicker = a;
    as_link.clicker = a;

    as_img.onclick = function() {
        removeZMSGraphicInterface();
        CreateImage(this.clicker, this.clicker.url);
        return false;
    }
    as_link.onclick = function() {
        removeZMSGraphicInterface();
        CreateLink(this.clicker, this.clicker.url);
        return false;
    }
    close.onclick = function() {
        removeZMSGraphicInterface();
        return false;
    }
}

function removeZMSGraphicInterface() {
    var interface = document.getElementById('browser_zms_graphic_interface');
    if(interface)
        interface.a.parentNode.removeChild(interface);
}

function chooseURL(url) {
    if($('selector').opener) {
        var split_url = url.split('content/');
        split_url.shift();
        var input = $('selector').opener.getElement('input');
        if(input) {
            input.value = '{$' + split_url[0] + '}';
            closeBrowser();
        }
    }
}

/* File System Functions */
function fs_copy(del_origin, button) {
    if(!del_origin)
        del_origin = '';
    else
        del_origin = '&del_origin=1'; // cut

    var toCopy = new Array();
    var loc = window.location.pathname.replace('/manage', '/');
    $$('.selectionbox').each(function(el, i) {
        if(el.checked) {
            if(el.getParent('tr').getElement('.filename').innerHTML.indexOf('...') == 0)
                el.getParent('tr').getElement('.filename').innerHTML = el.getParent('tr').getElement('.filename').title;
            toCopy.push('&file=' + el.getParent('tr').getElement('.filename').innerHTML);
        }
    });

    Cookie.dispose('fs_copyobjects');

    if(toCopy.length > 0) {
        Cookie.write('fs_copyobjects', '&originloc=' + loc + toCopy.join('') + del_origin, { path: '/' });
        setPasteButton(1);
        showButtonResponse($(button));
    }
}

function fs_paste() {
    var pastestring = Cookie.read('fs_copyobjects');
    document.location.href = 'paste?' + pastestring;
}

function fs_del() {
    var toDel = "";
    $$('.selectionbox').each(function(el, i) {
        if(el.checked) {
            if(el.getParent('tr').getElement('.filename').innerHTML.indexOf('...') == 0)
                el.getParent('tr').getElement('.filename').innerHTML = el.getParent('tr').getElement('.filename').title;
            toDel += '&file=' + el.getParent('tr').getElement('.filename').innerHTML;
        }
    });

    if(toDel != "")
        document.location.href = 'delete?' + toDel + '&search=' + $('search').value;
}

function fs_rename() {
    var oldfilename = $('renamer_oldfilename').value;
    var filename = $('renamer_filename').value;
    var resp = $('renamer_response');

    if(filename == "") {
        resp.innerHTML = 'Filename must not be empty!';
    }
}

function fs_rename_close() {
    $('renamer').setStyle('display', 'none');
}

var replace_count = instance_count = 0;

function fs_global_search_replace(form) {
    if (form.searchtext.value && form.replacetext.value) {
        $$('.message, .replace_info').each(function(msg, i) {
            msg.destroy();
        });

        $('instance_count').innerHTML = $('replace_count').innerHTML = replace_count = instance_count = 0;

        $('instance_list').getElements('li').each(function(instance_item, i) {
           
            var instance_name = instance_item.getElement('a').innerHTML;

            if (!document.getElementById(instance_name)) {

                var myHTMLRequest = new Request.HTML({
                    url: instance_item.getElement('a').href,
                    onComplete: function(tree, eles, html, js) {
                        var results       = false;
                        var replace_info  = new Element('div', {
                            'class': 'replace_info',
                            id:    instance_name,
                            html:  '<span>' + instance_name + '</span>'
                        });
                        var replace_table = new Element('table', { html: '<tbody></tbody>' });
                        var replace_conf  = new Element('span',  { html: 'ersetzen', 'class': 'confirm' });
                        var replace_form, form_el;

                        eles.each(function(el) {
                            if (el.id == 'replace_form') {
                                replace_form = new Element('form',  { method: 'post', action: el.action });
                                new Element('input', { type: 'hidden', name: 'confirm',     value: '1' }).inject(replace_form);
                                new Element('input', { type: 'hidden', name: 'searchtext',  value: form.searchtext.value  }).inject(replace_form);
                                new Element('input', { type: 'hidden', name: 'replacetext', value: form.replacetext.value }).inject(replace_form);
                            }
                            else if (el.id == 'replace_results') {
                                el.getElements('tr').each(function(row_el) {
                                    if (row_el.getParent().get('tag') != 'thead') {
                                        row_el.inject(replace_table.getElement('tbody'));
                                        results = true;
                                    }
                                });
                            }
                        });
                        if (!results) {
                            var msg = new Element('div', { 'class': 'message', html:  'keine Treffer' });
                            msg.inject(replace_info);
                        }
                        else {
                            instance_count++;
                            $('instance_count').innerHTML = instance_count;

                            replace_table.inject(replace_form);
                            replace_conf.inject(replace_info);
                            replace_form.inject(replace_info);

                            replace_info.getElement('span.confirm').addEvent('click', function(event) {
                                fs_confirm_global_search_replace(instance_name);
                            });
                        }                        
                        replace_info.inject($('instance_container'));
                    }
                }).post(form);
            }
        });
    }  
  
    return false;
}

function fs_confirm_global_search_replace(instance) {
    var instances = new Array();
    if (instance) {
        instances.push(document.getElementById(instance));
    }
    else {
        instances = $('instance_container').getElements('.replace_info');
    }
    
    instances.each(function(el) {
        var form = el.getElement('form');
        if (form) {
            var myHTMLRequest = new Request.HTML({
                url: form.action,
                onComplete: function(tree, eles, html, js) {
                    replace_count++;
                    $('replace_count').innerHTML = replace_count;
                    el.destroy();
                }
            }).post(form);
        }
        else {
            el.destroy();
        }
    });
}

/* CSS Color Changer */
var used_colors;
var allowedString = '0123456789abcdef';
function checkCSS() {
    var content = codemirror_editor.getCode();
    var results = $('results');
    if(!results) {
        results = new Element('form');
        results.id = 'results';
        results.inject($('ajax_editor'), 'after');
        results.addEvent('submit', function(e) {
            new Event(e).stop();
            replaceCSS();
        });
    }

    used_colors = parseCSSColors(content);

    var resultsHTML = '<b>Gefundene Farben:</b><table class="cms_color_table">';

    for(i=0;i<used_colors.length;i++)
        resultsHTML += '<tr><td class="left_td" style="background: #' + used_colors[i]['hex_code'] + ';"><span>&nbsp;</span></td><td class="color_td">' + used_colors[i]['orig_code'] + '</td><td class="right_td">Ersetzen:</td><td class="right_td"><input name="newcolor'+i+'" id="newcolor'+i+'" size="20"></td></tr>';

    resultsHTML += '</table>'
        + '<p><input type="submit" value="Ersetzen" title="Ersetzen [R]" accesskey="R">'
        + ' <input type="button" id="convert_to_rgb" onclick="replaceCSS(' + "'rgb'" + ')" value="Alle Farben in RGB umwandeln" />'
        + ' <input type="button" id="convert_to_hex" onclick="replaceCSS(' + "'hex'" + ')" value="Alle Farben in Hex umwandeln" /></p>';
    results.set('html', resultsHTML);

    return; // for now

    /** This is for later ... A full CSS explorer **/
    var comments = content.split('/*');
    for(i=0; i<comments.length; i++) {
            var end = comments[i].split('*/');
            if(end.length > 1) {
                    end.shift();
            }

            comments[i] = end.join('');
    }
    content = comments.join('');
    content = content.split('\n').join('');

    var dom = new Array();
    var splitcontent = content.split('{');
    for(i=0; i<splitcontent.length; i++) {
            dom[i] = new Object();
            var splitcom = splitcontent[i].split('}');
            if(splitcom.length > 1) {
                    dom[i]['selector'] = splitcom[1];

                    if(dom[i-1])
                            dom[i-1]['setting'] = splitcom[0];
            }
            else {
                    dom[i]['selector'] = splitcom[0];
            }
    }

    dom.pop();
    var cssTree = new Object();
    for(i=0; i<dom.length; i++) {
            //alert(dom[i]['selector'] + ' { \n ' + dom[i]['setting'] + ' } ');
            var selsplit = dom[i]['selector'].split(',');
            for(b=0; b<selsplit.length; b++) {
                    var selector = new Array();
                    var splitt = selsplit[b].split(' ');
                    for(c=0; c<splitt.length; c++) {
                            if(splitt[c] != "")
                                    selector.push(splitt[c]);
                    }
                    selsplit[b] = selector.join(' ');

                    if(cssTree[selsplit[b]] != undefined) {
                            cssTree[selsplit[b]] += dom[i]['setting'];
                    }
                    else {
                            cssTree[selsplit[b]] = dom[i]['setting'];
                    }

                    //alert(cssTree[selsplit[b]] + ' ' + selsplit[b] + ' ' + selsplit[b].length);
            }
    }

    var cssTreeHtml = "<table>";

    for(var el in cssTree) {
            cssTreeHtml += "<tr><td>" + el + "</td><td>" + cssTree[el] + "</td></tr>";
    }

    cssTreeHtml += "</table>";
    //$('results').innerHTML += cssTreeHtml;
}

function parseCSSColors(css) {
    var split_content = css.split('#');
    var colors = new Array();
    for(i=0;i<split_content.length;i++) {
        colorcode = split_content[i].substr(0,6);
        if(colorcode.length == 6) {
            valid_check = colorcode.split('');
            valid = 1;

            if(valid_check[3] ==  " " || valid_check[3] == ";") { //check for three bytes too
                while(valid_check.length > 3)
                    valid_check.pop();
            }

            for(b=0;b<valid_check.length;b++) //check if colorcode is valid hexcode
                if(allowedString.indexOf(valid_check[b].toLowerCase()) == -1)
                    valid = 0;

            colorcode = valid_check.join('');

            for(b=0;b<colors.length;b++) //check if color has already been added
                if(colors[b]['hex_code'] == colorcode)
                    valid = 0;

            if(valid) //add color
                colors.push({
                    hex_code: colorcode,
                    orig_code: '#' + colorcode
                });
        }
    }

    var rgb_colors = new Array();
    var rgb_types = new Array('rgb', 'rgba');
    for(t=0;t<rgb_types.length;t++) {
        split_content = css.split(rgb_types[t] + '(');
        for(i=0;i<split_content.length;i++) {
            var color_code = split_content[i].split(')')[0];
            if(color_code) {
                var original_color_code = color_code;
                color_code = color_code.replace(/ /g, '').split(',');
                var r = parseInt(color_code[0]).toString(16);
                var g = parseInt(color_code[1]).toString(16);
                var b = parseInt(color_code[2]).toString(16);
                if(!isNaN(color_code[0])) {
                    if (r.length == 1) r = '0' + r;
                    if (g.length == 1) g = '0' + g;
                    if (b.length == 1) b = '0' + b;
                    color_code = r + '' + g + '' + b;
                    var valid = 1;
                    for(b=0;b<colors.length;b++) { //check if color has already been added
                        if(colors[b]['hex_code'] == color_code) {
                            valid = 0;
                        }
                    }
                    if(valid) {
                        colors.push({
                            hex_code: color_code,
                            orig_code: rgb_types[t] + '(' + original_color_code + ')'
                        });
                    }
                }
            }
        }
    }
    return colors;
}

function replaceCSS(format) {
    if(!format)
        format = '';

    var css = codemirror_editor.getCode();

    for(i=0; i<used_colors.length; i++) {
        newvalue = $('newcolor'+i).value.toLowerCase();

        // check for auto format
        if(format && !newvalue) {
            newvalue = used_colors[i]['hex_code'];
        }

        if(format == 'rgb')
            newvalue = 'rgb(' + HexToRGB(newvalue) + ')';

        // check for hex
        if(newvalue.indexOf('#') > -1) {
            newvalue = newvalue.replace('#', '');
        }

        valid_check = newvalue.split('');
        valid = 1;
        for(b=0;b<valid_check.length;b++) //check if colorcode is valid hexcode
            if(allowedString.indexOf(valid_check[b].toLowerCase()) == -1)
                valid = 0;

        if(valid && (newvalue.length == 3 || newvalue.length == 6)) { //change
            css = css.split(used_colors[i]['orig_code'] + ';').join('#' + newvalue + ';');
            css = css.split(used_colors[i]['orig_code'] + ' ').join('#' + newvalue + ' ');
            css = css.split(used_colors[i]['orig_code'] + '\n').join('#' + newvalue + '\n');
            css = css.split(used_colors[i]['orig_code'] + '!').join('#' + newvalue + '!');
        }

        // check for rgb
        if(newvalue.indexOf('(') > -1 && newvalue.indexOf(')') > -1 && (newvalue.indexOf('rgb') > -1 || newvalue.indexOf('rgba') > -1)) {
            css = css.split(used_colors[i]['orig_code']).join(newvalue);
        }
    }

    codemirror_editor.setCode(css);
    checkCSS();
    return false;
}

function giveDec(Hex) {
    if(Hex == "A")
        Value = 10;
    else
    if(Hex == "B")
        Value = 11;
    else
    if(Hex == "C")
        Value = 12;
    else
    if(Hex == "D")
        Value = 13;
    else
    if(Hex == "E")
        Value = 14;
    else
    if(Hex == "F")
        Value = 15;
    else
        Value = eval(Hex)
    return Value;
}

function HexToRGB(hex) {
    var orig_hex = hex;
    hex = hex.toUpperCase();

    if(hex.length == 3) {
        var hex_1 = hex.substring(0, 1);
        var hex_2 = hex.substring(1, 2);
        var hex_3 = hex.substring(2, 3);
        hex = hex_1 + '' + hex_1 + '' + hex_2 + '' + hex_2 + '' + hex_3 + '' + hex_3;
    }

    if(hex.length != 6)
        return orig_hex;

    var a = giveDec(hex.substring(0, 1));
    var b = giveDec(hex.substring(1, 2));
    var c = giveDec(hex.substring(2, 3));
    var d = giveDec(hex.substring(3, 4));
    var e = giveDec(hex.substring(4, 5));
    var f = giveDec(hex.substring(5, 6));

    var x = (a * 16) + b;
    var y = (c * 16) + d;
    var z = (e * 16) + f;

    return x + ',' + y + ',' + z;
}

/* Mootools Popup */
function showHTMLPopup(html, onCompleteFunction) {
    $(document.body).removeEvents('keydown').addEvent("keydown", function(event) {
        if(event.key == "esc") {
            closeHTMLPopup();
        }
    });

    var popupcontainer = $('popupcontainer');
    if(!popupcontainer) {
        popupcontainer = new Element('div').inject(document.body, 'bottom');
        popupcontainer.id = 'popupcontainer';
    }

    popupcontainer.setStyles({
        position: 'fixed',
        top: '0',
        left: '0',
        right: '0',
        bottom: '0',
        background: 'black',
        opacity: '0',
        zIndex: '100000'
    });

    if(navigator.userAgent.indexOf('MSIE 6') > -1) {
        popupcontainer.setStyles({
            position: 'absolute',
            width: document.getWidth(),
            height: document.getHeight(),
            top: $(document.body).getScroll().y
        });
    }

    popupcontainer.html = html;
    popupcontainer.html += '<a class="close" href="javascript:closeHTMLPopup()"><span>X</span></a>';
    popupcontainer.onCompleteFunction = onCompleteFunction;
    popupcontainer.innerHTML = "";
    var fx = new Fx.Morph(popupcontainer, {
        duration: 500,
        wait: false,
        onComplete: function() {
            var popupcontent = $('popupcontent');
            if(!popupcontent) {
                popupcontent = new Element('div').inject(document.body, 'bottom');
                popupcontent.id = 'popupcontent';
            }
            popupcontent.setStyles({
                border: '2px solid gray',
                position: 'fixed',
                top: '50%',
                left: '50%',
                padding: 20,
                zIndex: popupcontainer.getStyle('zIndex')+1,
                opacity: 0,
                background: 'white',
                visibility: 'hidden'
            });

            popupcontent.innerHTML = popupcontainer.html;
            var close = popupcontent.getElement('.close');
            if(close) {
                close.addEvent('mouseover', function() {
                    this.setStyle('opacity', 0.5);
                });
                close.addEvent('mouseout', function() {
                    this.setStyle('opacity', 1);
                });
            }
            popupcontent.origHeight = popupcontent.getHeight(); //save for later
            popupcontent.origWidth = popupcontent.getWidth();

            popupcontent.setStyles({
                marginTop: 0-Math.round(popupcontent.getHeight()/2),
                marginLeft: 0-Math.round(popupcontent.getWidth()/2),
                visibility: 'visible',
                overflow: 'auto'
            });
            var aphex = new Fx.Morph(popupcontent, {
                duration: 500,
                wait: false,
                onComplete: function() {
                    popupcontainer.addEvent('click', function() {
                        closeHTMLPopup();
                    });
                }
            }).start({
                opacity: 1
            });

            var images = popupcontent.getElements('img');
            images.each(function(img, i) {
                img.addEvent('load', function() {
                    if(this.getHeight()+250 > document.body.offsetHeight) {
                        this.setStyle('height', document.body.offsetHeight - 250);
                    }
                    else if(this.getWidth()+50 > document.body.offsetWidth) {
                        this.setStyle('width', document.body.offsetWidth - 50);
                    }

                    $('popupcontent').origHeight = $('popupcontent').getHeight();
                    $('popupcontent').origWidth = $('popupcontent').getWidth();
                    resizeHTMLPopup();
                });
                img.setStyles({
                    cursor: 'pointer'
                });
                img.addEvent('click', function() {
                    closeHTMLPopup();
                });
            });

            if(popupcontainer.onCompleteFunction)
                popupcontainer.onCompleteFunction();

            if(navigator.userAgent.indexOf('MSIE 6') > -1) {
                popupcontent.setStyles({
                    position: 'absolute',
                    marginTop: 0,
                    top: $(document.body).getScroll().y + (document.body.offsetHeight / 2)  - (popupcontent.getHeight() / 2)
                });
            }
        }
    }).start({
        opacity: '0.4'
    });
}

function closeHTMLPopup() {
    [$('popupcontainer'), $('popupcontent')].each(function(el, i) {
        if(el) {
            el.removeEvents('click');
            var fx = new Fx.Morph(el, {
                duration: 500,
                wait: false,
                onComplete: function() {
                    if($('popupcontent'))
                        $('popupcontent').destroy();
                }
            }).start({
                opacity: 0
            });
        }
    });
}

function resizeHTMLPopup() {
    var popupcontent = $('popupcontent');
    var popupcontainer = $('popupcontainer');
    if(popupcontent) {
        var styles = new Object();
        if((popupcontent.getHeight()+100) > document.body.offsetHeight) {
            styles['overflow'] = 'hidden',
            styles['height'] = (document.body.offsetHeight - 100 - popupcontent.getStyle('padding').toInt() - 40);
        }
        else {
            styles['height'] = popupcontent.origHeight - 40;
        }

        if((popupcontent.getWidth()+100) > document.body.offsetWidth) {
            styles['overflow'] = 'hidden',
            styles['width'] = (document.body.offsetWidth - 100 - popupcontent.getStyle('padding').toInt() - 40);
        }
        else {
            styles['width'] = popupcontent.origWidth - 40;
        }

        styles['marginTop'] = 0-Math.round(styles['height']/2);
        styles['marginLeft'] = 0-Math.round(styles['width']/2);

        var aphex = new Fx.Morph(popupcontent, {
            duration: 500,
            wait: false,
            onComplete: function() {
            }
        }).start(styles);

        if(navigator.userAgent.indexOf('MSIE 6') > -1) {
            popupcontainer.setStyles({
                top: $(document.body).getScroll().y,
                width: document.body.getWidth(),
                height: document.body.getHeight()
            });
            popupcontent.setStyles({
                top: $(document.body).getScroll().y + (document.body.offsetHeight / 2)  - (popupcontent.getHeight() / 2),
                left: $(document.body).getScroll().x + (document.body.offsetWidth / 2)  - (popupcontent.getWidth() / 2),
                marginTop: 0
            });
        }
    }
}

window.addEvent('resize', function() {
    adjustTableEditor();
    //resizeHTMLPopup();
    movePanel();
});
window.addEvent('scroll', function() {
    //resizeHTMLPopup();
});

function check_all(form) {
    inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'checkbox')
            inputs[i].checked = 'checked';
    }
}

/* Login */

window.addEvent('domready', function() {
    if($('login')) {
        $(document.body).addClass('login');
        $('fancytitle').setStyle('display', 'block');
        var title = $('fancytitle').getElement('div');
        // go through each letter and wrap it in a span
        var kids = title.getChildren('span');
        kids.each(function(t, i) {
            var splithtml = t.innerHTML.split('');
            t.innerHTML = "";
            splithtml.each(function(letter) {
                var span = new Element('span');
                span.innerHTML = letter;
                span.inject(t);
                span.addClass('letter');
            });
        });

        title.getElements('.letter').each(function(let, i) {
            let.setStyles({
                opacity: 0,
                marginLeft: '50px'
            });
        });

        fadeInTitleLetters();

        new Fx.Morph($('login'), {
                duration: 500
        }).start({
            opacity: [0, 1]
        });

        new Fx.Morph($('login_bg'), {
                duration: 1000
        }).start({
            left: 0,
            right: 0,
            opacity: [0, 1]
        });

        if(!Browser.Engine.trident) {
            $$('.cms3k span').setStyle('fontStyle', 'italic');
        }

        $('login').getElement('input').focus();
    }
});

var currentTitleLetter = 0;
function fadeInTitleLetters() {
    var letters = $('fancytitle').getElements('.letter');
    if(currentTitleLetter < letters.length) {
        var morph = new Fx.Morph(letters[currentTitleLetter], {
                duration: 500
        }).start({
            opacity: 1,
            marginLeft: 0
        });
        currentTitleLetter++;
    }
    window.setTimeout('fadeInTitleLetters()', 100);
}

function toggle_dtml_example(index, link) {
    var example_div = $('dtml_example_' + index);
    var visible = example_div.getStyle('display');

    $$('.dtml_example').setStyles({ display: 'none' });

    if (visible == 'none' && link) {
        var position = $(link).getPosition();
        example_div.setStyles({
            display: 'block',
            top: (position.y + 25) + 'px',
            right: '20px'
        });
    }
}

// CTRL+F fix for selections that are out of bounds due to blue bars in interface
function getSelectionObj() {
    var obj;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.rangeCount) {
            // see if selection even contains anything, sometimes it's empty
            // have to create a cloned element for this according to Sir Google
            var frag = sel.getRangeAt(0).cloneContents();
            var el = document.createElement("div");
            el.appendChild(frag);
            html = el.innerHTML;
            $(el).destroy();

            if(html.length) {
                var range = sel.getRangeAt(0);
                obj = range.startContainer.parentNode;
            }
        }
    } else if (document.selection && document.selection.type == "Text") {
        // IE
        obj = document.selection.createRange().parentElement();
    }
    return obj;
}

var selectioncounter = 0; // we give each object with selections a unique number so that we can see when new selection was made easily
window.setInterval(function() {
    var selection = getSelectionObj();
    if(selection) {
        var scrollnow = false;
        if(!selection.counter) {
            selectioncounter++;
            selection.counter = selectioncounter;
            scrollnow = true;
        }
        else {
            if(selection.counter < selectioncounter) {
                // old selection is new again
                selectioncounter++;
                selection.counter = selectioncounter;
                scrollnow = true;
            }
        }

        if(scrollnow) {
            var scrolled = $(document.body).getScroll().y;
            var selection_y = $(selection).getTop();

            if(selection_y < scrolled + 100) {
                window.scrollTo(0, selection_y - 100);
            }
            else if(selection_y > scrolled + $(document.body).getHeight() - 100) {
                window.scrollTo(0, selection_y - $(document.body).getHeight() + 100);
            }
        }
    }
}, 1000);

