/* CONTENTS

1. Browserweiche

2.1 Fenster oeffnen(width*height)
 openAlertWindow(url, name) (300*250)
 openXSWindow(url, name) (300*150)
 openSWindow(url, name)(530*180)
 openSMWindow(url, name)(530*240)
 openBigInfoWindow(600*600)
 openMWindow(url, name)(530*300)
 openLWindow(url, name)(530*400)
 openBWindow(url, name) (650*400)
 openBigInfoWindow(url, name) (600*600)
 openSpecialWindow(url, name)(824*600)
 openSpecialWindowVC(url,name)(800*600)
 openBigResizableWindow(url, name) (850*600)
 openPerspectiveWindow(url,name)   (900x700)(
 openSelectWindow(url, name)(530*600) (Auswahlfenster)
 openCalendarSpecialWindow(url, name, scrolling) (um den Kalender ohne scrollen oeffnen zu koennen)
 CenterWindow  (zentriert ein Fenster,Beispiel in openLoginWindow)
 toGuestBook(id) (700x500);

2.2 Fenster oeffnen mit bestimmter url

mediaPlayer(fileName, width, height) (/qti/task/wizard/mediaplayer.jsp)
openUpload() (upload/uploadform.jsp)
openComponent() (/servlet/de.imc.clix.control.Clix?clixEvent=open-ecomponent)
openProfile(id) (/servlet/de.imc.clix.control.Clix?clixEvent=profileViewEvent)
setRefInUpperwork(Fensterreferenz) (schreibt Referenz des Fensters in upperwork.jsp -> Fenster werden geschlossen, wenn Navigation wechselt)
openChooseSkill(container,context,levelType,schedulingDisabled,comment,partner,name) (/servlet/de.imc.clix.control.Clix?clixEvent=chooseSkill)
openEditSkill(skillId,container,context,levelType,schedulingDisabled,comment,partner,name) (/servlet/de.imc.clix.control.Clix?clixEvent=chooseSkillLevel&edit=true)

3. Layer Funktionalitaeten

 openCloseAlert() (blendetLayer ein und aus)
 showHideLayers() (wird fuer openCloseAlert() gebraucht)
 findObj(n, d) (wird fuer showHideLayersde() gebraucht)
 setLayerToCenter(layerName,width)
 closeAlerts(alertLayerArray) (schliesst alle offenen Layer)
 hidealllayers() (laesst alle Layer im frame verschwinden)
 moveLayer(layerName,toppos,leftpos)
 showInfoLayer(nr,event)
 hideInfoLayer()

4. Formulare
 submitFormular(action,target,method,formname) (Formular verschicken)
 getFirstCheckedBoxof(formId, boxName) (Findet die erste gecheckte Box und gibt das Checkboxobjekt zur?ck)
 getCheckboxElements(formId, boxName) (Finds all boxes and returns the element list)
 getCheckedBoxElements(formId, boxName) (finds all checked boxes and returns the element list)
 getUncheckedBoxElements(formId, boxName) (finds all unchecked boxes and returns the element list)
 getCheckboxElementsByStatus(formId, boxName, checked) (Finds all boxes and returns the element list; with parameter 'checked=true' you can get only checked elements or unchecked ones)
 getCheckboxIds(formId, boxName) (finds all check boxes and returns the id list)
 getCheckedBoxIds(formId, boxName) (finds all checked boxes and returns the element ids)
 getUnCheckedBoxIds(formId, boxName) (finds all unchecked boxes and returns the element ids)
 getCheckboxIdsByStatus(formId, boxName, checked) (finds all check boxes and returns the id list)
 getCheckBoxIds(formID, boxName, checked) (Finds all boxes and returns a array; with parameter 'checked=true' you can get only checked elements or all))
 checkAllBoxesof(formID, boxName) (this method checks all boxes with boxName in form with id formId)
 uncheckAllBoxesof(formID, boxName) (this method unchecks all boxes with boxName in form with id formId)
 nolinebreak(formname,elemname) (Zeilenumbrueche entfernen)


Diverse
setTimestamp(url) (schraubt dummy an url)
reloadLocation (f�gt einen JS-Timestamp an die �bergebene URL an und l�d die URL im �bergebenen window)
setCursorClass(link,flag)  (Cursor aendern)
closeMenuItem() (Navi schliessen)
nothing()  // leer
showHelp(target)  // �ffnet die Onlinehilfe
countSigns(s1_t, s2_t) // counts sign like <br> in a given string

TODO: Mark or unmark functions as deprecated where their states are known.
*/
var Loadcontrol = false;
var IE = false;
var N4 = false;
var N6 = false;
var useExt = true;

if (typeof contextPath == "undefined") contextPath = "/clixHACK"; // HACK

/**
 * ClixUtils is a container object for various functions and other objects
 * that are of general interest.
 */
ClixUtils = {
    /* constants, do not modify */
    ProcessId: "procId",
    IgnoreProcId: true,
    IgnoreTimestamp: true,
    TimestampParam: "dmy",
    ClixEvent: "clixEvent",
    /* may vary, see baseURI function */
    BaseURI: contextPath + '/servlet/de.imc.clix.control.Clix?',

    /**
     * Overwrites ClixUtils.BaseURI with given parameter (or, if not given, with contextPath value).
     * @param {String} cp
     * @return ClixUtils.BaseURI (reset value)
     */
    baseURI: function(cp) {
        if (!cp) cp = contextPath;
        ClixUtils.BaseURI = cp + '/servlet/de.imc.clix.control.Clix?';
        return ClixUtils.BaseURI;
    },

    /**
     * Appends given parameters to given url.
     * Called as ClixUtils.genericAppendParameters(...).
     * Appends procId when needed.
     * Without set url, a default base url is used (for call of CLIX servlet).
     * @param {String} url - URL, context path is not needed, as it is prepended when required
     * @param {Object} parameters - JSON object with parameters to be submitted, e.g. {name1:"value1",name2:"value2"}
     * @param {boolean} ignoreTimestamp (optional) - ignored, please set it to false
     * @param {boolean} ignoreProcId (optional) - when true, no (additional) procId parameter is appended,
     *  even if it is submitted via "parameters"
     */
    genericAppendParameters: function(url, parameters, ignoreTimestamp, ignoreProcId) {
        var uri = new ClixUtils.UriObject(url, parameters);
        var isFullUrl = uri.hasAbsolutePath();
        if (!isFullUrl) {
            uri.addDmy();
            var procId = uri.getParameterValue(ClixUtils.ProcessId);
            if (procId == null && !ignoreProcId) {
                if (typeof processId != "undefined") {
                    // use existing procId (see ScriptTag for var processId)
                    procId = processId;
                } else {
                    // generate new procId
                    //procId = generateIdentifier("dummy", "dummy", true);
                    alert("Error: procId is missing (clixscriptsv4.js)!");
                }
            } else {
                if (Ext.isArray(procId)) {
                    // let procId be unique by deleting all values except 'the first'
                    procId = procId[0];
                }
            }
            if (procId != null) {
                uri.setParameter(ClixUtils.ProcessId, procId);
            } else if (typeof processId != "undefined") {
                uri.setParameter(ClixUtils.ProcessId, processId);
            }
        }
        return uri.toString();
    },

    /**
     * Appends given parameters to given url.
     * @param {String} url - URL, context path is not needed, as it is prepended when required
     * @param {Object} parameters - JSON object with parameters to be submitted, e.g. {name1:"value1",name2:"value2"}
     * a timestamp and processId are appended
     */
    appendParameters: function(url, parameters) {
        return ClixUtils.genericAppendParameters(url, parameters, ClixUtils.IgnoreTimestamp, ClixUtils.IgnoreProcId);
    },

    /**
     * Appends given parameters to given url without
     * @param {String} url - URL, context path is not needed, as it is prepended when required
     * @param {Object} parameters - JSON object with parameters to be submitted, e.g. {name1:"value1",name2:"value2"}
     * a timestamp and processId are NOT appended
     */
    createUrl: function(url, parameters) {
        return ClixUtils.genericAppendParameters(url, parameters);
    },

    /**
     * Convenience function to create an URL like /clix/servlet/de.imc.clix.control.Clix?clixEvent=eventName&...
     */
    createEventUrl: function(eventName, parameters) {
        if (!parameters) parameters = {};
        parameters[ClixUtils.ClixEvent] = eventName;
        return ClixUtils.genericAppendParameters(null, parameters);
    },

    /**
     * Loads a new page given by url into win.
     * @param {Object} win - target window
     * @param url - normally a page url, but it is allowed to let url be a javascript function to be called
     * @param {Object} parameters - optional parameter object
     */
    redirect: function(win, url, parameters) {
        if (typeof win == "string") {
            var target = window;
            var path = win.split(".");
            for (var i = 0; i < path.length; ++i) {
                target = target[path[i]] || target;
                ClixUtils.debuglog("Set target", target.name);
            }
            win = target;
        }
        if (typeof url == "function") {
            // redirection target is a JS function call, used e.g. in program manager
            url.call();
        } else if (typeof url == "string" && url.toLowerCase().indexOf("javascript:") >= 0) {
            // redirection target is a JS function call wrapped within a string
            eval(url);
        } else if (url instanceof ClixUtils.UriObject) {
            win.location.href = url.toString();
        } else {
            win.location.href = ClixUtils.createUrl(url, parameters);
        }
    },

    /**
     * Convenience function to redirect to a given event
     */
    redirectEvent: function(win, eventName, parameters) {
        if (!parameters) parameters = {};
        parameters[ClixUtils.ClixEvent] = eventName;
        ClixUtils.redirect(win, null, parameters);
    },

    /**
     * Wrapper for FORM elements.
     * Appends dmy and procId parameters, when <code>submit</code> is called.
     * Adds missing form elements automatically.
     * Usage example:
     * <pre>
     *  var f = new ClixUtils.Form(document.forms[0], { param1: "value1", param2: "value2" });
     *  f.submit();
     * </pre>
     */
    Form: function(form, parameters, action, target) {
        this.form = form;
        if (!this.form) {
            alert("No form element found!");
            return;
        }
        if (target) {
            this.form.target = target;
        }
        this.target = form.target;
        if (action) {
            this.form.action = action;
        }
        if (!this.form.action || this.form.action == "") {
            // set default action to CLIX servlet
            this.form.action = ClixUtils.BaseURI;
        }
        this.action = this.form.action;
        this.method = this.form.method;
        this.setParameters(parameters);
    },

    /**
     * This 'class' is a kind of sibling for the Java class de.imc.java.util.UriObject
     * and works very similar.
     * @param url some URL, may contain a query (e.g. "demo/test.jsp?p=2&q=demo")
     * @param params JS object with parameter definition
     */
    UriObject: function(url, params) {
        if (!url) {
            url = ClixUtils.BaseURI;
        }
        if (url.indexOf("/") == 0 && url.indexOf(contextPath) < 0) {
            url = contextPath + url;
        }
        if (url.indexOf("?") < 0) {
            url += "?";
        }
        if (!params) {
            params = {};
        }
        var query = url.substring(url.indexOf("?") + 1);
        this.uri = url.substring(0, url.indexOf("?"));
        this.params = params;
        this.addParameters(query);
    },

    /**
     * Writes debug output to console, when console object exists
     * (e.g., for use with Firebug)
     */
    debuglog: function() {
        if (typeof console == "object") {
            // this strange code is needed for IE 8 script debugger,
            // for FF a "console.log(arguments)" would suffice
            var a = [];
            for (var i = 0; i < arguments.length; ++i) {
                a[i] = arguments[i];
            }
            console.log(a);
        }
    },

    /**
     * Window (Popup) management functions
     */
    Window: {
        /**
         * Default parameters for standard popup window settings
         */
        Params: {
            S:            'width=530,height=180,top=100,left=100,resizable=no,dependent=no,scrollbars=no',
            SM:           'width=530,height=240,top=100,left=100,resizable=no,dependent=no,scrollbars=no',
            M:            'left=100,top=100,width=530,height=300,resizable=no,dependent=no,scrollbars=no',
            L:            'left=100,top=100,width=530,height=400,resizable=no,dependent=no,scrollbars=1',
            Special:      'width=900,height=600,top=50,left=100,resizable=yes,dependent=no,scrollbars=',
            Calendar:     'width=860,height=600,top=50,left=100,resizable=yes,dependent=no,scrollbars=',
            VC:           'width=800,height=600,top=50,left=100,resizable=yes,dependent=no,scrollbars=1,directories=yes',
            BigResizable: 'left=50,top=50,width=850,height=600,resizable=yes,dependent=no,scrollbars=1',
            Alert:        'top=200,left=400,width=300,height=250,resizable=no,dependent=no,scrollbars=no',
            XS:           'top=200,left=400,width=300,height=150,resizable=no,dependent=no,scrollbars=no',
            B:            'width=650,height=400,resizable=no,dependent=no,scrollbars=1',
            BigInfoNoResizable:   'width=600,height=600,top=50,left=100,resizable=no,dependent=no,scrollbars=1',
            BigInfoResizable:     'width=600,height=600,top=50,left=100,resizable=yes,dependent=no,scrollbars=1',
            Login:        "resizable=no,dependent=no,scrollbars=no",
            ComponentIE:  'top=50,left=50,width=850,height=600,resizable=yes,scrollbars=auto',
            Component:    'top=50,left=50,width=850,height=600,resizable=yes,scrollbars=auto',
            WBT:          'width=800,height=600,top=100,left=200,resizable=yes,scrollbars=yes,toolbar=yes,status=yes',
            NewWindowIE:  'top=200,left=150,toolbar=no,location=no,status=no,menubar=no,resizable=yes,scrollbars=auto,directories=no,width=650,height=400',
            NewWindow:    'toolbar=no,location=no,status=no,menubar=no,resizable=yes,scrollbars=auto,directories=no,width=650,height=400',
            External:     'width=700,height=460,left=150,top=110,scrollbars=1,location=yes,menubar=yes,status=yes,toolbar=yes,resizable=yes',
            Info:         'width=400,height=600,resizable=yes, dependent=yes,scrollbars=yes',
            HtmlUpload:   'width=800,height=600,top=50,left=100,resizable=yes,dependent=no,scrollbars=yes',
            Profile:      'width=900,height=600,top=50,left=100,resizable=yes,dependent=no,scrollbars=no',
            UserInfo:     'width=650,height=400,resizable=no,dependent=no,scrollbars=1',
            Select:       'left=100,top=100,width=530,height=600,resizable=yes,dependent=no,scrollbars=1',
            ChooseSkill:  'width=600,height=600,top=50,left=100,resizable=auto,dependent=no,scrollbars=1',
            Testplayer:   'width=840,height=540,top=50,left=100,resizable=yes,dependent=no,scrollbars=1'
        },

        /**
         * Opens a new window
         * @param uri - ClixUtils.UriObject instance or String object, should be not null
         * @param {String} name - window name, defaults to "clixWindow"
         * @param {String} strParams - parameters for window.open (window parameters)
         * @param {Function} callback - an optional callback function to open a window, defaults to window.open (try e.g. parent.window.open)
         * @param (boolean) withoutReference Don�t store the reference in Upperwork
         * @return new window object
         */
        open: function(uri, name, strParams, callback, withoutReference) {
            var clixWindow;
            if (name == null) {
                name = "clixWindow";
            }
            if (uri == null || (typeof uri == "string" && uri.length > 0
                    && uri.toLowerCase().indexOf("javascript:") < 0)) {
                uri = ClixUtils.UriObject.createUri(uri);
            }
            if (typeof callback != "function") {
                callback = window.open;
            }
            ClixUtils.debuglog("Opening " + uri);
            clixWindow = callback(uri, name.replace(/[^a-zA-Z0-9]/g, 'x'), strParams);
            // The 'replace' is needed because IE fails when name contains e.g. ':'.
            clixWindow.focus();
            if (typeof (withoutReference) == 'undefined' || withoutReference == false) {
                setRefInUpperwork(clixWindow);
            }
            return clixWindow;
        },

        /**
         * Closes the given window.
         * Use this function to close a window, especially in all
         * cases where the original close function is overwritten.
         * Usage example: ClixUtils.Window.close(window)
         * @param window - window (or frame) object
         */
        close: function(window) {
            ClixUtils.debuglog("close", window);
            var refUpperframe = findUpperwork();
            if (refUpperframe && refUpperframe.newwindowArray) {
                refUpperframe.newwindowArray.remove(window);
            }
            var t = typeof window.originalCloseFunction;
            if (IE) {
                if (t == "function" || t == "object") {
                    // see ScriptTag.java; function reference is created within script tag;
                    // note that type of original close is generally "function",
                    // but in IE it is "object" (or "unknown" when window is already closed)
                    window.originalCloseFunction();
                }
                // else window seems to be already closed, nothing is to be done
            } else {
                if (window.Window && window.Window.prototype) {
                    // this will not work in IE
                    window.Window.prototype.close.call();
                } else {
                    // fallback, will not work if close is overwritten
                    window.close();
                }
            }
        },

        /**
         * Opens a new window, see also ClixUtils.Window.open()
         * and ClixUtils.UriObject.createEventUri()
         */
        openEvent: function(event, parameters, name, strParams) {
            var uri = ClixUtils.UriObject.createEventUri(event, parameters);
            return ClixUtils.Window.open(uri, name, strParams);
        }
    },

    /**
     * MessageBox provides a kind of manager for alert messages.
     */
    MessageBox: {
        /**
         * Storage for config objects that define alert messages
         */
        Store: {},
        /**
         * Storage for Ext.Window objects
         */
        CmpStore: {},
        /**
         * Opens an alert message named 'obj'
         */
        open: function(obj) {
            showObject(obj, "show");
        },
        /**
         * Closes an alert message named 'obj'
         */
        close: function(obj) {
            showObject(obj, "hide");
        }
    },

    toBoolean : function(value){
        var result = false;
        if(typeof value == 'string'){
            result = 'true' == value.toLowerCase();
        }else if(typeof value == 'number'){
            result = value > 0;
        }else {
            result = value;
        }
        return result;
    }
};

