
//Namespace allocation
if (!window.webde){window.webde={};}
if (!webde.products) {webde.products={};}
if (!webde.products.os) {webde.products.os = {};}
if (!webde.products.os.util) {webde.products.os.util = {};}

/**
 * @author chha
 * 
 * Alle von außen reingereichten Daten: CallerData
 * 
 * Der Username wird aus der Location rausgezogen, die Spracheinstellung aus
 * dem partnerdata-Attribut der /userdata.js-Scriptes. Dies muß vor Start der qx-
 * Anwendung für den Splashscreen geschehen, also plain-old-js.
 */
webde.products.os.util.CallerData = {
     BASE64S: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+=/',
     /**
     * Decode-Funktion
     * 
     * dekodiert einen String base64
     * 
     * @type static
     * @param encStr {var} (String) base64-String
     * @return {String} dekodierter String
     */
    base64Decode : function(encStr) {
      var bits;
      var decOut = '';
      var i = 0;

      for (;i<encStr.length; i+=4) {
        bits = (this.BASE64S.indexOf(encStr.charAt(i)) & 0xff) << 18 | (this.BASE64S.indexOf(encStr.charAt(i + 1)) & 0xff) << 12 | (this.BASE64S.indexOf(encStr.charAt(i + 2)) & 0xff) << 6 | this.BASE64S.indexOf(encStr.charAt(i + 3)) & 0xff;
        decOut += String.fromCharCode((bits & 0xff0000) >> 16, (bits & 0xff00) >> 8, bits & 0xff);
      }

      if (encStr.charCodeAt(i - 2) == 61) {
        return (decOut.substring(0, decOut.length - 2));
      }
      else if (encStr.charCodeAt(i - 1) == 61) {
        return (decOut.substring(0, decOut.length - 1));
      }
      else {
        return (decOut);
      }
    },
    
    /**
     * Get all values from the partnerdata string as an object.
     */
    getPartnerParameters : function () {
       
        var partnerdata = webde.products.os.userdata ? webde.products.os.userdata.partnerdata : null;
       
        // Fix for Bug #176688: Check partnerdata from URL first!
        var rawString = webde.products.os.util.CallerData.getLocationParameter("partnerdata") || partnerdata;
        
        if (!rawString) {
            return {};
        }

        //ist der Input base64-codiert?
        var isBase64 = new RegExp("^["+this.BASE64S+"]*$");
        if (isBase64.exec(rawString)) {
            rawString = this.base64Decode(rawString);
        }
        //partnerdata sind url-query-codiert, aber eigentlich nicht noch mal eingepackt
        //Wenn aber mind. ein "%3D" und kein "=" im String vorhanden ist ...
        if (rawString.indexOf("%3D") !== -1 && rawString.indexOf("=") === -1) {
            rawString = decodeURIComponent(rawString);
        }
        var partnerData = rawString.split("&");
        var params = {};
        for (var i = 0; i < partnerData.length; i++) {
            //der query-wert ist query-codiert ...
            var splitted = partnerData[i].split("=");
            params[splitted[0]] = unescape(splitted[1]);
        }
        //Nur die ersten 2 Zeichen interessant!
        if (params.lang && params.lang.length>2) {
            params.lang = params.lang.substring(0,2);
        }

        
        webde.products.os.util.CallerData.getPartnerParameters = function () {
            return params;
        };
        
        return params;
    },
    
    /**
     * Get all parameters from URL as an object.
     */
    getUrlParameters : function () {
        var params = {};
        var searchstring = window.location.search.substring(1);  // strip '?'
        var keyValuePairs = searchstring.split("&");

        for (var i=0, l=keyValuePairs.length; i<l; i++) {
            var tmp = keyValuePairs[i].split("=", 2);

            try {
                params[tmp[0]] = decodeURIComponent(tmp[1] || "");
            }
            catch(e) {
                if (e.name != "URIError") {
                    throw e;  // rethrow
                }
                else {
                    params[tmp[0]] = unescape(tmp[1] || "");
                }
            }
        }

        webde.products.os.util.CallerData.getUrlParameters = function () {
            return params;
        };

        return params;
    },
    
    /**
     * Get from a named key from the partnerdata value
     * 
     * @param {String} name - the name for a value in the partnerdata query-string
     * @return {String} the value
     */
    getPartnerParameter: function(name) {
        var params = this.getPartnerParameters();
        return params[name] || "";
    },

    getJSessionFromLocation: function() {
        var match = window.location.href.match(/;JSESSIONID\=(.*?)\?/i);
        if (match) {
            return match[1];
        }
        return "";
    },

    getJSessionFromCookie: function() {
        var match = document.cookie.match(/JSESSIONID\=([^;]*)/i);
        if (match) {
            return match[1];
        }
        return "";
    },
    
    getLangFromCookie: function() {
        var match = document.cookie.match(/SD_LANG\=([^;]*)/i);
        if (match) {
            return match[1];
        }
        return "";
    },
    
    getCountryFromCookie: function() {
        var match = document.cookie.match(/SD_COUNTRY\=([^;]*)/i);
        if (match) {
            return match[1];
        }
        return "";
    },
    
    /**
     * Gets a parameter from the current Url
     * 
     * @param {String} name - get the value for the named query parameter
     * @return {String} query-parameter
     */
    getLocationParameter: function(name){
        var params = this.getUrlParameters();
        if(typeof params !== "undefined" && params) {
          return params[name] || "";  
        }
        return "";
    },

    /**
     * Checks if a given language is available (Config.AVAILABLE_LANGUAGES)
     * 
     * @param {String} lang
     * @return {false | String} The lang String or false if not available
     */
    isLangAvailable: function(lang) {
        if(lang && typeof lang.substr === "function") {
            lang = lang.substr(0,2);
            var langs = (webde.products.os.LangConfig || webde.products.os.Config).AVAILABLE_LANGUAGES;
            if(langs) {
                for(var i=0, j=langs.length; i<j; i++) {
                    if(langs[i] === lang) {
                        return lang;
                    }
                }
            }            
        }
        return false;
    },
    
    /**
     * Try to get the language from url-query or partnerdata values
     * 
     * @param {String} defaultLang
     * @return {String} the lang-value
     */
    getLang: function(defaultLang) {
        var locale = this.getLocationParameter("locale");
        if(locale && locale.length > 1) {var localeLang = locale.substr(0,2).toLowerCase();}
        var ret = 
            this.isLangAvailable(this.getLocationParameter("lang")) || 
            this.isLangAvailable(localeLang) || 
            this.isLangAvailable(this.getPartnerParameter("lang")) ||
            this.getLangFromCookie() ||
            this.isLangAvailable(defaultLang) ||
            this.isLangAvailable("en") ||
            (webde.products.os.LangConfig || webde.products.os.Config).AVAILABLE_LANGUAGES[0];
        return ret.substring(0, 2).toLowerCase();
    },
    
    
    /**
     * Checks if a given country is available (Config.AVAILABLE_COUNTRIES)
     * 
     * @param {String} lang
     * @return {false | String} The lang String or false if not available
     */
    isCountryAvailable: function(country) {
        if(country && typeof country.substr === "function") {
            country = country.substr(0,2).toLowerCase();
            var countries = (webde.products.os.LangConfig || webde.products.os.Config).AVAILABLE_COUNTRIES || ["*"];
            if(countries) {
                for(var i=0, j=countries.length; i<j; i++) {
                    if(countries[i] === "*" || countries[i] === country) {
                        return country;
                    }
                }
            }            
        }
        return false;
    },
    
    /**
     * Try to get the country from url-query or partnerdata values
     * 
     * @param {String} defaultLang
     * @return {String} the lang-value
     */
    getCountry: function(defaultCountry) {

        // Namespace allocation
        if (!window.webde){window.webde={};}
        if (!webde.products) {webde.products={};}
        if (!webde.products.os) {webde.products.os = {};}
        if (!webde.products.os.LangConfig) {webde.products.os.LangConfig = {};}
        if (!webde.products.os.Config) {webde.products.os.Config = {};}
      
        var locale = this.getLocationParameter("locale");
        if(locale && locale.length > 4) {
          var localeCountry = locale.substr(3,2).toLowerCase();
        }
      
        var countries = (webde.products.os.LangConfig || webde.products.os.Config).AVAILABLE_COUNTRIES || [null];
        var dflt = countries[0] || defaultCountry || "de";
        var ret = 
            this.isCountryAvailable(this.getLocationParameter("country")) || 
            this.isCountryAvailable(localeCountry) || 
            this.isCountryAvailable(this.getPartnerParameter("country")) ||
            this.getCountryFromCookie() ||
            this.isCountryAvailable(defaultCountry) ||
            this.isCountryAvailable("en") ||
            dflt;
        return ret.substring(0, 2).toLowerCase();
    },
    
    /**
     * Change the Config-URLs with spezific, allowed Values von partnerdata 
     * ("lang" cann be overwritten with value von href.location value)
     * 
     * Only named keys from available-Object will replaces, first ist default!
     * {'lang': ['en', 'fr', 'es'],
     *  'regCountry': ['us', 'gb']
     * }
     * @param {String} url - From .../#lang#/... to the localized shortcut ../en/..
     * @param {Object} available - key, object for "to be replaced" pairs
     * @return {String} replaced url
     **/
    injectUrl: function(url, available) {
        if (!available) {
            return url;
        }
        var replacedUrl = url || "";
        var partnerParams = this.getPartnerParameters();
        var urlParams = this.getUrlParameters();
        
        for (var key in available) {
            if(typeof available[key] !== "function") {
                newValue = urlParams[key] || partnerParams[key];
                if(newValue && available[key].join("|").indexOf(newValue)!==-1) {
                    replacedUrl = replacedUrl.replace("#"+key+"#", newValue);
                } else {
                    replacedUrl = replacedUrl.replace("#"+key+"#", available[key][0]);
                }                
            }
        }
        /* zu schön, um weggeworfen zu werden.
        url = url.replace(/(?:#([a-z]+)#)/gi, function (m1, m2) {
            return defaultValues[m2] || m1;
        });
        */
        return replacedUrl;
    },
    /**
     * deprecated.
     * @param {String} url
     * @param {String} defaultLang
     */
    injectUrlWithLanguage: function(url, defaultLang) {
        var lang = webde.products.os.util.CallerData.getLang(defaultLang);
        return url.replace("/en/", "/" + lang + "/");
    },
    
    getPin: function() {
        return this.pin;
    },
    
    setPin: function(newPin) {
        this.pin = newPin;
    },
    
    getToken: function() {
        return this.token;
    },
    
    setToken: function(newToken) {
        this.token = newToken;
    },
    
    /*
     * QuickFix: Helper function which decides if a jump to the new migrated client should be done in the
     * index.html of the middleware
     * 
     */
    getSwitchForIncarnation: function(incarnation) {
       var doSwitchForIncarnation = { 
           //ToDo: Better move this to masterconfig.js
           'office_de'   : true,
           'office_eu'   : true,
           'office_us'   : true,
           'workplace_de': false,
           'workplace_eu': false,
           'workplace_us': false
       }[incarnation];
       return doSwitchForIncarnation; 
    }
 };
 
 /** The following part will used from guestlist.html - needs config.js and jquery.js!
  * 
  */
