/** Copyright (c) 2001-2011 Laszlo Systems, Inc. All Rights Reserved. */
function Webtop(){
    this.isDHTML = false;
    this.init = function(isDHTML){
        this.isDHTML = isDHTML;
    };

    //Update wrapper's min width
    this.updateMinWidth = function(newWidth){
        getApp().style.minWidth = newWidth+'px';
        document.body.style.minWidth = newWidth+'px';
    };

    //return focus to the <embed> or to an attachment window if one is on top
    this.returnFocus = function(){
        if(this.isDHTML) return;
        var theSwf = getApp();
        if(theSwf) theSwf.focus();
    };

    //call this function to reload an adFrame.
    this.reloadAdFrame = function(adFrame){
        adFrame.location.reload();
    };

    //set the title of the page, title will be a concatenation of preTitle, 
    //browserTitle, postTitle where browserTitle is the original title of the
    //page stored when the app is initialized
    this.originalPageTitle = document.title;
    this.setTitle = function(preTitle,postTitle){
        if(!preTitle) preTitle = "";
        if(!postTitle) postTitle = "";
        document.title = preTitle + this.originalPageTitle + postTitle;
    };

    this.writeApp = function(swfConfig,lzr,debug,backtrace,profile,baseUrl,bgcolor){
        var appUrl = baseUrl + "?lzt=" + (lzr == 'dhtml' ? 'object' : 'swf') + "&lzr=" + lzr + "&debug=" + debug + "&lzbacktrace=" + backtrace + "&profile=" + profile;
        //add config parameters 
        for(var k in swfConfig){
            var value = swfConfig[k];
            appUrl += "&lzmc_" + typeof(value) + "_" + k + "=" + escape(value);
        }
        //pass in the wrapper url to be used in reload
        appUrl += '&lzmc_string_reloadurl=' + escape(location.href);
        var args = {
            url:appUrl,
            bgcolor:bgcolor,
            width:'100%',
            height:'100%',
            id:'lzapp',
            appenddivid:'appDiv'
        }
        if(lzr == 'dhtml'){
            args.history = true;
            lz.embed.dhtml(args);
        }else{
            args.history = false;
            args.accessible = 'false';
            args.allowfullscreen = 'true';
            args.wmode = 'opaque';
            lz.embed.swf(args);
        }
    };

    //Register a JavaScript method as a TextService listener. Whenever the 
    //value associated with the textKey changes, the callback function will be 
    //invoked with a single argument, the new text value.
    this.textServiceReady = false;
    this.textServiceListenerBuffer = [];
    this.addTextListener = function(textKey,callbackString){
        this.textServiceListenerBuffer.push({textKey:textKey,callbackString:callbackString});
        if(this.textServiceReady) this.flushTextListenerBuffer();
    };

    //Called from LZX when TextService is ready to receive listener registrations
    this.flushTextListenerBuffer = function(){
        this.textServiceReady = true;
        while (this.textServiceListenerBuffer.length > 0){
            var params = this.textServiceListenerBuffer.shift();
            lz.embed.setCanvasAttribute('textServiceAddListener',params.textKey+":"+params.callbackString);
        }
    };
}

function Mail(){
    //downloadFile() from the laszlo application when an attachment is clicked
    //@param string url - url of 
    //@param string disp - disposition [attachment/inline]
    this.downloadFile = function(url,disp,subtype,extension,attachinfo,popupY,popupMiddleX){
        if(!disp) disp = "";
        if(!subtype) subtype = "";
        if(!extension) extension = "";
        if(!attachinfo) attachinfo = "";
        popupY = (popupY == null) ? 0 : parseInt(popupY);
        popupMiddleX = (popupMiddleX == null) ? 0 : parseInt(popupMiddleX);

        var mt = navigator.mimeTypes;
        if(!wgBrowser.isff && mt && mt.length){
            //check for installed plugins here and inline any handled types
            var type; var mimetype; var suffixes; var suffix;
            for(type in mt){
                if(mt[type].type){
                    mimetype = mt[type].type;
                    suffixes = mt[type].suffixes;
                    if(suffixes.indexOf(extension) != -1 || mimetype.indexOf(subtype) != -1){
                        disp = "inline";
                    }
                }
            }
        }

        //if content can be handled inline, open a new window otherwise load the attachment
        if(disp == "inline"){
            if(wgBrowser.isie) url = "includes/browserdownload.html?"+escape(url);
            newWin = window.open(url,"_top","width=600,height=400,top=100,left100,toolbar=yes,menubar=yes,location=no,scrollbars=yes,resizable=yes");
        }else{
            wgBrowser.getFrameByName('downloadFrame').location = url;
        }
    }

    this.openComposeWindow = function(emailAddress){
        lz.embed.setCanvasAttribute('js_mailto',emailAddress);
    }
}