/**
 * Factory function to create a ClixUtils.Form object with given formName
 * @param {String} formName - name of an existing form
 */
ClixUtils.Form.create = function(formName, parameters, action, target) {
    var form = ClixUtils.Form.findForm(formName);
    var obj = new ClixUtils.Form(form, parameters, action, target);
    return obj;
};

/*ClixUtils.Form.createDummy = function(formHtml, parameters, action, target) {
    var form = Ext.getBody().insertHtml("afterEnd", formHtml, true);
    form.setDisplayed(false);
    var obj = new ClixUtils.Form(form.dom, parameters, action, target);
    return obj;
};
*/

/**
 * Searches for a form with name (or id) given by n
 * within document d.
 * @param n {String} form name (or id)
 * @param d {HtmlDocument} document that contains form
 * @return HtmlForm
 */
ClixUtils.Form.findForm = function(n, d) {
    var p,i,x;
    if (!d) d = document;
    x = d.forms[n];
    if (!x && d.getElementById) {
        x = d.getElementById(n);
    }
    // search for n bottom-up in parent frames:
    if (!x && parent.document && parent.document != d) {
        x = ClixUtils.Form.findForm(n, parent.document);
    }
    return x;
};

/**
 * Member functions for Form objects
 */
ClixUtils.Form.prototype = {
    /**
     * Initialize form with given parameters (must be an object)
     * @param parameters
     * @return
     */
    setParameters: function(parameters) {
        if (parameters) {
            for (var key in parameters) {
                this.setElement(key, parameters[key]);
            }
        }
    },

    /**
     * Submits given form, adds or updates timestamp ("dmy")
     * and procId parameters before executing form.submit.
     */
    submit: function(ignoreTimestamp, ignoreProcId) {
        if (!ignoreTimestamp) this.setElement(ClixUtils.TimestampParam, (new Date()).getTime());
        if (!ignoreProcId) this.setElement(ClixUtils.ProcessId, processId);
        this.form.action = this.action;
        this.form.target = this.target;
        if (this.cloneTo) {
            // clone form node to cloneTo element
            this.form = cloneNodeTo(this.form, this.cloneTo);
        }
        ClixUtils.debuglog("submitting");
        this.form.submit();
        ClixUtils.debuglog(this.form.action, this.form.target);
        if (this.window) {
            this.window.close();
        }
    },

    /**
     * Sets element named name of form to given value.
     * Creates a new (hidden) element if there is none.
     */
    setElement: function(name, value) {
        if (this.form[name]) {
            this.form[name].value = value;
        } else {
            var elem = this.form.ownerDocument.createElement("input");
            elem.setAttribute("type", "hidden");
            elem.setAttribute("name", name);
            elem.setAttribute("value", value);
            this.form.appendChild(elem);
        }
    },

    /**
     * Like setElement, but adds the given value to
     * existing value(s) for given name.
     */
    addElementValue: function(name, value) {
        if (Ext.isArray(value)) {
            for (var i = 0; i < value.length; ++i) {
                var elem = this.form.ownerDocument.createElement("input");
                elem.setAttribute("type", "hidden");
                elem.setAttribute("name", name);
                elem.setAttribute("value", value[i]);
                this.form.appendChild(elem);
            }
        } else {
            var elem = this.form.ownerDocument.createElement("input");
            elem.setAttribute("type", "hidden");
            elem.setAttribute("name", name);
            elem.setAttribute("value", value);
            this.form.appendChild(elem);
        }
    },

    /**
     * Removes the element(s) with given name from form
     */
    removeElement: function(name) {
        var elements = this.form.getElementsByTagName("input");
        var toRemove = [], i;
        for (i = 0; i < elements.length; ++i) {
            if (elements[i].name == name) {
                toRemove.push(elements[i]);
            }
        }
        for (i = 0; i < toRemove.length; ++i) {
            this.form.removeChild(toRemove[i]);
        }
    },

    removeElementValue: function(name, value) {
        var elements = this.form.getElementsByTagName("input");
        var toRemove = [], i;
        for (i = 0; i < elements.length; ++i) {
            if (elements[i].name == name && elements[i].value == value) {
                this.form.removeChild(elements[i]);
                break;
            }
        }
    },

    getElementValue: function(name) {
        return this.form[name].value;
    },

    /**
     * Sets form action
     */
    setAction: function(action) {
        this.action = action;
        this.form.action = action;
    },

    /**
     * Sets the form target
     */
    setTarget: function(target) {
        this.target = target;
        this.form.target = target;
    },

    /**
     * Gets form parameters in a form that can be used in UriObject objects.
     * @param {Boolean} asString - to return a String representation of the form contents
     * @return object with all form parameters and values, e.g. { name1: "value1", name2: "value2" }
     */
    getParameters: function(asString) {
        var result = Ext.Ajax.serializeForm(this.form);
        return asString ? result : Ext.urlDecode(result);
    },

    /**
     * Gets form parameters and action url parameters in one object
     */
    getAllParameters: function(asString) {
        var params = Ext.urlDecode(Ext.Ajax.serializeForm(this.form));
        var actionUri = new ClixUtils.UriObject(this.action);
        actionUri.addParameters(params);
        return asString ? Ext.urlEncode(actionUri.params) : actionUri.params;
    },

    getUri: function() {
        this.form.action = this.action;
        this.form.target = this.target;
        var params = Ext.urlDecode(Ext.Ajax.serializeForm(this.form));
        var actionUri = new ClixUtils.UriObject(this.action);
        actionUri.addParameters(params);
        ClixUtils.debuglog("getUri", actionUri);
        return actionUri;
    },

    /**
     * Iterates form elements and replaces original "onclick" event handler
     * with an Ext "click" event handler, where the event handlers target
     * window is set to given target.
     * Status: Experimental!
     * Example: myForm = ClixUtils.Form.create("myForm");
     *          myForm.setEventHandlerTargets(window);
     *         Somewhere in the form: <input type="checkbox" name="name1" onclick="checkInput(this)" />
     *         Result of call: event handling function is called within current window (not Ext window).
     * @param {Window} target window object
     */
    setEventHandlerTargets: function(target, eventName) {
        var elems = this.form.elements;
        if (!eventName) eventName = "onclick";
            //var withExp = /^with {(.+)}$/;
        var fnRegExp = /^(javascript:)?([^(]+)/;
        for (var i = 0; i < elems.length; i++) {
            var onclick = elems[i].getAttribute(eventName);
            var result = fnRegExp.exec(onclick);
            ClixUtils.debuglog("handling", onclick, result[2], target[result[2]]);
            if (result) {
                elems[i].removeAttribute(eventName);
                Ext.EventManager.on(elems[i], eventName.substring(2), target[result[2]], target);
            }
        }
    },

    /**
     * Sets all checkbox type elements in the underlying form element to given value.
     * @param on - state of checkboxes to set (true or false)
     * @return number of handled elements
     */
    setAllCheckboxes: function(on) {
        var elems = this.form.elements;
        var counter = 0;
        for (var i = 0; i < elems.length; i++) {
            if (elems[i].type == 'checkbox' && !elems[i].disabled) {
                elems[i].checked = on;
                counter++;
            }
        }
        return counter;
    }
};

/**
 * @see ClixUtils.UriObject.createUri, for CLIX events
 */
ClixUtils.UriObject.createEventUri = function(event, params) {
    return ClixUtils.UriObject.createUri(null, params).setParameter(ClixUtils.ClixEvent, event);
};

/**
 * Creates an instance of ClixUtils.UriObject
 * from given url and params (parameters)
 */
ClixUtils.UriObject.createUri = function(url, params) {
    var uri = new ClixUtils.UriObject(url, params);
    if (!uri.hasAbsolutePath()) {
        uri.addDmy();
        var procId = uri.getParameterValue(ClixUtils.ProcessId);
        if (procId == null && typeof processId != "undefined") {
            uri.setParameter(ClixUtils.ProcessId, processId);
        }
    }
    return uri;
};

/**
 * Member functions for UriObject objects.
 * Note to create a new instance with <code>new ClixUtils.UriObject(...)</code>
 * or a factory function like <code>ClixUtils.UriObject.createUri(...)</code> before
 * using any of the functions defined within prototype.
 */
ClixUtils.UriObject.prototype = {
    /**
     * Adds parameters to this uri. Multiple value parameters are handled
     * automatically (like "a=1&a=2&a=3" or {a:[1,2,3]}).
     * Example:
     * <code>var u = new ClixUtils.UriObject("/page.jsp");
     * u.addParameters({ param1: "value1", param2: "value2" });
     * </code>
     * @param params JS object with parameter definition or query string
     */
    addParameters: function(params) {
        var paramObj;
        if (typeof params == "string") {
            paramObj = Ext.urlDecode(params);
        } else {
            paramObj = params;
        }
            // copy all parameters from paramObj to this.params:
        for (var p in paramObj) {
            if (typeof this.params[p] == "undefined") {
                this.params[p] = paramObj[p];
            } else {
                if (Ext.isArray(this.params[p])) {
                    if (Ext.isArray(paramObj[p])) {
                        for (var q in paramObj[p]) {
                            this.params[p].push(paramObj[p][q]);
                        }
                    } else {
                        this.params[p].push(paramObj[p]);
                    }
                } else {
                    if (Ext.isArray(paramObj[p])) {
                        this.params[p] = [ this.params[p] ];
                        for (var q in paramObj[p]) {
                            this.params[p].push(paramObj[p][q]);
                        }
                    } else {
                        this.params[p] = [ this.params[p], paramObj[p] ];
                    }
                }
            }
        }
        return this;
    },

    /**
     * Added for convenience
     * @see addParameters
     */
    addParameter: function(paramName, paramValue) {
        var p = {};
        p[paramName] = paramValue;
        return this.addParameters(p);
    },

    /**
     * Sets (and overwrites pre-existing) parameter paramName
     * to value paramValue.
     */
    setParameter: function(paramName, paramValue) {
        this.params[paramName] = paramValue;
        return this;
    },

    /**
     * For your convenience
     * @see setParameter
     */
    setProcessId: function(newProcessId) {
        this.params[ClixUtils.ProcessId] = newProcessId;
        return this;
    },

    removeParameter: function(paramName) {
        delete this.params[paramName];
        return this;
    },

    /**
     * @return parameter value, which can be a string or an array
     */
    getParameterValue: function(paramName) {
        return this.params[paramName];
    },

    addDmy: function() {
        this.params[ClixUtils.TimestampParam] = (new Date()).getTime();
        return this;
    },

    getQuery: function() {
        var paramStr = Ext.urlEncode(this.params);
        if(paramStr && paramStr.length > 0){
            return "?" + paramStr;
        } else{
            return "";
        }
    },

    hasAbsolutePath: function() {
        return this.uri.indexOf("://") > 0;
    },

    toString: function() {
        return this.uri + this.getQuery();
    }
};

if ((navigator.appName == "Netscape") && (parseFloat(navigator.appVersion.substring(0, 4)) < 5.0))
{
    N4 = true;
}
;
if ((navigator.appName == "Netscape") && (parseFloat(navigator.appVersion.substring(0, 4)) >= 5.0))
{
    N6 = true;
}
;
if (navigator.appName == "Microsoft Internet Explorer")
{
    IE = true;
}
;
/** The function searchFrameBottomUp searches a specific frame identified by its name starting from the given window object.
 * searchFrameBottomUp searches from bootm to top using the parent element to climb up.
 * @param startWindow the window object from which the search will be started.
 * @param frameName the name of the specific frame that is searched for as a string.
 * @return the frame (resp. window) object with the name given in frameName or null if no such object is found.
 */
function searchFrameBottomUp(startWindow, frameName) {
    if (startWindow == null) {
        startWindow = window;
    }
    var currentWindow = startWindow;
    var currentFrames = startWindow.frames;
    var searchedFrame = null;

    // search frames up tp top window
    do {
        for (i = 0; i < currentFrames.length; i++) {
            if (currentFrames[i].name == frameName) {
                return currentFrames[i];
            }
        }
        currentWindow = currentWindow.parent;
        currentFrames = currentWindow.frames;
    } while (currentWindow != currentWindow.parent);

    // search frames of top window
    for (i = 0; i < currentFrames.length; i++) {
        if (currentFrames[i].name == frameName) {
            return currentFrames[i];
        }
    }

    return searchedFrame;
}


// ALAN 20.06.06 -> offene Fenster werden beim Wechsel der Navigation geschlossen
// Changed by Andreas POhl 20070823: Integration into parent frameset:
// changed behavior to search from bottom up to upperframe instead of going down from top
// changed by SR (Bug23528 -> window has lost the opener by reload opener frame, so window.opener is undefinded ->  trying reference window.opener.top.opener causes an error)
function setRefInUpperwork(clixWindow) {
    var refUpperframe = findUpperwork();
    if (refUpperframe != null) {
        try {
            // check for upperwork loaded in upperframe
            if (refUpperframe.location.href.match(/upperwork/)) {
                refUpperframe.setReference(clixWindow);
            }
            else {
                // in case upperwork is not yet loaded skip setting the reference
            }
        }
        catch(e) {
            // in case of an error in setReference, e.g. upperwork is not loaded in upperframe skip the reference
        }
    }
}

function findUpperwork() {
    var refUpperframe = null;
    var clixMainTop = getClixMainTop();

    if (useExt) {
        refUpperframe = clixMainTop.Ext.get("upperframe");
        if (refUpperframe && refUpperframe.dom) refUpperframe = refUpperframe.dom;
        if (refUpperframe && refUpperframe.contentWindow) refUpperframe = refUpperframe.contentWindow;
    }
    if (!refUpperframe) refUpperframe = searchFrameBottomUp(window, "upperframe");
    // upperframe in main Window searched, if no upperframe found refUpperframe=null
    if (refUpperframe != null) {
        return refUpperframe;
        // upperframe in clixWindow searched, if no upperframe found refUpperframe=null
    } else {
        try {
            if (window.opener) {
                refUpperframe = searchFrameBottomUp(window.opener.top, "upperframe");
            } else if (top.opener) {
                refUpperframe = searchFrameBottomUp(top.opener.top, "upperframe");
            }
            // upperframe in parent window of clixWindow searched, if no upperframe found refUpperframe=null
            if (refUpperframe == null) {
                if (window.opener.top.opener) {
                    refUpperframe = searchFrameBottomUp(window.opener.top.opener, "upperframe");
                    // upperframe in parent window of parent window of clixWindow  searched, if no upperframe found refUpperframe=null
                    if (refUpperframe == null) {
                        if (window.opener.top.opener.top.opener) {      // upperframe in parent window of parent window of parent window of clixWindow searched, if no upperframe found refUpperframe=null
                            refUpperframe = searchFrameBottomUp(window.opener.top.opener.top.opener, "upperframe");
                        }
                    }
                }
            }
        } catch(e) {
            // one of the windows has lost his opener by reload the opener frame, so upperframe could not be referenced
            refUpperframe = null;
        }

        if (refUpperframe != null) {
            return refUpperframe;
        }
        else {
            // there are  more then 4 windows opened, so upperframe could not be found
            return null;
        }
    }


}


function closeAllWindowsInUpperwork() {
    var f = findUpperwork();
    if (typeof f.closeAllwindows == "function")
        f.closeAllwindows();
}

function closeAllWindowsInUpperworkBut(window) {
    var f = findUpperwork();
    if (typeof f.closeAllwindowsBut == "function")
        f.closeAllwindowsBut(window);
}

// ENDET

/**
 * Suggestion: use ClixUtils.Window.open directly
 */
function generalOpenWindow(url, name, strParams, returnWindow) {
    var clixWindow = ClixUtils.Window.open(url, name, strParams);
    if (returnWindow)
        return clixWindow;
}


function openSWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.S);
}

function openSMWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.SM);
}

function openMWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.M);
}


function openLWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.L);
}

function openObjectPopupWindow(url, procId, popupId, params) {
    var popupReference;
    if (typeof (name) != 'undefined' && typeof (url) != 'undefined' && typeof (procId) != 'undefined' && typeof (popupId) != 'undefined') {
        // Check if the same popup is opened from another tab!
        var checkOk = getClixContentframe().checkObjectPopupOpenLayer(procId, popupId);
        if (checkOk) {
            var popupName = procId + 'ObjectPopup';// Use the tab id AND a String as name because we can only open one object popup in a tab.
            popupReference = ClixUtils.Window.open(url, popupName, params, undefined, true);
            if (typeof (popupReference) != 'undefined') {
                getClixContentframe().addObjectPopupReference(procId, popupReference, popupId);
            }
    
            // Titel des Fensters entspricht dem Tab
            updateWindowTitle(popupReference,0);
            return popupReference;
        }
    }
    return null;
}

// Ändert den Titel des Fensters auf den Namen des aktiven Tabs
function updateWindowTitle(windowRef, counter){
    try{
        if(windowRef.document != null && windowRef.document.title != null && windowRef.document.title.length > 0){
           var t = getActiveTabTitle();
            var regExpre =  /&#39/gi;            // Titel muss ohne Kodierung übergeben werden (Bug 48778)
            t = t.replace(regExpre,'\'');      
            windowRef.document.title = t;
        }else{
            counter++;
            if(counter < 200) {
                ClixUtils.debuglog("can't change window title: title-Tag isn't available in window " + counter);
                setTimeout(function(){updateWindowTitle(windowRef, counter)},100);
            }else
              ClixUtils.debuglog("can't change window title: title-Tag isn't available in window");
        }
    }catch(e){
        ClixUtils.debuglog("can't change window title: title-Tag isn't available in window" + e);
    }
}




function openSpecialWindow(url, name, scrolling) {
    if (arguments.length < 3) {
        scrolling = "no";
    }
    var p = ClixUtils.Window.Params.Special + scrolling;
    return ClixUtils.Window.open(url, name, p);
}