webde.products.os.util.GuestStarter = {
    mountGuest : function() {
        var postData = '{"path":"'+ webde.products.os.util.CallerData.getLocationParameter("path")+
                     '", "token":"'+ webde.products.os.util.CallerData.getLocationParameter("token")+'"}';
        $.ajax({type:"POST",
                url:"/op/@nonymous/user/registerMount?nocache="+(new Date()).getTime(),
                data: postData,
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                //error: function(req, state, error) {console.info("Error wregisterMount",state," - Error:",error);}
                success: webde.products.os.util.GuestStarter.listRootTemp
               });
    },
    listRootTemp : function() {
        $.ajax({url:    "/op/@nonymous/list/?nocache="+(new Date()).getTime(), 
                success: webde.products.os.util.GuestStarter.listRootTempRead,
                dataType: "json"});
    },
    listRootTempRead : function(myList, status) {
        webde.products.os.util.GuestStarter.listFolder();
    },
    listFolder : function() {
        $.ajax({url:    "/op/@nonymous/list/" + 
                        webde.products.os.util.CallerData.getLocationParameter("path") +  
                        "?nocache="+(new Date()).getTime(), 
                success: webde.products.os.util.GuestStarter.getToken,
                error: webde.products.os.util.GuestStarter.folderListingFailed,
                dataType: "json"});
    },
    setUserPin : function() {
        var postData = 
            '{"path":"' + 
            webde.products.os.util.CallerData.getLocationParameter("path") +
            '","pin":"' + 
            webde.products.os.util.CallerData.getPin() + 
            '"}';
        $.ajax({
            url: "/op/@nonymous/user/setPin?nocache=" + (new Date()).getTime(),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            //dataType: "json",
            success: webde.products.os.util.GuestStarter.listFolder
        });
    },
    folderListingFailed : function(XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.status == 401) {
            if (webde.products.os.util.GuestStarter.countRetries() > 2) {
                // max retries, what to do, what to do..
            }
            else {
                webde.products.os.util.GuestStarter.incrementRetries();
                webde.products.os.util.GuestStarter.askUserForPin();
            }
        } else {
            // general error, don't know what to do yet..
        }
    },
    incrementRetries : function() {
        if (webde.products.os.util.GuestStarter.retries === undefined) {
            webde.products.os.util.GuestStarter.retries = 0;
        }
        webde.products.os.util.GuestStarter.retries = webde.products.os.util.GuestStarter.retries + 1;
    },
    countRetries : function() {
        return webde.products.os.util.GuestStarter.retries;
    },
    askUserForPin : function() {
        var pinDialogBox = '<div style="position:absolute; left:100px; right: 100px"><p>Es ist ein Kennwort für den Zugriff auf die Freigabe erforderlich,<br/>welches Sie in einer separaten E-Mail erhalten haben.</p><input id="pininput"/><input type="submit" value="Ok"/></div>';
        $("body").append(pinDialogBox);
                
        //webde.products.os.util.CallerData.setPin("54321");
        webde.products.os.util.GuestStarter.setUserPin();
    },
    getToken : function() {
        $.ajax({url: "/op/@nonymous/propget/" +
                     webde.products.os.util.CallerData.getLocationParameter("path") +
                     "?nocache=" + (new Date()).getTime(),
                success: webde.products.os.util.GuestStarter.mediaJump,
                dataType: "json"});
    },
    mediaJump : function(myList, status) {
        var token;
        
        if (myList) {
            if (myList.length > 0) {
                for (var i = 0; i < myList.length; i++) {
                    var filename = myList[i].name;
                    if (webde.products.os.util.CallerData.getLocationParameter("path") === filename) {
                        token = myList[i].downloadtoken;
                    }
                }
            }
            else {
                token = myList.downloadtoken;
            }
        }
        
        if (token){
            webde.products.os.util.CallerData.setToken(token);
            webde.products.os.util.GuestStarter.changeLocation();
        }
        
    },
    changeLocation : function() {
        var photoShowUrl = webde.products.os.Config.DATA_URL_ROOT + 
                           "@nonymous/mediaRss/" +
                           webde.products.os.util.CallerData.getLocationParameter("path") + 
                           "?token=" + webde.products.os.util.CallerData.getToken();
        var mediaUrl = webde.products.os.Config.FOTO_SHOW_URL + "#" + encodeURIComponent("/"+photoShowUrl);
        document.location = mediaUrl;
    }
    
};