function BrowserUtilities(){
    var me = this;

    this.isff = lz.embed.browser.isFirefox;
    this.isie = lz.embed.browser.isIE;
    this.isie7 = this.isie && lz.embed.browser.version == 7;
    this.issafari = lz.embed.browser.isSafari;
    this.isopera = lz.embed.browser.isOpera;
    this.isnetscape = lz.embed.browser.isNetscape;
    this.ischrome = lz.embed.browser.isChrome;
    this.iswebkit = this.ischrome||this.issafari;

    this.iswin = navigator.appVersion.indexOf("Win") != -1;
    this.ismac = navigator.appVersion.indexOf("Mac") != -1;
    this.ismacppc = navigator.platform.indexOf("PPC") != -1;
    this.isunix = navigator.appVersion.indexOf("X11") != -1;
    this.islinux = navigator.appVersion.indexOf("Linux") != -1;

    //holds reference to the framescollection once it's been found
    //see getFrameByName
    this._framesColl = null;

    this._windowHasFocus = true;

    //set a cookie value
    this.setCookie = function (cookieName,cookieValue,nDays){
        var today = new Date();
        var expire = new Date();
        if(nDays == null || nDays == 0) nDays = 1;
        expire.setTime(today.getTime() + 3600000*24*nDays);
        document.cookie = cookieName+"="+escape(cookieValue)+";expires="+expire.toGMTString()+";path=/";//Scopes the cookie to the same scope as cookies set by the server.
    };

    //read a cookie value
    this.readCookie = function(name){
        var nameEQ = name+"=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++){
            var c = ca[i];
            while (c.charAt(0) == ' '){
                c = c.substring(1,c.length);
            }
            if(c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
        }
        return null;
    };

    //Check that cookies are enabled.
    this.cookiesEnabled = function(){
        var v = Math.floor(1000*Math.random());
        this.setCookie('_ce',v);
        return v == this.readCookie('_ce');
    };

    this.getQueryVariable = function(variable){
        var query = window.top.location.search.substring(1);
        var vars = query.split("&");
        for(var i = 0; i < vars.length; i++){
            var pair = vars[i].split("=");
            if(pair[0] == variable) return pair[1];
        }
    };

    //Sets the URL of the top level window
    this.setLocation = function(url){
        top.window.location.href = url;
    };

    //Get the URL of the top level window
    this.getLocation = function(){
        return top.window.location;
    };

    //Opens a URL with the provided target and options. A wrapper around window.open.
    this.openUrlWithOptions = function(url,target,options){
        var test = null;
        if(options !='null' && options != ''){//while the lzx function call pass the 'null' string
            test = window.open(url,target,options);
        }else{
            test = window.open(url,target);
        }
        if(test == null){
            if(this.isie){
                alert('Please disable your popup blocker to use this function.\r\rWarning: Internet Explorer may reload the application if you enable popups.  Be sure to save your work before doing so.');
            }else{
                alert('Please disable your popup blocker to use this function.');
            }
        }
    };

    //get references to the window objects of the hidden frames via the
    //frames collection. document.getElementById would just give reference
    //to the iframe object which doesn't support printing
    this.getFrameByName = function(frameName){
        if(!this['_framesColl']){
            if(document.frames){//Opera, Internet Explorer
                this._framesColl = document.frames;
            }else{
                this._framesColl = window.frames;//Firefox, Safari, Netscape
            }
        }
        if(this._framesColl) return this._framesColl[frameName];
        return null;
    };

    //Display a growl notification if the user's system supports it and the 
    //browser window is in the background.
    this.showDesktopNotification = function(title,message,iconUrl){
        if(window['fluid'] && !me._windowHasFocus){
            window.fluid.showGrowlNotification({
                title: title,
                description: message,
                icon: iconUrl
            });
        }
    };

    //Track if the browser window has focus or not.
    this._onBlur = function(){me._windowHasFocus = false;}
    this._onFocus = function(){me._windowHasFocus = true;}
    if(this.isie){
        document.onfocusin = this._onFocus;
        document.onfocusout = this._onBlur;
    }else{
        window.onfocus = this._onFocus;
        window.onblur = this._onBlur;
    };

    this.invokeMethodToSwf = function(methodName,args){
        try{
            var newArgs = methodName;
            if(args != undefined) newArgs = [newArgs,args.join(',')].join(',');

            var theSwf = getApp();
            if(theSwf) theSwf.callMethod(newArgs);
        }catch (err){
            if(typeof(console) != "undefined"){
                console.error("ERROR in component_iframe.html -> invokeMethodToSwf() -> " + err.message);
            }
        }
    };

    this.callParentPortal = function(methodName){
        if(!this.guid){
            var query = document.location.search.substring(1);
            var vars = query.split("&");
            for(var i = 0; i < vars.length; i++){
                var pair = vars[i].split("=");
                if(pair[0] == 'guid'){
                    this.guid = pair[1];
                    break;
                }
            }
        }
        var args = Array.prototype.slice.call(arguments);
        args.shift();
        var obj = parent.parent.lz.embed.lzapp.canvas[this.guid];
        obj[methodName].apply(obj,args)
    };
}