function openCalendarSpecialWindow(url, name, scrolling) {
    if (arguments.length < 3) {
        scrolling = "no";
    }
    var p = ClixUtils.Window.Params.Calendar + scrolling;
    return ClixUtils.Window.open(url, name, p);
}


//A.O. 10.4.2004: Fktn. notwendig, da die vorher verwendete Funktion openSpecialWindow keine Vergr??erung des Fensters zulie?. Weiterhin ist f?r die korrekte
//Funktionalit?t der F11-Taste unter dem IE ein directories=yes notwendig. Ansosnten wird der obere Teil, z.B. eine
//Titelzeile in einem "nackten" PopUp abgeschnitten.

function openSpecialWindowVC(url, name) {
    ClixUtils.Window.open(url, name, ClixUtils.Window.Params.VC);
}

function openBigResizableWindow(url, name, noReturn) {
    var clixWindow = ClixUtils.Window.open(url, name, ClixUtils.Window.Params.BigResizable);

    if (!noReturn) {
        return clixWindow;
    }
}

function openAlertWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.Alert);
}


function openXSWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.XS);
}

function openBWindow(url, name) {
    return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.B);
}


function openBigInfoWindow(url, name, resizable) {
    if (arguments.length < 3 || resizable == false) {
        return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.BigInfoNoResizable);
    }
    else {
        return ClixUtils.Window.open(url, name, ClixUtils.Window.Params.BigInfoResizable);
    }
}


function openPerspectiveWindow(url, name) {
    var w = screen.availWidth;
    var h = screen.availHeight;
    var strParams = 'width=' + w + ',height=' + h + ',top=0,left=0,resizable=yes,dependent=no,scrollbars=1';

    if (name == null) {
        name = "ClixAnalytics";
    }
    var clixWindow = ClixUtils.Window.open(url, name, strParams);
    clixWindow.focus();
    clixWindow.window.resizeTo(screen.availWidth, screen.availHeight);
}

function openLoginWindow(url) {
    var paramstring = CenterWindow(350, 400) + ClixUtils.Window.Params.Login;
    return ClixUtils.Window.open(url, 'login', paramstring);
}

/*
    This method check if a given window exists and close it if yes
 */
function closeWindowCommon(wnd) {
    if (wnd && !wnd.closed) {
        wnd.close();
    }
}

function CenterWindow(_width, _height) {
    var ow = screen.availWidth;
    var oh = screen.availHeight;
    var str = "width=" + _width + ",height=" + _height + ",left=" + (ow - _width) / 2 + ",top=" + (oh - _height) / 2 + ",";
    return str;
}

function mediaPlayer(fileName, width, height) {
    openWindow(ClixUtils.UriObject.createUri("/control/mediaplayer.jsp",
    { file: fileName, width: width, height: height }), "clixMediaPlayer", width, height, true);
}

function starter(url) {
    openWindow(url, "contentStarter", 800, 600);
}

function openUpload() {
    UploadFactory.init(false);
    UploadFactory.openUpload('open_default_upload', {})

}

/** This method opens an upload window with defined size and position
 * @param url The url must be a handler that returns the uploadform.jsp or the site himself
 * @name name will be the name of the upload window
 * @return the upload window
 */
function openUploadWindow(url, name) {
    var uploadParams = getUploadParams();
    return ClixUtils.Window.open(url, name, uploadParams);
}

/*
 * upload params
 * @return the default upload parameters to open an own upload event with
 */
function getUploadParams() {
    var wheight = 220;
    if (isArabic == "true")
        wheight += 7;
    if (IE) {
        wheight += 10;
    }
    return 'width=530,height=' + wheight + ',screenX=300,screenY=350,top=300,left=350,dependant=yes'
}

/**
 * Opens a Component in a pop-up
 * @param id the componentId: program, course or learning object
 * @param source
 *    In case the mode is start, the source from where the component is opened, used for tracking information:
 *      - 1 (TrackingItem.SOURSE_CATALOG): the pop-up is opened from catalog;
 *      - 2 (TrackingItem.SOURCE_MY_BOOKSHELF): the pop-up is opened from bookshelf;
 *      - 0: otherwise.
 *    In case the mode is preview, the starting point from where the pop-up is opened, used for distinguishing the windows:
 *      - 0 (CourseWebKeys.SOURCE_COMPONENT): the pop-up is opened from the browser;
 *      - 1 (CourseWebKeys.SOURCE_COMPOSING): the pop-up is opened from another pop-up which is opened from the browser;
 *      - 2 (CourseWebKeys.SOURCE_MODULE): the pop-up is opened from another pop-up which can be opened from the browser or from a pop-up.
 *    In case the mode is backEnd or frontEnd:
 *      - no predefined compulsory values.
 * @param mode the running mode of the component
 *      - backEnd (CourseWebKeys.BACK_END): the component is opened in the manager where the object was created;
 *      - frontEnd (CourseWebKeys.FRONT_END): the component is opened in learning area as read only;
 *      - start (CourseWebKeys.START): the component is opened is running mode - all changes are saved;
 *        - preview (CourseWebKeys.PREVIEW): the component is opened is preview mode - no changes are saved.
 * @see CourseWebKeys and TrackingItem
 **/
function openComponent(id, source, mode) {
    if (typeof source == 'undefined') {
        source = 0;
    }
    if (typeof mode == 'undefined') {
        mode = 'start';
    }
    loadScript(contextPath + '/script/ajax/ajax.js', ['ajax']);
    new ajax.AjaxRequest(contextPath + '/servlet/de.imc.clix.control.Clix', {
        onload: doOpenComponent,
        responseType: ajax.RESPONSE_JSON,
        method: ajax.METHOD_POST,
        parameters: {
            clixEvent: 'ecomponent-link',
            id: id,
            source: source,
            mode: mode,
            dmy: (new Date()).getTime()
        }
    });
}

function doOpenComponent(reply) {
    var componentLink = new String(reply.eComponentLink);
    if (componentLink.search(/clixEvent=load-media*/) < 0) {
        var component;
        var composing;
        var module;
        var componentId = reply.id;
        var componentSource = reply.source;
        var popupId = componentSource + componentId;
        var popupName = processId + 'ObjectPopup' + componentSource;
        var url = ClixUtils.UriObject.createEventUri('open-ecomponent', {
            id: componentId, source: componentSource, mode: reply.mode, popup: true});

        var windowParam;
        if (reply.windowParam) {
        	windowParam = eval(reply.windowParam);
        } else if (navigator.appName == 'Microsoft Internet Explorer') {
            windowParam = ClixUtils.Window.Params.ComponentIE;
        } else {
        	windowParam = ClixUtils.Window.Params.Component;
        }

        if (componentSource == 0) {
        	if (window.module && window.module.closed) {
                window.module.close();
            }
            if (window.composing && window.composing.closed == false) {
                window.composing.close();
            }
            component = openObjectPopupWindow(url, processId, popupId, windowParam);
            window.component = component;
        } else if (componentSource == 1) {
            if (window.module && window.module.closed == false) {
                window.module.close();
            }
            composing = ClixUtils.Window.open(url, popupName, windowParam, undefined, true);
            if (typeof (composing) != 'undefined') {
                getClixContentframe().addObjectPopupReference(processId, composing, popupId);
            }
            updateWindowTitle(composing, 0);
            window.composing = composing;
            return composing;
        } else if (componentSource == 2) {
            module = ClixUtils.Window.open(url, popupName, windowParam, undefined, true);
            if (typeof (module) != 'undefined') {
                getClixContentframe().addObjectPopupReference(processId, module, popupId);
            }
            updateWindowTitle(module, 0);
            window.module = module;
            return module;
        }
    } else {
        var parameters = {
            id: reply.id,
            source: reply.source,
            mode: reply.mode,
            dmy: (new Date()).getTime()
        };
        loadScript(contextPath + '/script/edu/loadmedia.js', ['getMedia','loadMedia']);
        getMedia(contextPath + componentLink, 'component', null, parameters);
    }
}

function get(variable, defaultvalue) {
    if (variable == 'undefined' || variable == null) {
        return defaultvalue;
    }
    return variable;
}

var mailLayerHandler  = new Imc.Clix.EditLayerHandler({
    showInPopup:false,
    layerHeight:450,
    layerWidth:500,
    doAfterSaveHandler: function() {},
    errorDivId: "description_errorDiv",
    formName: "mail"
});

function submitMailLayer() {
	mailLayerHandler.processForm('mailto', {}, true);
}

/* wird wohl nich mehr verwendet
function MM_findObj(n, d) {
 var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i>d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}
*/

/**
 * Searches for an element/object with id (or form element name) 'n'.
 * When n is a form object, then the search is done bottom-up
 * (works with iframes, but not with framesets).
 * @param n - id of element (or form element name)
 * @param d - document object (optional, default: current document)
 * @return element when found, otherwise null
 */
function findObj(n, d) {
    var p,i,x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }

    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];

    for (i = 0; !x && d.layers && i < d.layers.length; i++) {
        x = findObj(n, d.layers[i].document);
    }
    if (!x && d.getElementById) {
        x = d.getElementById(n);
    }
    showConfiguration("findObj with actual Ext", window);
    if (!x && useExt) {
        x = Ext.get(n); // to find elements managed by Ext (note: parameter 'd' is ignored here!)
        if (x && x.dom) x = x.dom;
        if (x && x.contentWindow) {
            // especially for frames, to work like frameset;
            // contentWindow is an iframe attribute
            x = x.contentWindow;
        }
    }
    // search for n bottom-up in parent frames:
    if (!x && parent.document && parent.document != d) {
        x = findObj(n, parent.document);
    }
    return x;
}

/**
 * Clones DOM node n to destination node d, without displaying it (display=none).
 * Tested with FF 2.0 and IE 8.0
 * @param n - existing DOM node
 * @param d - existing target DOM node, e.g. document.body
 * @return cloned node
 */
function cloneNodeTo(n, d) {
    var f = n.cloneNode(true);
    if (!d) d = document;
    f.setAttribute("style", "display:none");
    d.appendChild(f);
    // Copy form element values (if there are any),
    // as they are not copied by cloneNode in general
    // (at least not in firefox)
    for (var i = 0; n.elements && i < f.elements.length; ++i) {
        f.elements[i].value = n.elements[i].value;
    }
    return f;
}

/**
 * TODO: What are the parameters?
 * @return
 */
function showHideLayers() {
    var i,p,v,obj,args = showHideLayers.arguments;

    for (i = 0; i < (args.length - 2); i += 3) {
        // try to show ExtJS object first, falling back to legacy code when there is no ExtJS object
        if (!showObject(args[i], args[i + 2]) && (obj = findObj(args[i])) != null) {
            v = args[i + 2];

            if (obj.style) {
                obj = obj.style;
                v = (v == 'show') ? 'visible' : (v = 'hide') ? 'hidden' : v;
            }
            if (typeof obj.visibility != "undefined")
                obj.visibility = v;
        }
    }
}

function findExtCmp(name) {
    var cmp = Ext.getCmp(name);
    if (cmp) return cmp;
    if (window != CLIXTOP && typeof parent.findExtCmp == "function") {
        return parent.findExtCmp(name);
    }
    return null;
}

/**
 * Displays an alert item without reload the page
 * @param paramObj - parameter container
 */
function displayAlert(paramObj) {
    var request = new ajax.AjaxRequest(
            ClixUtils.UriObject.createEventUri('display-alert').toString(), {
                onload: doDisplayAlert,
                responseType: ajax.RESPONSE_JSON,
                method: ajax.METHOD_POST,
                parameters: paramObj
    });
}
/**
 * Display alert_item from given reply
 * @param reply
 */
function doDisplayAlert(reply) {
    // show alert message:
    if (reply.alert_item) {
        var win = createFromAlertItem(reply.alert_item);
        win.show();
    }
}