/*******************************************************************
 *  LOADER LOADER LOADER LOADER LOADER LOADER LOADER LOADER LOADER *
 *******************************************************************
 * 
 *    Smartdrive Loader Class: Provides the necessary methods for loading the QX Client or SD Widget
 *
 *    ATTENTION:
 *        - All methods below "_loadScript" need to be called in the same order as implemented here
 *        - After calling any method that is using "_loadScript" the current script tag must be closed due to asynchronous / timing problems otherwise
 *        - If in doubt see the current index.template.html file for the correct order and fractionation of the script tags 
*/
(function() {

    var loader = {
        
        // Private method to check if a value is contained within a given array
        _arrayContains : function (arr, val) {
            for(var i=0, j=arr.length; i<j; i++) {
                if(arr[i] === val) {
                    return true;
                }
            }
        },

        // Private method to apply definition to context if not in blacklist
        _applyDefinition : function (def, context, blacklist) {
            context = context || this;
            blacklist = blacklist || [];
            for (var key in def) {
                if(typeof def[key] !== "function") {
                    var val = def[key];
                    if(!this._arrayContains(blacklist, key) && typeof val !== "function") {
                        this[key] = val;
                    }                    
                }
            }
        },


        // TODO: noCache Cachetime konfigurierbar
        // Private method to load a script by using document.write to inject a script tag
        _loadScript : function (url, noCache) {
            if(noCache) {
              //url
            }
            document.write("<sc" + "ript type=\"text/javascript\" charset=\"UTF-8\" src=\"" + url + "\"><\/script>");
        },
        
        // Private method which returns the configured URL of the IAC library file
        _getIacFileUrl : function () {
          return webde.products.os.Config.IAC ? webde.products.os.Config.IAC.FILE_URL : webde.products.os.Config.IAC_FILE_URL;
        },
        
        // Private method that checks if PLUPLOAD shall be used / loaded
        _pluploadEnabled : function() {
            //alert("_pluploadEnabled: " + webde.products.os.Config);
            return (
                    webde.products.os.Config.PLUPLOAD_ACTIVATEABLE_VIA_LOCATION &&
                    webde.products.os.util.CallerData.getLocationParameter("useplupload") === "true"
                ) || webde.products.os.Config.PLUPLOAD_FILE_UPLOAD_ENABLED;
        },


        /**
         * Initializes the currently active user and session.
         * If the active user is a guest an empty userdata record is applied to webde.products.os.userdata
         * 
         * Attention: 
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         *      - MUST be called as first method within the HTML BODY because the other methods rely on it
         */
        initUserAndSession : function () {
            if(webde.products.os.util.CallerData.createFavIcon) {
                webde.products.os.util.CallerData.createFavIcon();
            }  
            
            //Check for guest user
            var username = webde.products.os.util.CallerData.getLocationParameter("username") || "@nonymous";
            var jsession = webde.products.os.util.CallerData.getJSessionFromLocation();
            if (username.indexOf("@nonymous") !== 0) {
                var jStr = jsession ? ";jsessionid=" + jsession : "";
                this._loadScript("/userdata.js" + jStr + "?username=" + username + "&noCache=" + new Date().getTime());
            }
            else { // guest user, generate empty userdata record
                webde.products.os.userdata = {
                    sessionid       : jsession,
                    username        : username,
                    salutation      : "",
                    firstname       : "Gast",
                    lastname        : "Nutzer",
                    originserver    : "",
                    originsession   : "",
                    payuser         : false
                };
            }
            
            
            
            ///////////////////////////////////////////////////////
            // dalk: TESTING
            ///////////////////////////////////////////////////////
            
            //sessionid in userdata löschen, wenn cookie vorhanden!
            if (webde.products.os.userdata && webde.products.os.userdata.sessionid && cookie) {
              webde.products.os.userdata.sessionid = "";
            }
      
            webde.products.os.userdata = webde.products.os.userdata || {username:""};
            webde.products.os.userdata.isGuestUser = webde.products.os.userdata.username.indexOf("@nonymous") === 0 || (webde.products.os.util.Location && webde.products.os.util.Location.hasParameter("guestuser"));
            
            /*  
               check for webde.products.os.userdata.payuser=="0" moved to application.js
           */
            
        },


        /**
         * Applies the client specified by master-config, CallerData and LocationParameter
         * 
         * Attention: 
         *      - MUST be called from the HTML HEAD and before any other of the methods below 
         */ 
        applyClient : function (incarnation) {
            var config, clientDef;
            
            // Get config, default incarnation and client definition
            config = com.unitedinternet.masterconfig;
            if(typeof config === "undefined" || !config || !config.clients) {
                this.doNotStart = true;
                return;
            }
            clientDef = config.clients;
            this.incarnation =  incarnation || config.incarnation; 
            
            // Assign defaults from the client definition
            this._applyDefinition(clientDef, this, ["incarnations"]);
            
            // Overwrite default incarnation by callerdata
            if(config.allowConfigByCallerdata) {
                this.incarnation = webde.products.os.util.CallerData.getPartnerParameter("incarnation") || this.incarnation;
                
                // WebDesk-Hack: to make Workdesk work ASAP! (it would be better to set the incarnation directly via partnerdata!)
                var comid = webde.products.os.util.CallerData.getPartnerParameter("comid");
                if(comid) {
                  this.incarnation = "workplace_eu";
                  var ctr = webde.products.os.util.CallerData.getCountry("de");
                  if(ctr === "us" || ctr === "ca") {
                    this.incarnation = "workplace_us";
                  }
                }
            }
            
            // Overwrite default incarnation by URL / location parameter
            if(config.allowConfigByUrl) {
                this.incarnation = webde.products.os.util.CallerData.getLocationParameter("incarnation") || this.incarnation;
            }
            
            // Apply incarnation definition
            this._applyDefinition(clientDef.incarnations[this.incarnation]);
            
            // inject meta tag with version info here!
            var meta = document.createElement("META");
            meta.setAttribute("name","application.clientversion");
            meta.setAttribute("content",""+this.version);
        },


        /**
         * Loads the correct configuration file depending on the selected application
         * and incarnation. Also loads the features file if useFeatures is true
         *
         * Attention: 
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         */
        loadConfig : function () {
            // dakl: Quick Hack to make GMX.de Live work: Check if config was already loaded
            if(!this.configLoaded && !this.doNotStart) {
                this.configLoaded = true;
                if(this.useFeatures) {
                    com.unitedinternet.loader._loadScript(this.jsPath+"features-"+this.incarnation+".js");
                }
                com.unitedinternet.loader._loadScript(this.jsPath+"config-"+this.incarnation+".js");
            }
        },
        
        /**
         * Loads the correct CSS file and favicon by injecting link tags via document.write
         * 
         * Attention: 
         *      - MUST be called from within the HTML HEAD and after "applyClient" 
         */
        loadCssAndFavicon : function () {
            if(!this.doNotStart) {
                if(this._pluploadEnabled()) {
                    document.write("<li" + "nk type=\"text/css\" rel=\"stylesheet\" href=\"" + this.jsPath + "html/plupload/examples/css/plupload.queue.css\"><\/link>");
                }
                document.write("<li" + "nk type=\"text/css\" rel=\"stylesheet\" href=\"" + this.contentPath + "css/style.css\"><\/link>");
                document.write("<li" + "nk type=\"image/vnd.microsoft.icon\" rel=\"icon\" href=\"" + this.contentPath + "favicon.ico\"><\/link>");                
            }
        },
        
        
        
        
        //              PLUPLOAD
        loadJSAPI           : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript("http://www.google.com/jsapi");
            }
        },
        loadJQuery          : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                google.load("jquery", "1.3");
            }
        },
        loadGears           : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/gears_init.js");
            }
        },
        loadBrowserPlus     : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript("http://bp.yahooapis.com/2.4.21/browserplus-min.js");
            }
        },
        
        //          PLUPLOAD PROD
        loadPlupload        : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/js/plupload.full.min.js");
            }
        },
        loadPluploadQueue   : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/js/jquery.plupload.queue.min.js");
            }
        },
        //          PLUPLOAD PROD
        
        //          PLUPLOAD DEV
        loadPluploadDev                 : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.js");
            }
        },
        loadPluploadDev_Gears           : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.gears.js");
            }            
        },
        loadPluploadDev_Silverlight     : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.silverlight.js");
            }
        },
        loadPluploadDev_Flash           : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.flash.js");
            }
        },
        loadPluploadDev_Browserplus     : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.browserplus.js");
            }
        },
        loadPluploadDev_HTML4           : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.html4.js");
            }
        },
        loadPluploadDev_HTML5           : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/plupload.html5.js");
            }
        },
        loadPluploadQueueDev            : function() {
            if(this._pluploadEnabled() && !this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.jsPath+"html/plupload/src/javascript/jquery.plupload.queue.js");
            }
        },
        //          PLUPLOAD DEV
        
        //              PLUPLOAD
        
        



        /**
         * Applies the correct theme to window.qxsettings and thus overwrites the values 
         * of the original configuration file that was loaded by loadConfig
         */
        applyTheme : function () {
            if(!this.doNotStart) {
                window.qxsettings["qx.resourceUri"]=location.protocol+this.themePath;
                window.qxsettings["qx.theme"]="webde.products.os.theme." + this.theme+"Theme";                
            }
        },


        /**
         * Applies the session to webde.products.os.userdata.sessionid and
         * redirects to LOGIN_ERROR_GOTO if no valid session was found
         */        
        applySession : function () {
            if(!this.doNotStart) {
                if (webde.products.os.util.CallerData.getJSessionFromLocation()) {
                    webde.products.os.userdata.sessionid = webde.products.os.util.CallerData.getJSessionFromLocation();
                }

                if (!webde.products.os.util.CallerData.getJSessionFromCookie()) {
                    if (!webde.products.os.userdata.sessionid && webde.products.os.userdata.username !== "@nonymous") {
                        if (webde.products.os.Config.LOGIN_ERROR_GOTO) {
                            window.location.href = webde.products.os.Config.LOGIN_ERROR_GOTO;
                        }
                    }
                }
            }
        },


        /**
         * Loads the Qooxdoo framework file
         * 
         * Attention: 
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         */
        loadQooxdoo : function () {
            if(!this.doNotStart) {
                com.unitedinternet.loader._loadScript(this.qxPath+"qx.js");
            }
        },


        /**
         * Inserts a splash screen within an iframe if showSplashScreen is true
         */
        insertSplashScreen : function () {
            if(this.showSplashScreen && !this.doNotStart) {
                var splashUrl = webde.products.os.Config.SPLASH_SCREEN_IFRAME_NOPAYUSER;
                if (webde.products.os.userdata.payuser && webde.products.os.Config.SPLASH_SCREEN_IFRAME_PAYUSER) {
                    splashUrl = webde.products.os.Config.SPLASH_SCREEN_IFRAME_PAYUSER;
                }
                document.write(
                    '<div id="splashScreen" style="width:100%;height:100%;">\n' +
                    '    <iframe src="' + splashUrl + '" scrolling="no" frameborder="0" width="100%" height="100%"></iframe>' +
                    '</div>'
                );
            }
        },


        /**
         * Loads the sendmail IAC file if ACTION_SENDMAIL is set to "iac" in features
         * 
         * Attention:
         *      - Do not mistake this for the "loadIac" method below!
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript 
         */
        loadSendmailIac : function () {
            var iacFileUrl = this._getIacFileUrl();
            if (iacFileUrl && webde.products.os.features && (webde.products.os.features.ACTION_SENDMAIL === "iac" || webde.products.os.features.ACTION_SENDMAIL === "iacv1") && !this.doNotStart) {
                this._loadScript(iacFileUrl);
            }
        },


        /**
         * Applies the needed configuration variables back to webde.products.os.Config.*
         * Currently only sets the appPath but additional variables may follow
         */
        applyConfigVariables : function () {
            if(!this.doNotStart) {
                webde.products.os.Config.appPath = this.jsPath;    
            }
        },
        
        
        /**
         * Loads the correct IAC Wrapper and IAC Mapping file if IAC.FILE_URL is set
         *
         * Attention:
         *      - Do not mistake this for the "loadSendmailIac" method above!
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         */  
        loadIac : function () {
            if(!this.doNotStart) {
            
                // Also load TIF Pixel file
                var agofUrl = webde.products.os.Config ? webde.products.os.Config.AGOF_URL : false;
                if(agofUrl) {
                    this._loadScript(agofUrl);
                }
            
                var iacFileUrl = this._getIacFileUrl();
                if(iacFileUrl && webde.products.os.Config.IAC) {
                    // Namespace
                    var com = com || {};
                    com.unitedinternet = com.unitedinternet || {};
                    com.unitedinternet.portal = com.unitedinternet.portal || {};
                    com.unitedinternet.portal.iac = com.unitedinternet.portal.iac || {};
                    com.unitedinternet.portal.navigator = com.unitedinternet.portal.navigator || {};
                    
                    // Load IAC Files
                    this._loadScript(iacFileUrl);
                    var type = webde.products.os.Config.IAC.TYPE;
                    var mappingType = webde.products.os.Config.IAC[this.appname.toUpperCase()].MAPPING_TYPE;
                    this._loadScript(this.jsPath+"iac_" + type + ".js");
                    this._loadScript(this.jsPath+"iac_" + (mappingType || type) + "_mapping.js");
                }
            }
        },


        /**
         * Loads the correct language file, sets the locale and applies the i18nized HTML title
         *
         * Attention:
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         */
        loadLanguage : function () {
            if(!this.doNotStart) {
                var locale = webde.products.os.util.CallerData.getLang((webde.products.os.LangConfig || webde.products.os.Config).AVAILABLE_LANGUAGES[0]);
                this._loadScript(this.jsPath + locale + ".js");
                qx.locale.Manager.getInstance().setLocale(locale);
                document.title = webde.products.os.Config.TEXTS.pageTitle;
            }
        },


        /**
         * Loads the actual application javascript file
         *
         * Attention:
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         */
        loadApplication : function () {
            if(!this.doNotStart) {
                this._loadScript(this.jsPath+this.appfilename+".js");
            }
        },


        /**
         * Loads the workarounds javascript file if useWorkarounds is set to true
         *
         * Attention:
         *      - Script tag MUST be closed after the call to this method because it uses _loadScript
         */
        loadWorkarounds : function () {
            if(this.useWorkarounds && !this.doNotStart) {
                this._loadScript(this.jsPath+"workarounds.js");
            }
        },


        /**
         * Sets the correct logger, starts the application and 
         * calls the initializeIAC
         *
         * Attention:
         *      - This has to be the last method to be called from within the index.template.html
         */
        startApplication : function () {
            if(!this.doNotStart) {
                qx.log.Logger.ROOT_LOGGER.setMinLevel(qx.log.Logger.LEVEL_OFF);
                if (webde.products.os.util.CallerData) {
                    if (webde.products.os.util.CallerData.getLocationParameter("debug") || webde.products.os.util.CallerData.getPartnerParameter("debug")) {
                        qx.log.Logger.ROOT_LOGGER.setMinLevel(qx.log.Logger.LEVEL_DEBUG);
                    }
                }
                qx.core.Init.getInstance().setApplication(new webde.products.os.Application(com.unitedinternet.smartdrivewidgets));
                
                this.initializeIAC();
            }
        },
        
        /**
         * Calls the initialize method of the IAC Wrapper if the wrapper was loaded
         *
         * Attention:
         *      - This has to be the last method to be called from within the index.template.html
         */
        initializeIAC : function () {
          if(!this.doNotStart) {
              if (
                  com && 
                  com.unitedinternet && 
                  com.unitedinternet.smartdrivewidgets && 
                  typeof com.unitedinternet.smartdrivewidgets.initialize == "function"
              ){
                  com.unitedinternet.smartdrivewidgets.initialize();
              }
          }
        }
    };
    
    // Apply loader class to namespace
    com = window.com || {};
    com.unitedinternet = com.unitedinternet || {};
    com.unitedinternet.loader = loader;
    
    // dakl: Quick Hack to make GMX.de Live work:
    //com.unitedinternet.loader.applyClient("gmx_de");
    //com.unitedinternet.loader.loadConfig();
})();