/**
 * Shows or hides an Ext object (normally Ext.Window) in a message box.
 * In order to show an object, there must be a Javascript object
 * named ClixUtils.MessageBox.Store[obj], located at the actual document.
 * @param obj - a string naming a Javascript object (id)
 * @param showhide - "hide" to hide, otherwise try to show object
 * @return true when object exists and is shown or closed successfully
 */
function showObject(obj, showhide, framename) {
    ClixUtils.debuglog("showObject", obj, showhide, framename);
    if (!useExt) {
        //alert("Error: Missing Ext!\nExtJS must be included for correct function!");
        return false;
    }
    try {
        //showConfiguration("showObject called", window);
        var win = findExtCmp("messagebox_" + obj);
        if (win) {
            ClixUtils.debuglog("Deleting existing Ext object (remaining from other action)");
            win.destroy();
        }
		//console.debug("create Ext object from config object named messagebox_"+obj);
        // createMessage is defined in messages.js
        var messagebox = ClixUtils.MessageBox.Store[obj];

        var messageType = messagebox.messageType || "info";
        if (messageType == "slide") {
            ClixUtils.debuglog("creating slidebox", messagebox.title, messagebox.html);
            win = CLIXTOP.Ext.ux.imc.Slidebox.createSlidebox(messagebox.html, messagebox);
            win.show();
        } else {
            win = Ext.ux.imc.Window.createMessage(messageType, '', '', messagebox);
            if (showhide == "hide" || showhide == "hidden") {
                //console.debug("rendered? "+win.rendered);
                if (!win.rendered) {
                    // to be able to close an Ext.Window, it must have been rendered
                    win.render(Ext.getBody());
                }
                win.close();
            } else {
                win.show();
				// Next lines make win visible when win.show was called on a
                // non visible layer. In this case win's position is negative,
                // so win must be centered to be visible.
                var pos = win.getPosition(true);
                if (pos[0] < 0 || pos[1] < 0) {
                    win.on("afterlayout", win.center, win);
                }
            }
        }
        ClixUtils.MessageBox.CmpStore[obj] = win;
        return true;
    } catch(e) {
        ClixUtils.debuglog("Exception in showObject", e);
		//alert("Exception in showObject: "+e.toString());
        return false;
    }
}

/**
 * @param (Layername,'','show' oder 'hide',framename) or ('newlayer','','show','content')
 * @deprecated use showObject() directly to open or close an (Ext based) alert message
 */
function openCloseAlert(layer, dummy, showhide, framename) {
    // Ext integration:
    if (showObject(layer, showhide, framename)) {
        return;
    }
    try {
        // Legacy (non-Ext):
        if (IE) {
            if (arguments.length <= 3) {
                eval('document.all["' + layer + '"].style.left=(parseInt(document.body.clientWidth)-(parseInt(document.all["' + layer + '"].offsetWidth)))/2');
                eval('document.all["' + layer + '"].style.top=(parseInt(document.body.clientHeight)-(parseInt(document.all["' + layer + '"].offsetHeight)))/2');
                if (document.all["content"]) {
                    eval('document.all["' + layer + '"].style.top=parseInt(document.all["content"].style.top)+30');
                }
            } else if (arguments.length == 4) {
                eval('parent.' + framename + '.document.all["' + layer + '"].style.left=parseInt((document.body.clientWidth-parseInt(parent.' + framename + '.document.all["' + layer + '"].offsetWidth))/2)');
                if (eval('parent.' + framename + '.document.all.content')) {
                    eval('parent.' + framename + '.document.all["' + layer + '"].style.top=parseInt(parent.' + framename + '.document.all.content.style.top)+30');
                }
            }
        }
        if (arguments.length == 5) { // top, left position as parameters
            moveLayer(layer, framename, arguments[4]);
        }
        if (showhide == "show") {
            setTimeout("window.scrollTo(0,0)", 10);
        }

        moveLayersIFrame(layer, showhide);
        showHideLayers(layer, '', showhide);
    } catch (exception) {
        ClixUtils.debuglog("Exception in openCloseAlert", exception);
    }
}


// add 2004.02.17 by Yi, hide all Layers of alertLayerArray
// also alle Layer die auf der Seite in einem array angegeben wurden:
//var taskAlertLayers = ["noresults", "dateinvalid", "tooManyValuesLayer"];

function closeAlerts(alertLayerArray) {
    if (alertLayerArray != null) {
        for (var i = 0; i < alertLayerArray.length; i++) {
            var alertLayer = findObj(alertLayerArray[i]);
            if (alertLayer != null) {
                openCloseAlert(alertLayerArray[i], "", "hide");
            }
        }
        // end next
    }
}

/**
 * Hides all layers (when !extonly) and hides all Ext "messagebox_*" windows.
 * @param extonly - set to true to ignore layers and hide Ext windows only
 */
function hidealllayers(extonly)
{

    // Close all Ext.Window objects with id starting with "messagebox_"
    if (useExt) {
        //alert("Error: Missing Ext!\nExtJS must be included for correct function!");
        return;
    }
    Ext.ComponentMgr.all.each(function(item) {
        if (item.id && item.id.indexOf("messagebox_") >= 0 && item.isVisible()) item.hide();
    });
    if (!extonly) {
        // Legacy code: hides all div elements.
        var allLayers = document.getElementsByTagName('div');
        var NumberOfLayers = allLayers.length
        for (var i = 0; i < NumberOfLayers; i++)
        {
            if (allLayers[i].style.visibility != "hidden") allLayers[i].style.visibility = "hidden";
        }
    }
}

/* zentriert Layer horizontal  */
function setLayerToCenter(layerName, layerWidth) {
    var layer;
    var width;
    if (IE || N6) {
        layer = document.getElementById(layerName);
        if ((arguments.length == 1) && (IE)) layerWidth = parseInt(layer.clientWidth);
        width = parseInt(document.body.clientWidth);
        var alertWidth = parseInt(layerWidth);
        var newWidth = (width - alertWidth) / 2;
        layer.style.left = newWidth;
    }
}


function moveLayer(layerName, toppos, leftpos)
{
    if (IE || N6)
    {
        eval("document.getElementById('" + layerName + "').style.top=" + toppos);
        eval("document.getElementById('" + layerName + "').style.left=" + leftpos);
        eval("document.getElementById('" + layerName + "').style.visibility='visible'");
    }
    if (N4)
    {
        eval("document.layers['" + layerName + "'].top=" + toppos);
        eval("document.layers['" + layerName + "'].left=" + leftpos);
        eval("document.layers['" + layerName + "'].visibility='show'");
    }
}


function moveLayersIFrame(layerName, visi) {
    var divRef = document.getElementById(layerName);
    var ifrRef = document.getElementById('divShim_' + layerName);

    if (ifrRef != null) {
        divRef.style.display = "block";
        ifrRef.style.width = divRef.offsetWidth;
        ifrRef.style.height = divRef.offsetHeight;
        ifrRef.style.top = divRef.style.top;
        ifrRef.style.left = divRef.style.left;
        ifrRef.style.zIndex = divRef.style.zIndex - 1;
        if (visi == "show" || visi == "visible")
            ifrRef.style.display = "block";
        else
            ifrRef.style.display = "none";
    }

}


/* wird nicht mehr verwendet

function showInfoWithoutScrolling(url) {
       url = setDummy(url);
        window.open(url,'Info','width=640,height=480,scrollbars=no');
}
*/


/* verschickt ein Formular
 gibt es nur 1 Formular auf der Seite und die action ist bereits im formular gesetzt,
sind keine Parameter notwendig:submitFormular()
soll die action gesetzt werden dann ein Aufruf der Art:submitFormular('/home/formular3.jsp')
*/
function submitFormular(action, target, method, formname)
{
    if (document.forms.length == 0) {
        alert("There is no form to be sent on this page!");
        return
    }
    var theform = document.forms[0];
    if (document.forms.length > 1)
    {
        if (arguments.length == 4) {
            theform = findObj(formname)
        }
        else {
            alert("Please specify a formname");
            return
        }
    }
    if (arguments.length == 0) {
        if (document.forms[0].action == "") {
            alert("Please specify an action page");
        }
        else {
            document.forms[0].submit();
            return
        }
    }
    theform.action = top.upperframe.contextPath + arguments[0];

    if (arguments.length > 1)
    {
        if (arguments[1] == "") theform.target = "_self"; else theform.target = arguments[1];
    }
    else theform.target = theform.target = "_self";

    if (arguments.length > 2)
    {
        if (arguments[2] == "") theform.method = "get"; else theform.method = arguments[2];
    }
    else theform.method = "get";

    theform.submit();
}

/**
 * finds the first checked box and returns the element
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getFirstCheckedBoxof(formId, boxName) {
    var allCheckedBoxes = getCheckedBoxElements(formId, boxName);
    if (allCheckedBoxes != null && allCheckedBoxes.length > 0) {
        return allCheckedBoxes[0];
    } else {
        return null;
    }
}

/**
 * finds all check boxes (independent from activation status) and returns the element list
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getCheckboxElements(formId, boxName) {
    var allBoxes = new Array();
    if (document.forms.length == 1) {
        allBoxes = document.forms[0].elements;
    } else {
        allBoxes = document.getElementById(formId).elements;
    }
    var resultBoxArray = new Array();
    if (allBoxes.length > 0) {
        var j = 0;
        for (var i = 0; i < allBoxes.length; i++) {
            if (boxName != null && boxName.length > 0) {
                if (boxName == allBoxes[i].name) {
                    resultBoxArray[j++] = allBoxes[i];
                }
            } else {
                resultBoxArray[j++] = allBoxes[i];
            }
        }
    }
    return resultBoxArray;
}

/**
 * finds all check boxes (regarding its activation status) and returns the element list
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 * @param {Boolean} checked - status of the checkboxes to search for
 */
function getCheckboxElementsByStatus(formId, boxName, checked) {
    var allCheckboxes = getCheckboxElements(formId, boxName);
    var resultArray = new Array();
    if (allCheckboxes != null) {
        var j = 0;
        for (var i = 0; i < allCheckboxes.length; i++) {
            if (checked) {
                if (allCheckboxes[i].checked) {
                    resultArray[j++] = allCheckboxes[i];
                }
            } else {
                if (!allCheckboxes[i].checked) {
                    resultArray[j++] = allCheckboxes[i];
                }
            }
        }
    }
    return resultArray;
}

/**
 * finds all checked boxes and returns the element list
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getCheckedBoxElements(formId, boxName) {
    return getCheckboxElementsByStatus(formId, boxName, true);
}

/**
 * finds all unchecked boxes and returns the element list
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getUncheckedBoxElements(formId, boxName) {
    return getCheckboxElementsByStatus(formId, boxName, false);
}

/**
 * finds all check boxes and returns the id list
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getCheckboxIds(formId, boxName) {
    var allCheckboxes = getCheckboxElements(formId, boxName);
    var resultArray = new Array();
    if (allCheckboxes != null) {
        var j = 0;
        for (var i = 0; i < allCheckboxes.length; i++) {
            resultArray[j++] = allCheckboxes[i].value;
        }
    }
    return resultArray;
}

/**
 * finds all check boxes and returns the id list
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 * @param {Boolean} checked - status of the checkboxes to search for
 */
function getCheckboxIdsByStatus(formId, boxName, checked) {
    var allCheckboxes = getCheckboxElements(formId, boxName);
    var resultArray = new Array();
    if (allCheckboxes != null) {
        var j = 0;
        for (var i = 0; i < allCheckboxes.length; i++) {
            if (allCheckboxes[i].checked == checked) {
                resultArray[j++] = allCheckboxes[i].value;
            }
        }
    }
    return resultArray;
}

/**
 * finds all checked boxes and returns the element ids
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getCheckedBoxIds(formId, boxName) {
    return getCheckboxIdsByStatus(formId, boxName, true);
}

/**
 * finds all unchecked boxes and returns the element ids
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function getUnCheckedBoxIds(formId, boxName) {
    return getCheckboxIdsByStatus(formId, boxName, false);
}

/**
 * this method checks all boxes with boxName in form with id formId
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function checkAllBoxesof(formId, boxName) {
    var allCheckBoxes = getCheckboxElements(formId, boxName);
    for (var i = 0; i < allCheckBoxes.length; i++) {
        allCheckBoxes[i].checked = true;
    }
}

/**
 * this method unchecks all boxes with boxName in form with id formId
 * @param {String} formId - name of the form to search checkboxes into
 * @param {String} boxName (otpional) - name of the checkbox to search checkboxes for
 */
function uncheckAllBoxesof(formID, boxName) {
    var allCheckBoxes = getCheckboxElements(formID, boxName);
    for (var i = 0; i < allCheckBoxes.length; i++) {
        allCheckBoxes[i].checked = false;
    }
}

/* entfernt Zeilenumbrueche */
function nolinebreak(formname, elemname)
{
    var numberoflinebreaks = 0;
    for (var i = 0; i < eval("document." + formname + "." + elemname + ".value.length"); i++)
    {
        if (eval("document." + formname + "." + elemname + ".value.charAt(i)") == "\n") numberoflinebreaks++;
    }
    eval("document." + formname + "." + elemname + ".value=escape(document." + formname + "." + elemname + ".value)");
    for (var j = 0; j < numberoflinebreaks; j++)
    {
        eval("document." + formname + "." + elemname + ".value=document." + formname + "." + elemname + ".value.replace('%0D%0A','%20')");
    }
    eval("document." + formname + "." + elemname + ".value=unescape(document." + formname + "." + elemname + ".value)");
}

/**
 * @author klees
 * @param url to add a js dummy
 * @return the url with new jsdmy timestamp
 */
function setTimeStamp(url, checkexisting) {
    if (checkexisting) {
        if (url.indexOf("jsdmy") < 0) {
            return addTimeStamp(url);
        } else {
            return url;
        }
    } else {
        return addTimeStamp(url);
    }
}

/**
 * @author klees
 * @param url to add a js dummy if no parameter with name "jsdmy" already exists
 * @return the url with new jsdmy timestamp
 */
function addTimeStamp(url) {
    return addParameterToRequest(url, "jsdmy", (new Date()).getTime());
}

/* Hauptfunktionalitaet:
 * - laed die URL im uebergebenen destWindow
 * Nebenfunktionalitaeten:
 * - fuegt einen JS-Timestamp an die destUrl an (sofern nicht bereits vorhanden)
 * - fuegt die procId an deie destUrl an (sofern nicht bereits vorhanden)
 */
function reloadLocation(destWindow, destUrl) {
    destWindow.location.href = setTimeStamp(addProcessIdentifier(destUrl));
}

/* verhindert, dass sich der Cursor ueber einem inaktiven Link aendert
fuer die  Buttons in der Buttonrow die inaktiv werden gibt es ein Tag ->designvorlagen/baukasten.jsp
*/
function setCursorClass(link, flag) {
    if (IE) {
        if (flag) link.style.cursor = "default";
        else link.style.cursor = "hand";
    }
    if (N6) {
        if (flag) link.style.cursor = "default";
        else link.style.cursor = "pointer";
    }
}


/* ruft den Navipunkt  'my_home' auf -> Navi schliessen und myHome in den Contentframe*/
function closeMenuItem() {
    parent.upperframe.toMenuItem('my_home');
}

/**
 * @author klees
 * @param url to add the current process id to
 */
function addProcessIdentifier(url) {
    if (ClixUtils.ProcessId != null && ClixUtils.ProcessId != "null" && url.indexOf(ClixUtils.ProcessId + "=") < 0) {
        url = setTimeStamp(url, true);
        return addParameterToRequest(url, ClixUtils.ProcessId, processId)
    }
    return setTimeStamp(url, true);

}

function changeHeadlineButtons(imgObject, eventType) {
    var template = imgObject.id;
    var name = "";
    if (eventType == "mouseover") {
        name = template + "_on.png";
    } else if (eventType == "mouseout") {
        name = template + "_off.png";
    } else if (eventType == "click") {
        name = template + "_down.png";
    }

    imgObject.src = contextPath + "/data/client_design/default/standard/images/redesign/" + name
}

function waitForActiveTagToBeLoaded(newTabs, urlPrefix) {
    if (typeof(findUpperwork().parent.contentframe.document.getElementById(findUpperwork().parent.contentframe.mainTabPanel.getActiveTab().contentEl.id).contentWindow.content.Loadcontrol) != 'undefined'
            && findUpperwork().parent.contentframe.document.getElementById(findUpperwork().parent.contentframe.mainTabPanel.getActiveTab().contentEl.id).contentWindow.content.Loadcontrol) {
        var newTabId = newTabs[0].value;
        findUpperwork().parent.contentframe.openNaviTab(urlPrefix + newTabId);
        if (newTabs.length > 0) {
            var parameterTabs = newTabs.slice(1);
            if (parameterTabs.length > 0) {
                setTimeout(waitForActiveTagToBeLoaded, 500, parameterTabs, urlPrefix);
            }
        }
    } else {
        setTimeout(waitForActiveTagToBeLoaded, 500, newTabs, urlPrefix);
    }
}

/**
 * this method add a parameter to a given request including decision if the parameter should be added with ? or &
 * @author klees
 * @param url to add the new parameter name and value to
 * @param attrname the name of the parameter to add
 * @param attrvalue the value of the parameter to add
 * @return url with attached parameter and name
 */
function addParameterToRequest(url, attrname, attrvalue) {
    if (url instanceof ClixUtils.UriObject) {
        return url.addParameter(attrname, attrvalue);
    }
    if (url.indexOf('?') < 0) {
        url += '?';
    } else {
        url += '&';
    }
    url += attrname + '=' + attrvalue;
    return url;
}

/**
 * This method generate a defined process identifier string
 * @param {String} objectType string iditifieng the type of the object (e.g. user)
 * @param {String} objectId id of the object that will be handled in the process
 * @param {Boolean} addDummy if true a dummy will be added (e.g. to handle the same process many times (e.g. create))
 * @deprecated this method will be removed soon
 *             use methods openManagerTab, openObjectCreateTab, openObjectEditTab to open tabs instead
 */
function generateIdentifier(objectType, objectId, addDummy) {
    var theNewPid = '';
    if (objectType || objectId || addDummy) {
        if (objectId) {
            theNewPid += objectId + '.';
        }
        theNewPid += objectType
        if (addDummy) {
            theNewPid += '_at_' + (new Date()).getTime();
        }
    }
    return theNewPid;
}


/* -- Deprecated -- jetzt kommen die deprecated functions
   -- Deprecated -- jetzt kommen die deprecated functions
   -- Deprecated -- jetzt kommen die deprecated functions
   -- Deprecated -- jetzt kommen die deprecated functions
   -- Deprecated -- jetzt kommen die deprecated functions
   -- Deprecated -- jetzt kommen die deprecated functions
*/

/**
 * @deprecated
 */
function openWBT(url) {
    var wbtWindow = ClixUtils.Window.open(url, 'WBT', ClixUtils.Window.Params.WBT);
    wbtWindow.focus();
}

/**
 * @deprecated
 */
function newwindow(urlie, named) {
    if (navigator.appName == "Microsoft Internet Explorer") {
        var Fenster = ClixUtils.Window.open(urlie, named, ClixUtils.Window.Params.NewWindowIE);
    }
    if (navigator.appName == "Netscape") {
        var Fenster = ClixUtils.Window.open(urlie, named, ClixUtils.Window.Params.NewWindow);
        Fenster.moveTo(150, 200);
    }
}


function preview(url) {
    // SSC 13.05.03  Umstellung der PopUps
    url = setTimeStamp(url);
    openSpecialWindow(url, 'Preview');
    // ende
}

function showInfo(url) {
    url = setTimeStamp(url);
    // SSC 13.05.03  Umstellung der PopUps
    openLWindow(url, 'Info');
    // ende
}

function setDummy2(url) {
    if (url.indexOf('?') < 0) {
        url += '?';
    } else {
        url += '&';
    }
    url += 'jsdmy=' + (new Date()).getTime();
    return url;
}

function windowOpen(url) {
    // SSC 14.05.03  Umstellung der PopUps
    var clixWindow = openSpecialWindow(url, 'clixWindow');
    // ende

    return clixWindow;
}

/**
 * @deprecated
 */
function openExternal(url) {
    var externWindow = ClixUtils.Window.open(url, 'clixWindow', ClixUtils.Window.Params.External);
    externWindow.focus();
}

/**
 * @deprecated
 */
// Bitte diese Funktion nicht mehr verwenden (C.L. 08.07.2003)
// stattdessen: Fensterinhalt in Frameset packen, wo der Inhaltsframe scrollt
function openWindow(url, name, _width, _height, resizability) {
    var ow = screen.availWidth;
    var oh = screen.availHeight;
    var scrollBar = "0";
    if ((_width > screen.availWidth) || (_height > screen.availHeight))
        scrollBar = "1";
    if (arguments.length < 5){
        var str = "left=" + (ow - _width) / 2 + ",top=" + (oh - _height) / 2 + ",width=" + _width + ",height=" + _height + ",scrollbars=" + scrollBar;
    }

    else
    {
        if (resizability == 'yes' || resizability){
            var str = "left=" + (ow - _width) / 2 + ",top=" + (oh - _height) / 2 + ",width=" + _width + ",height=" + _height + ",scrollbars=" + scrollBar + ",resizable=yes";
        }
    }

    var newWindowObject = ClixUtils.Window.open(url, name, str);
    newWindowObject.focus();
}
// Bitte diese Funktion nicht mehr verwenden (C.L. 08.07.2003)
// stattdessen: Fensterinhalt in Frameset packen, wo der Inhaltsframe scrollt

/**
 * @deprecated
 */
function getOpenWindow(url, name, _width, _height) {
    var ow = screen.availWidth;
    var oh = screen.availHeight;
    var scrollBar = "0";
    if ((_width > screen.availWidth) || (_height > screen.availHeight))
        scrollBar = "1";

    var str = "left=" + (ow - _width) / 2 + ",top=" + (oh - _height) / 2 + ",width=" + _width + ",height=" + _height + ",scrollbars=" + scrollBar;

    return ClixUtils.Window.open(url, name, str);
}

/**
 * @deprecated
 */
/*A.O. 29.8.2003, da Scrollbarfunktionalit?t bei openWindow fehlerhaft*/
function openWindowCommon(url, name, _width, _height, scrollbars, resizeable, noReturn) {
    if (typeof noReturn == 'undefined') {
        noReturn = false;
    }
    var ow = screen.availWidth;
    var oh = screen.availHeight;
    var str = "left=" + (ow - _width) / 2 + ",top=" + (oh - _height) / 2 + ",width=" + _width + ",height=" + _height + ",scrollbars=" + scrollbars + ",resizable=" + resizeable;
    var fileWindow = ClixUtils.Window.open(url, name, str);
    fileWindow.focus();
    if (!noReturn)
        return fileWindow;
}

function openWindowCommonFull(url, name, _width, _height, toolbar, menubar, location, scrollbars, status, resizeable) {
    var ow = screen.availWidth;
    var oh = screen.availHeight;
    var str = "left=" + (ow - _width) / 2 + ",top=" + (oh - _height) / 2 + ",width=" + _width + ",height=" + _height + ",toolbar=" + toolbar + ",menubar=" + menubar + ",location=" + location + ",scrollbars=" + scrollbars + ",status=" + status + ",resizable=" + resizeable;
    var fileWindow = ClixUtils.Window.open(url, name, str);
    fileWindow.focus();
}

function openInfo(url) {
    if (window.info)
        info.close();

    var info = ClixUtils.Window.open(url, 'Info', ClixUtils.Window.Params.Info);
    info.focus();
}

function openInfoType(url) {
    // SSC 13.05.03  Umstellung der PopUps
    openMWindow(url, 'Info');
}


/**
 * @deprecated
 */
function newwindowComponent(urlie, named) {
    // SSC 13.05.03  Umstellung der PopUps
    openSpecialWindow(setTimeStamp(urlie), named, 'yes');
    // Sonderfall bis Frageb?gen-Frontend umgebaut ist, dann brauch man keine Scrollbalken mehr
    // ende
}


/**
 * @deprecated
 */
function openInfoStatus(url) {
    openLWindow(url, 'Info');
}

/**
 * @deprecated
 */
function MM_showHideLayers() {
    var da,weg;
    if (arguments[2] == 'show') {
        da = "visible";
        if (arguments.length == 5 && arguments[4]) setTimeout("window.scrollTo(0,0)", 10);
    }
    if (arguments[2] == 'hide')
    {
        if (navigator.appName == "Netscape") {
            da = "hide";
        }
        if (navigator.appName == "Microsoft Internet Explorer") {
            da = "hidden";
        }
    }

    if (arguments[2] == 'show')
    {
        if (navigator.appName == "Netscape") {
            da = "show";
        }
        if (navigator.appName == "Microsoft Internet Explorer") {
            da = "visible";
        }
    }
    if (arguments.length == 4 || arguments.length == 5) {
        if (arguments[3] == '') {
            if (navigator.appName == "Microsoft Internet Explorer") {
                eval('document.all["' + arguments[0] + '"].style.visibility="' + da + '"');
            } else {
                var argumente = arguments[0];
                document.layers[argumente].visibility = "'+da+'";
            }
        } else {
            if (navigator.appName == "Microsoft Internet Explorer") {
                eval('parent.' + arguments[3] + '.document.all["' + arguments[0] + '"].style.visibility="' + da + '"');
            } else {
                var argumente = arguments[0];
                if (N4) {
                    document.layers[argumente].visibility = "'+da+'";
                }
                if (N6) {
                    document.getElementById(argumente).style.visibility = "'+da+'";
                }
            }
        }
    }
    if (arguments.length == 3)
        if (navigator.appName == "Microsoft Internet Explorer") {
            eval('document.all["' + arguments[0] + '"].style.visibility="' + da + '"');
        } else {
            var argumente = arguments[0];
            document.layers[argumente].visibility = "'+da+'";
        }

    if (navigator.appName == "Microsoft Internet Explorer")
    {
        if (arguments.length <= 3)
        {
            eval('document.all["' + arguments[0] + '"].style.pixelLeft=parseInt((document.body.clientWidth-parseInt(document.all["' + arguments[0] + '"].style.width))/2)');
            if (document.all["content"])
            {
                eval('document.all["' + arguments[0] + '"].style.top=parseInt(document.all["content"].style.top)+30');
            }
        }

        if (arguments.length == 4)
        {
            eval('parent.' + arguments[3] + '.document.all["' + arguments[0] + '"].style.pixelLeft=parseInt((document.body.clientWidth-parseInt(parent.' + arguments[3] + '.document.all["' + arguments[0] + '"].style.width))/2)');

            if (eval('parent.' + arguments[3] + '.document.all.content'))
            {
                eval('parent.' + arguments[3] + '.document.all["' + arguments[0] + '"].style.top=parseInt(parent.' + arguments[3] + '.document.all.content.style.top)+30');

            }
        }

    }

}

/**
 * loads myHome into contentframe
 */
function closePage() {
    parent.upperframe.closeNavi();
    ClixUtils.redirect(parent.contentframe, "/home/myhome.jsp");
}

/**
 * @deprecated
 */
/* schaltet scrollen aus */
function s()
{
    if (navigator.appName == "Microsoft Internet Explorer")
    {
        document.body.scroll = "no";
    }
}

/* ueberprueft Laenge eines Eintrags->dies geschieht eigentlich im Tag Java*/
function check_length(area, length) {
    if (area.value.length > length) {
        area.value = area.value.substr(0, length);
        if (!IE) {
            var correctionForFF = countSigns(area.value, '\n');
            area.value = area.value.substr(0, length - correctionForFF);
        }
        var layerName = area.name + "TagLayer";
        openCloseAlert(layerName, "", "show");
    }
}
/**
 * @deprecated
 */
/* verschickt Formular*/
function toggleGroup(groupName) {
    if (window.newFile)
        window.newFile.close();
    document.clixform.clixFormEvent.value = "toggleGroup$" + groupName;
    document.clixform.submit();
}
/**
 * @deprecated use ClixUtils.Form for this task
 */
function submitClixForm(clixEventName) {
    document.clixform.clixFormEvent.value = clixEventName;
    document.clixform.submit();
}

// R.S. wie openSpecialWindow aber mit Scrolling nur f?r HTML-Upload-Seiten
function openHTMLUploadWindow(url, name) {
    var clixWindow = ClixUtils.Window.open(url, name, ClixUtils.Window.Params.HtmlUpload);
    clixWindow.focus();
}

function openProfile(id, userBeanName) {
    ClixUtils.Window.openEvent('profileViewEvent', {
        newWindow: true, id: id, userBeanName: userBeanName }, 'userProfile',
            ClixUtils.Window.Params.Profile);
}

function openUserInfo(id) {
    ClixUtils.Window.openEvent('user-info', { id: id }, 'userInfo',
            ClixUtils.Window.Params.UserInfo);
}

function addToAddressBook(id, searchMapKey) {
    ClixUtils.redirectEvent(parent, 'addusertoaddressbook', {
        addressId: id, searchMapKey: searchMapKey });
}

function toGuestBook(id) {
    var uri = ClixUtils.UriObject.createEventUri('my-messageboard-list-popup', {
        owner_id: id });
    openWindow(uri, 'guestbook', 700, 500);
}

function openSelectWindow(url, name) {
    if (window.clixWindow)
        clixWindow.close();

    var clixWindow = ClixUtils.Window.open(url, name, ClixUtils.Window.Params.Select);
    clixWindow.focus();

    return clixWindow;
}
/**
 * Attention: Do NEVER use 'top' to reference top frame,
 * as CLIX may be integrated within an other application
 * (e.g. sharepoint).
 * Changed by Andreas Pohl 20070823: Integration into parent frameset:
 * Adapted getClixTop to search for the main frame of a parent frameset
 * if a name is given in SystemIntegration.windowFrameName
 * If found CLIX is shown in this frame instead of using top
 * @return CLIX top frame
 */
function getClixTop(current) {
    if (!current) current = window;
    if (current.tagName == "IFRAME") current = current.contentWindow;
    // The variable windowFrameName is defined in the document in which this Javascript file is embedded
    // The content of the variable is read from SystemIntegration.windowFrameName
    // search for the main frame of the parent frameset, if a name is set
    if (typeof windowFrameName != "undefined") {
        var parent_window = current;
        var parent_frames = null;
        do {
            // stepping
            parent_window = parent_window.parent;
            if(parent_window && parent_window.contextPath){
                // the parent_window is not a clix window
                break;
            }
            if (parent_window.tagName == "IFRAME") parent_window = parent_window.contentWindow;
            parent_frames = parent_window.frames;
            if (parent_frames.length) {
                for (i = 0; i < parent_frames.length; i++) {
                    try {
                        if (parent_frames[i].name == windowFrameName) {
                            // return the main frame of parent frameset
                            return parent_frames[i];
                        }
                    } catch (e) {
                        // ignore exception; maybe parent_frame[i] is an external page,
                        // so that there is no access to the 'name' property
                    }
                }
            }
        } while (parent_window != top && parent_window != parent_window.parent);
    }

    // if nothing found in upper part, the default behavior of getClixTop is carried out
    var currentFrame = current;
    try {
        while (currentFrame.parent && currentFrame.parent != currentFrame) {
            if (currentFrame.location.hostname == currentFrame.parent.location.hostname
                    && String(currentFrame.parent.location.pathname).indexOf(contextPath) == 0) {
                currentFrame = currentFrame.parent;
            } else {
                break;
            }
        }
    } catch (e) {
    }
    return currentFrame;
}

function getClixMainTop(current) {
    if (!current) current = window;
    current = getClixTop(current);
    try {
        while (current.opener && current.opener != current
                && current.opener.location.hostname == current.location.hostname
                && String(current.opener.location.pathname).indexOf(contextPath) == 0) {
            current = getClixTop(current.opener);
        }
    } catch (exception) {
    }
    return current;
}

/**
 * Gets CLIX actionframe, even from a popup (of a popup...)
 */
function getClixActionframe() {
    var topFrame = getClixMainTop();
    return topFrame.actionframe;
}
/**
 * Gets CLIX content, even from a popup (of a popup...)
 */
function getClixContentframe() {
    var topFrame = getClixMainTop();
    return topFrame.contentframe;
}
/**
 * @deprecated
 */
function getAjaxRequest() {
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            request = new ActiveXObject('Msxml2.XMLHTTP');
        } catch(err) {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
    return request;
}

function loadScript(scriptpath, functions) {
    var request = getAjaxRequest();
    request.open('GET', scriptpath, false);
    request.send(null);
    eval(request.responseText);
    for (var i = 0; i < functions.length; i++) {
        window[functions[i]] = eval(functions[i]);
    }
}

// Start: Vorschlag von A.O. (Bug16623)
var originaloption;
/**
 * @deprecated
 */
function setOriginaloption(ac) {
    originaloption = ac;
}

/**
 * @deprecated
 */
function resetToOriginaloption(dc) {
    dc.selectedIndex = originaloption;
    dc.blur();
}
// Ende: Vorschlag von A.O. (Bug16623)

function openChooseSkill(container, context, levelType, schedulingDisabled, comment, partner, name, popupExpression) {
    if (popupExpression == null) {
        popupExpression = '';
    }
    var uri = ClixUtils.UriObject.createEventUri('chooseSkill', {
        container: container,
        context: context,
        levelType: levelType,
        schedulingDisabled: schedulingDisabled,
        comment: comment,
        partner: partner });
    uri.addParameters(popupExpression);
    return ClixUtils.Window.open(uri, name, ClixUtils.Window.Params.ChooseSkill);
}

function openEditSkill(skillId, container, context, levelType, schedulingDisabled, comment, partner, name, popupExpression) {
    if (popupExpression == null) {
        popupExpression = '';
    }
    var uri = ClixUtils.UriObject.createEventUri('chooseSkillLevel', {
        edit: true,
        skillId: skillId,
        container: container,
        context: context,
        levelType: levelType,
        schedulingDisabled: schedulingDisabled,
        comment: comment,
        partner: partner });
    uri.addParameters(popupExpression);
    return ClixUtils.Window.open(uri, name, ClixUtils.Window.Params.ChooseSkill);
}

/**
 * @deprecated
 */
function nothing() {
}

/**
 * @deprecated
 */
function setLinkCursor(link) {
    if (link.href.indexOf('nothing') < 0)
        setCursorClass(link, false);
    else
        setCursorClass(link, true);
}

  function setCursor(link) {
    setLinkCursor(link);
  }
/**
 * @deprecated
 */
function showHelp(target) {
    alert(target);
}

/* scrollingTabs course, courseType */
function resetScrollingTabs() {
    try {
        if (typeof(parent.upperframe) != "undefined") {
            parent.upperframe.lastLeftPosition = 0;
        } else if (typeof(top.opener.top.upperframe) != "undefined") {
            top.opener.top.upperframe.lastLeftPosition = 0;
        } else if (typeof(top.opener.top.opener.top.upperframe) != "undefined") {
            top.opener.top.opener.top.upperframe.lastLeftPosition = 0;
        } else {
            top.opener.top.opener.top.opener.top.upperframe.lastLeftPosition = 0;
        }
    } catch (e) {
    }
}

/**
 * Closes the calendar window if exists in a form.
 * Called from imc:body tag within onunload event handler.
 * @see HtmlBodyTag
 * @return
 */
function destroyCalendarPopup() {
    if (typeof(calendarWindow) != "undefined")
        calendarWindow.close();
    hidealllayers(true);
}

/**
 * Shows debug output on firebug console
 * (uncomment one of the other lines to have more interaction!)
 * @param message - message to be displayed
 * @param win - window object, to provide window.name output
 */
function showConfiguration(message, win) {
    if (!win) win = window;
    message = 'Current frame name is ' + win.name + '\n' + message;
	// Debug output to be used with firebug:
    //	if (typeof console == "object") { console.debug(message); console.trace(); }
    //CLIXTOP.Ext.example.msg('Info', message);
    //Ext.Msg.show({ buttons: Ext.MessageBox.OK, modal: false, msg: message, title: "Info" });
    //alert(message);
}
/**
 * @deprecated
 */
function countSigns(s1, s2) {
    var result = 0;
    var s2_length = s2.length;
    var begin;
    var end = s1.indexOf(s2);
    while (end >= 0) {
        result++;
        begin = end + s2_length;
        end = s1.indexOf(s2, begin);
    }
    return result;
}

/**
 * CLIX top frame/window
 */
CLIXTOP = getClixTop(window);
EXTWINDOW = window;

if (typeof Ext != "object") {
    // Search for Ext instance bottom-up
    var target = window;
    var obj = target.Ext;
    while (typeof obj != "object" && target != CLIXTOP && target.parent && target != target.parent) {
        target = target.parent;
        obj = target.Ext;
    }
    if (typeof obj == "object") {
        Ext = obj;
        EXTWINDOW = target;
    } else {
        // There is no Ext object even at the top level frameset, so create an "emergency" object
        // here to be able to use the most essential Ext functionality
        Ext = {
            isArray : function(v) {
                return v && typeof v.length == 'number' && typeof v.splice == 'function';
            },
            get: function() { /* dummy */
            },
            getCmp: function() { /* dummy */
            },
            getBody: function() {
                return document.body;
            },
            ComponentMgr: {
                all: { each: function() { /* dummy */
                } }
            },
            /**
             * Copied from extjs/base/source/core/Ext.js
             */
            urlEncode : function(o) {
                if (!o) {
                    return "";
                }
                var buf = [];
                for (var key in o) {
                    var ov = o[key], k = encodeURIComponent(key);
                    var type = typeof ov;
                    if (type == 'undefined') {
                        buf.push(k, "=&");
                    } else if (type != "function" && type != "object") {
                        buf.push(k, "=", encodeURIComponent(ov), "&");
                    } else if (Ext.isArray(ov)) {
                        if (ov.length) {
                            for (var i = 0, len = ov.length; i < len; i++) {
                                buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
                            }
                        } else {
                            buf.push(k, "=&");
                        }
                    }
                }
                buf.pop();
                return buf.join("");
            },
            urlDecode : function(string, overwrite) {
                if (!string || !string.length) {
                    return {};
                }
                var obj = {};
                var pairs = string.split('&');
                var pair, name, value;
                for (var i = 0, len = pairs.length; i < len; i++) {
                    pair = pairs[i].split('=');
                    name = decodeURIComponent(pair[0]);
                    value = decodeURIComponent(pair[1]);
                    if (overwrite !== true) {
                        if (typeof obj[name] == "undefined") {
                            obj[name] = value;
                        } else if (typeof obj[name] == "string") {
                            obj[name] = [obj[name]];
                            obj[name].push(value);
                        } else {
                            obj[name].push(value);
                        }
                    } else {
                        obj[name] = value;
                    }
                }
                return obj;
            }
        }
    }
}

if (typeof createMessage != "function") {
    // When there is no such function, search for it bottom-up;
    // at least at CLIXTOP there must be one
    var target = window;
    var fn = target.createMessage;
    while (typeof fn != "function" && target != CLIXTOP && target.parent && target != target.parent) {
        target = target.parent;
        fn = target.createMessage;
    }
    if (typeof fn == "function") {
        createMessage = fn;
        showSlidebox = target.showSlidebox;
    }
}

function showInfoLayer(nr, evt) {
    var e = evt || window.event;
    if (!e) return null;
    var layerTop;
    var layerLeft;
    if (IE) {
        // alert("y: "+e.y);
        if (e.y > 300) {
            layerTop = String((e.y + document.body.scrollTop - 20) + "px");
        } else {
            layerTop = String((e.y + document.body.scrollTop ) + "px");
        }

        if (e.x > 400) {
            layerLeft = String((e.x + document.body.scrollLeft - 280) + "px");
        } else {
            layerLeft = String((e.x + document.body.scrollLeft) + "px");
        }

    }
    if (N6) {
        if ((e.pageY - pageYOffset) > 200) {
            layerTop = String((e.pageY - 140) + "px");
        } else {
            layerTop = String((e.pageY + 10) + "px");
        }
        if ((e.pageX - pageXOffset) > 400) {
            layerLeft = String((e.pageX - 280) + "px");
        } else {
            layerLeft = String(e.pageX + "px");
        }
    }

    document.getElementById(nr).style.top = layerTop;
    document.getElementById(nr).style.left = layerLeft;
    document.getElementById(nr).style.visibility = 'visible';


}
function hideInfoLayer(nr) {
    if (IE) {
        document.getElementById(nr).style.visibility = 'hidden';
    }
    if (N6) {
        document.getElementById(nr).style.visibility = 'hidden';
    }
}

function getActiveIFrameName() {
    var n = '';
    var upperwork = findUpperwork();
    if(upperwork){
        var contentFrame = upperwork.parent.contentframe;
        if(contentFrame){
            var mainTabPanel = contentFrame.mainTabPanel;
            if(mainTabPanel){
                var activeTab = mainTabPanel.getActiveTab();
                if(activeTab){
                    var domEl = contentFrame.document.getElementById(activeTab.contentEl.id);
                    if(domEl){
                        n = domEl.name;
                    }
                }
            }
        }
    }
    return n;
}

function getActiveTabTitle() {
    var upperwork = findUpperwork();
    var contentFrame = upperwork.parent.contentframe;
    var mainTabPanel = contentFrame.mainTabPanel;
    var activeTab = mainTabPanel.getActiveTab();
    return activeTab.title;
}

if (Ext.Ajax) {
    // preset Ajax for CLIX
    Ext.Ajax.defaultHeaders = { "X-Response-Type": 3};
}

function openImagePreviewWindow(url, name, noReturn, w, h) {
    var clixWindow = window.open(url, name, "width=" + w + ",height=" + h + ",left=50,top=50,resizable=yes,dependent=no,scrollbars=1", true);
    if (!noReturn) {
        return clixWindow;
    }
}

/* needed for EditLayer */

function getRefToThisFrame() {
    return this;
}


/* needed for editarealine, rubrikline to scroll to top
* ACHTUNG:
* */
function scrollTop() {
    var panel = null;
    if(typeof(contentPanel) != "undefined" && contentPanel != null){
        panel = contentPanel;
    }else if(typeof(EditHelper) != "undefined" && typeof(EditHelper.contentPanel) != "undefined")  {
       panel = EditHelper.contentPanel;
    }

    if (panel != null) {                                           // Editierseite im Content ohne HTML Editor
        panel.body.scrollTo('top', 0, true);
    } else {     // Seite ohne contentPanel
        if(Ext.isIE){
            if(document.getElementById("contentDiv") != null && document.body.scrollTop > 0) { // Editierseite im Content mit HTMLEditor
                document.body.scrollTop = 0;
            } else if(document.body.scrollTop > 0){    // Editierseitem im Layer
                document.body.scrollTop = 0;
           }
        }else{
            if(document.getElementById("contentDiv") != null && document.getElementById("contentDiv").scrollTop > 0) { // Editierseite im Content mit HTMLEditor
                document.getElementById("contentDiv").scrollTop = 0;
            } else if(document.body.scrollTop > 0){                                                                     // Editierseitem im Layer
                document.body.scrollTop = 0;
            }
        }
   }

}


/* needed for editarealine, rubrikline to scroll to an anchor */
function scrollToElement(elemId) {
    var panel = null;
    if(typeof(contentPanel) != "undefined" && contentPanel != null){
        panel = contentPanel;
    }else if(typeof(EditHelper) != "undefined" && typeof(EditHelper.contentPanel) != "undefined")  {
       panel = EditHelper.contentPanel;
    }

    var elem = document.getElementById(elemId);
    if(elem != null){
        var y = 0;
        if (elem.offsetParent) {
            do {
                y = y + elem.offsetTop;
            } while (elem = elem.offsetParent);
        }
        // BEGINN Workaround  Bug 46733
            if(elemId=="publishingDate"){
            y = y-20;
            }
            // ENDE Workaround  Bug 46733
            

        if (panel != null) {                                          // Editierseite im Content ohne HTML Editor
            panel.body.scrollTo('top', y, true);
        } else {
            if(Ext.isIE){
                if(document.getElementById("contentDiv") != null) {     // Editierseite im Content mit HTMLEditor
                    document.body.scrollTop = y;
                } else {  // Layer
                    document.body.scrollTop = y;
                }
            }else{
                if(document.getElementById("contentDiv") != null) {         // Editierseite im Content mit HTML Editor
                    if(y == 0 && document.getElementById("HTMLEditorTitle_" + elemId) != null) {   //elem ist textarea eines HTMLEditors (display: none) ...
                                                                                                   // weg. eines FF Bugs kann zu einem nicht angezeigten Element nicht gescrollt werden
                                                                                                   //  -> für FF wird zum Titel des Editors gescrollt
                        scrollToElement("HTMLEditorTitle_" + elemId)
                    }else{
                        document.getElementById("contentDiv").scrollTop = y;
                    }
                } else {                                                     // Edtierseite  im Layer
                    document.body.scrollTop = y;
                }
            }
        }
    }
}
/**
* The method creates a array with given parameter and values to send to request.
* To extract this values use Event.getParameterValueList(key)
* @param {String} selectedrecords - selected records array from search (e.g. searchPanel.getSelections())
* @param {Array} parameterArray - configuration array (e.g. new Array({requestParameterName: 'entryId', attributeName: 'pf.entry_id'}));)
*                                 requestParameterName - parameter name in request, attributeName - column name in data source
*/
function createParameterContainer(selectedRecords, parameterArray){
    var valuesContainer = new Array();
    for(var i = 0; i < selectedRecords.length; i++){
        var value = '';
        for(var j = 0; j < parameterArray.length; j++){
            if(j > 0) value += ';';
            value += parameterArray[j].requestParameterName + ':' + selectedRecords[i][parameterArray[j].attributeName];
        }
        valuesContainer[i] = value;
    }
    return valuesContainer;
}

function openJobFamilyLandscape(inTab, start, view, tabName) {
    var url = ClixUtils.createEventUrl('role-structure-frontend',
            { view: view || 'general', start: start || '' });
    if (inTab) {
        getClixContentframe().openManagerTab('JobFamily', url, tabName || 'Job Family');
    } else {
        openSpecialWindow(url, 'JobFamily', true);
    }
}

function printDiv(divName) {
    var printDiv = document.getElementById("printDiv");
    if(!printDiv){
        printDiv = document.createElement('div');
        printDiv.id = 'printDiv';
        document.getElementsByTagName("body")[0].appendChild(printDiv);
    }
    var mediaStyle = document.getElementById("mediaStyle");
    if(!mediaStyle){
        mediaStyle = document.createElement("style");
        mediaStyle.type = "text/css";
        document.getElementsByTagName("head")[0].appendChild(mediaStyle);
    }
    var children = document.body.children;
    var cssCode = '@media screen{#printDiv{display:none}}\n@media print{\n';
    for(var i = 0; i <children.length; i ++){
        if("printDiv" != children[i].id){
            cssCode += '#'+children[i].id+'{display:none}\n';
        }
    }
    cssCode += '}';
    if (mediaStyle.styleSheet) {
        mediaStyle.styleSheet.cssText = cssCode;
      } else {
        while(mediaStyle.hasChildNodes()){
            mediaStyle.removeChild(mediaStyle.children[0]);
        }
        mediaStyle.appendChild(document.createTextNode(cssCode));
    }
    var contentDiv = document.getElementById(divName);
    printDiv.innerHTML = contentDiv.innerHTML;
    this.focus();
    this.print();
}
