/* MindTouch Dream
 * Copyright (C) 2006 MindTouch, Inc 
 * www.mindtouch.com (http://www.mindtouch.com/) <oss@mindtouch.com (mailto:oss@mindtouch.com)>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * http://www.gnu.org/copyleft/gpl.html 
 */

var WidgetManager = Class.create();
WidgetManager.prototype = {
    _version : {
        'Release'   : 'Trunk',
        'Author'    : 'Urs C Muff',
        'Copyright' : '2006, MindTouch, Inc.'
    },
    _nextID : 0,
    _widgetsById : {},
    Mode : 'view',
    Settings : false,
    PADDING_WIDTH : 14,
    PADDING_HEIGHT : 19,

    initialize : function () {},
    toXml : function (node) {
        if (!node) {return null;}
        // TODO: needs support for xml attributes
        if (node.nodeType == 3) {return node.data;}
        var ret = "<" + node.className + ">";
        var child = node.firstChild;
        while (child) {
            ret += this.toXml(child);
            child = child.nextSibling;
        }
        ret += "</" + node.className + ">";
        return ret;
    },
    toXmlFromJson : function (data) {
        // TODO: needs support for xml attributes
        var ret = "";
        for (var elementName in data) {
            var elementValue = data[elementName];
            ret += "<" + elementName + ">";
            if (typeof elementValue == 'string') {
                ret += elementValue;
            } else {
                ret += this.toXmlFromJson(elementValue);
            }
            ret += "</" + elementName + ">";
        }
        return ret;
    },
    toHtmlFromJson : function (data) {
        // TODO: needs support for xml attributes
        var ret = "";
        for (var elementName in data) {
            var elementValue = data[elementName];
            ret += "<span class='" + elementName + "'>";
            if (typeof elementValue == 'string') {
                ret += elementValue;
            } else {
                ret += this.toHtmlFromJson(elementValue);
            }
            ret += "</span>";
        }
        return ret;
    },
    apply_domAttributes : function (node, data) {
        for (var attr in data) {
            var value = data[attr];
            node.setAttribute(attr, value);
        }
    },
    createHtml : function (widgetType, callback) {
        var ID = parent.Widget._nextID++;
        var url = this._getRequestUri("/widget/create/" + widgetType + "?id=" + ID);
        new Ajax.Request(
            url,
            {
                method: 'post',
                onException: function (request, ex) { Widget._handleException('createHtml ('+url+')', ex); },
                onFailure: function (request) { Widget._handleBadResponse('createHtml ('+url+')', request); },
                onSuccess: function (request) { callback(request, ID); }
            }
        );
    },
    insertWidget : function(editor, widgetHtml, widgetID) {
        try {
            editor.insertHTML(widgetHtml);
            var widgetIFrame = this._findWidgetByID(widgetID, editor._doc);
            if (widgetIFrame) {
                this._initIFrame(widgetIFrame);
            }
        } catch (ex) {
            Widget._handleException('insertWidget', ex);
        }
    },
    getWidget : function(node) {
        if (node.widget) {return node.widget;}
        var widgetID = node.getAttribute('widgetID');
        if (!widgetID) {return null;}
        var widget = Widget._getWidgetDivByID(widgetID);
        if (!widget) {return null;}
        node.widget = widget;
        return widget;
    },

    // Widget body load
    initializeEditor : function (doc) {
        var spans = doc.getElementsByTagName('span');
        for (var i = spans.length; i > 0; ) {
            var span = spans[--i];
            if (span.className == 'widget') {
                this._initEditorSpan(span);
            }
        }
    },
    iframe_bodyLoad : function (doc) {
        if (!doc) doc = document;
        var widgetDiv = doc.getElementById('widgetDiv');
        this._initDiv(widgetDiv);
    },
    body_init : function () {
        var spans = document.getElementsByTagName('span');
        for (var i = spans.length; i > 0; ) {
            var span = spans[--i];
            if (span.className == 'widget') {
                this._initSpan(span);
            }
        }
    },
    _htmlEncode_regEx : new RegExp().compile(/[&<>\x22\u0080-\uFFFF]/g),
    htmlEncode : function(str) {
        if(typeof str.replace == 'undefined') str = str.toString();
        return str.replace(this._htmlEncode_regEx, function(s,b) {
            switch (s) {
            case '&': return "&amp;";
            case '<': return "&lt;";
            case '>': return "&gt;";
            case "\xA0": return "&nbsp;";
            case '"': return "&quot;";
            default: return "&#"+s.charCodeAt(0)+";";
            }
        });
    },
    setInnerText : function(node, text) {
        if (!node) {debugger; return;}
        if (typeof node.innerText != 'undefined') {node.innerText = text; }
        else if (typeof node.textContent != 'undefined') {node.textContent = text; }
        else {node.innerHTML = this.htmlEncode(text);}
    },
    clearOpacity : function(node){
        node = $(node);
        var ns = node.style;
        if (document.body.filters) {
            try {
                if (node.filters && node.filters.alpha) {ns.filter = "";}
            } catch(e){}
        } else {
            if(typeof node.textContent != 'undefined') {
                ns.opacity = 1;
                ns.MozOpacity = 1;
            } else {
                if(typeof ns.KhtmlOpacity != 'undefined') {
                    ns.opacity = 1;
                    ns.KhtmlOpacity = 1;
                } else {ns.opacity = 1;}
            }
        }
    },
    setOpacity : function(node, opacity) {
        if(opacity >= 1) {
            if(document.body.filters) {
                this.clearOpacity(node);
                return;
            } else {opacity = 0.999999;}
        } else if(opacity < 0 ) {opacity = 0;}
        node = $(node);
        if(document.body.filters) {
            if(node.nodeName.toLowerCase() == "tr") {
                // FIXME: is this too naive? will we get more than we want?
                var tds = node.getElementsByTagName("td");
                for(var x=0; x<tds.length; x++){
                    tds[x].style.filter = "Alpha(Opacity="+opacity*100+")";
                }
            }
            node.style.filter = "Alpha(Opacity="+opacity*100+")";
            node.style.opacity = opacity;
        } else if(typeof node.textContent != 'undefined') {
            node.style.opacity = opacity; // ffox 1.0 directly supports "opacity"
            node.style.MozOpacity = opacity;
        } else if(typeof node.style.KhtmlOpacity != 'undefined') {
            node.style.opacity = opacity; // 1.3 directly supports "opacity"
            node.style.KhtmlOpacity = opacity;
        } else {
            node.style.opacity = opacity;
        }
    },

    // internal implementation
    _handleException : function(name, ex) {
        debugger;
        alert('Unhandled exception: '+name+': ' + (ex.description ? ex.name + ': ' + ex.description : ex));
        throw ex;
    },
    _handleBadResponse : function(name, request) {
        debugger;
        alert('Request failed: '+name+' (' + request.status + ') ' + request.statusText);
    },
    _setDimentsions : function (widgetIFrame, dimensions) {
        widgetIFrame.style.width = dimensions.width + "px";
        widgetIFrame.style.height = dimensions.height + "px";
    },
    _getWidgetDivByID : function (widgetID) {
        return this._widgetsById[widgetID];
    },
    _initEditorSpan : function (widgetSpan) {
        var widgetType = widgetSpan.getAttribute('widgetType');
        var xmlData = this.toXml(this._findChildElement(widgetSpan));
        var self = this;
        var ID = widgetSpan.getAttribute('widgetID');
        if (!ID) { ID = parent.Widget._nextID++; }
        else if (parent.Widget._nextID <= ID) { parent.Widget._nextID = parseInt(ID,10)+1; }
        var url = this._getRequestUri("/widget/load/" + widgetType + "?mode=edit&settings=true&id=" + ID);
        setTimeout(function() {
			new Ajax.Request(
				url,
				{
					method: 'post', 
					postBody: xmlData,
					onException: function (request, ex) { Widget._handleException('initEditorSpan ('+url+')', ex); },
					onFailure: function(request) { Widget._handleBadResponse('initEditorSpan ('+url+')', request); }, 
					onSuccess: function(request) { self._onEditorSpanLoaded(request, widgetSpan); }
				}
			)
		}, 0);
    },
    _onEditorSpanLoaded : function (request, widgetSpan) {
        try {
            var tmp = widgetSpan.ownerDocument.createElement('span');
            tmp.innerHTML = request.responseText;
            var widgetIFrame;
            var child = tmp.firstChild;
            while (child) {
                var next = child.nextSibling;
                widgetSpan.parentNode.insertBefore(child, widgetSpan);
                if (child.tagName.toLowerCase() == 'iframe') {widgetIFrame = child;}
                child = next;
            }
            widgetSpan.parentNode.removeChild(widgetSpan);
            widgetIFrame.setAttribute('widgetID', widgetSpan.getAttribute('widgetID'));
            this._initIFrame(widgetIFrame);
        } catch (ex) {
            Widget._handleException('_onEditorSpanLoaded', ex);
        }
    },
    _initDiv : function (widgetDiv) {
        widgetDiv.widget = new WidgetInstance(widgetDiv);
    },
    _initSpan : function (widgetSpan) {
        var widgetType = widgetSpan.getAttribute('widgetType');
        var widgetID = widgetSpan.getAttribute('widgetID');
        var xmlData = this.toXml(this._findChildElement(widgetSpan));
        var self = this;
        var url = this._getRequestUri("/widget/tohtml/" + widgetType + "?id=" + widgetID);
        new Ajax.Request(
            url,
            {
                method: 'post', 
                postBody: xmlData,
                onException: function (request, ex) { Widget._handleException('initSpan ('+url+')', ex); },
                onFailure: function(request) { Widget._handleBadResponse('initSpan ('+url+')', request); }, 
                onSuccess: function(request) { self._onSpanLoaded(request, widgetSpan); }
            }
        );
    },
    _onSpanLoaded : function (request, widgetSpan) {
        try {
            var tmp = widgetSpan.ownerDocument.createElement('div');
            tmp.innerHTML = request.responseText;
            var widgetDiv = tmp.firstChild;
            widgetSpan.parentNode.insertBefore(widgetDiv, widgetSpan);
            widgetSpan.parentNode.removeChild(widgetSpan);
            this._initDiv(widgetDiv);
        } catch (ex) {
            Widget._handleException("_onSpanLoaded", ex);
        }
    },
    _initIFrame : function (widgetIFrame) {
        widgetIFrame.widget = new WidgetInstance(widgetIFrame, true);
        var script = widgetIFrame.nextSibling;
        eval('widgetIFrame.widget.data = '+script.text+';');
        script.parentNode.removeChild(script);
    },
    _findChildElement : function (node) {
        var child = node.firstChild;
        while (child && child.nodeType == 3) child = child.nextSibling;
        return child;
    },
    _getInputs : function (form) {
        var inputsA = form.getElementsByTagName('input');
        var inputs = {};
        for (var i = inputsA.length; i > 0; ) {
            var input = inputsA[--i];
            inputs[input.name] = input;
        }
        return inputs;
    },
    _updateDomFromData : function (dataNode, data) {
        // TODO: needs support for xml attributes
        while (dataNode.firstChild) dataNode.removeChild(dataNode.firstChild);
        for (var elementName in data) {
            var elementValue = data[elementName];
            if (elementValue === undefined || elementValue === null) {
                continue;
            }
            var element = dataNode.ownerDocument.createElement('span');
            element.className = elementName;
            dataNode.appendChild(element);
            if (elementValue.constructor != Object) {
                var text = dataNode.ownerDocument.createTextNode(elementValue.toString());
                element.appendChild(text);
            } else {
                this._updateDomFromData(element, elementValue);
            }
        }
    },
    _findWidgetByID : function (ID, doc) {
        if (!doc) {doc = document;}
        var iframes = doc.getElementsByTagName('iframe');
        for (var i = iframes.length; i > 0; ) {
            var iframe = iframes[--i];
            if (iframe.getAttribute('widgetID') == ID) {
                return iframe;
            }
        }
        return null;
    },
    _getRequestUri : function(uri) {
        if (window.location.port != "8081") {
            uri = "/dream" + uri;
        }
        return uri;
    }
};

window.Widget = new WidgetManager();

var WidgetInstance = Class.create();
WidgetInstance.prototype = {
    mainDiv : null,
    mainIFrame : null,
    statusDiv : null,
    dataDiv : null,
    contentDiv : null,
    formDiv : null,
    settingsDiv : null,
    type : null,
    ID : -1,
    data : {},
    settingsShowing : null,
    innerWidget : null,
    outerWidget : null,

    initialize: function(widgetDivOrIFrame, isIFrame) {
        if (!isIFrame) {
            this.mainDiv = widgetDivOrIFrame;
            var divs = this.mainDiv.getElementsByTagName('div');
            for (var i = divs.length; i > 0; ) {
                var div = divs[--i];
                switch (div.className) {
                case 'status': this.statusDiv = div; break;
                case 'data': this.dataDiv = div; break;
                }
            }
        } else {
            this.mainIFrame = widgetDivOrIFrame;
            Event.observe(this.mainIFrame, "resize", this.onIFrameResize.bindAsEventListener(this));
        }
        this.type = widgetDivOrIFrame.getAttribute('widgetType');

        var xmlData = null;
        if (typeof Widget.EditID != 'undefined') {
            this.ID = Widget.EditID;
            var parentWidget = window.parent.parent.Widget._getWidgetDivByID(Widget.EditID);
            if (!parentWidget) return;
            parentWidget.innerWidget = this;
            this.outerWidget = parentWidget;
            Widget._widgetsById[this.ID] = parentWidget;
            xmlData = Widget.toXmlFromJson(parentWidget.data);
        } else {
            this.ID = widgetDivOrIFrame.getAttribute('widgetID');
            if (!this.ID) { this.ID = parent.Widget._nextID++; }
            else if (parent.Widget._nextID <= this.ID) { parent.Widget._nextID = parseInt(this.ID,10)+1; }
            widgetDivOrIFrame.setAttribute('widgetID', this.ID);
            Widget._widgetsById[this.ID] = this;
            if (this.dataDiv)
                xmlData = Widget.toXml(Widget._findChildElement(this.dataDiv));
        }
        if (!isIFrame) {
            this.formDiv = document.getElementsByClassName('widgetForm', this.statusDiv)[0];
            if (this.formDiv)
                this._initFromStatusDiv();
        }
        if (this.dataDiv && xmlData)
            this._request(xmlData);
    },
    toHtml : function() {
        return '<span class="widget" widgetType="'+this.type+'" widgetID="'+this.ID+'">'+Widget.toHtmlFromJson(this.data)+'</span>';
    },
    submitForm : function() {
        this._fillDataFromForm();
        this._applyData();
        this._saveData();
        this.onLeaveSettings();
        this._applyDimensions();
        return false;
    },
    onInputChanged : function() {
        this._fillDataFromForm();
        this._saveData();
    },
    onIFrameResize : function (event) {
        if (this.innerWidget) {
            this.innerWidget.onResize(this.mainIFrame.offsetWidth, this.mainIFrame.offsetHeight);
        }
    },
    onResize : function(width, height) {
        if (this.settingsShowing) {
            var inputs = Widget._getInputs(this.formDiv);
            var widthInput = inputs.width;
            if (widthInput)
                widthInput.value = width + "px";
            var heightInput = inputs.height;
            if (heightInput)
                heightInput.value = height + "px";
        }
    },
    _inline : "inline",
    onEnterSettings : function () {
        this.contentDiv.style.display = "none";
        this.formDiv.style.display = this._inline;
        this.settingsDiv.style.display = "none";
        this.settingsShowing = true;
        this._applyDimensions();
    },
    onLeaveSettings : function () {
        this.contentDiv.style.display = this._inline;
        this.formDiv.style.display = "none";
        this.settingsDiv.style.display = this._inline;
        this.settingsShowing = false;
    },
    hasSettings : true,
    noSettings : function () {
        this.hasSettings = false;
        this.settingsDiv.style.display = "none";
    },

    // internal implementation
    _request : function(xmlData) {
        var self = this;
        var url = Widget._getRequestUri("/widget/load/" + this.type + "?mode=" + Widget.Mode + "&id=" + this.ID);
        new Ajax.Request(
            url,
            {
                method: 'post', 
                postBody: xmlData,
                onException: function (request, ex) { Widget._handleException('request ('+url+')', ex); },
                onFailure: function(request) { Widget._handleBadResponse('request ('+url+')', request); }, 
                onSuccess: function(request) { self._requestOk(request); }
            }
        );
    },
    _requestOk : function(request) {
        try {
            this.statusDiv.innerHTML = request.responseText;
        } catch (ex) {
            /* gets triggered in IE*/
            //debugger;
        }
        this._initFromStatusDiv();
    },
    onMouseEnter : function(event) {
        if (this.leaveTimeout)
            window.clearTimeout(this.leaveTimeout);
        this.leaveTimeout = null;
        if (this.hasSettings)
            this.settingsDiv.style.display = this._inline;
    },
    leaveTimeout : null,
    onMouseLeave : function(event) {
        var self = this;
        if (this.leaveTimeout)
            window.clearTimeout(this.leaveTimeout);
        this.leaveTimeout = window.setTimeout(function() {
            self.settingsDiv.style.display = "none";
        }, 2500);
    },
    _initFromStatusDiv : function () {
        this.formDiv = document.getElementsByClassName('widgetForm', this.statusDiv)[0];
        this.contentDiv = document.getElementsByClassName('widgetContent', this.statusDiv)[0];
        this.settingsDiv = document.getElementsByClassName('widgetSettings', this.statusDiv)[0];

        if (Widget.Mode == 'view') { this.noSettings(); }
// don't have settings popup behavior in view mode
//        Event.observe(this.contentDiv, "mousemove", this.onMouseEnter.bindAsEventListener(this));
//        Event.observe(this.contentDiv, "mouseout", this.onMouseLeave.bindAsEventListener(this));
//        Event.observe(this.settingsDiv, "mousemove", this.onMouseEnter.bindAsEventListener(this));
//        Event.observe(this.settingsDiv, "mouseout", this.onMouseLeave.bindAsEventListener(this));

        var offset = Position.cumulativeOffset(this.contentDiv);
        if (!document.body.filters) {
            // FF hack to place settings, since cumulativeOffset does not quite work
            offset[1] -= 137;
            if (offset[1] < 0) offset[1] = 0;
        }

        Element.setStyle(this.settingsDiv, {left : offset[0] + "px", top : offset[1] + "px"});

        var scripts = this.statusDiv.getElementsByTagName('script');
        for (var i = scripts.length; i > 0; ) {
            var script = scripts[--i];
            try {
                if (script.className == 'data') {
                    var self = this;
                    var initEval = 'self._initializeFromData('+script.text+');';
                    window.setTimeout(function() {
                        eval(initEval);
                    }, 250);
                } else {
                    eval(script.text);
                }
            } catch (ex) {
                Widget._handleException('requestOK', ex);
            }
        }
    },
    _applyData : function () {
        var data = this.data[this.type];
        var node = document.getElementsByClassName(this.type, this.contentDiv)[0];
        var applyFunc = 'self.' + this.type + '_apply';
        var self = this;
        eval('if (typeof '+applyFunc+' != "undefined") '+applyFunc+'(node, data);');
        if (this.settingsShowing === null) {
            if (Widget.Settings)
                this.onEnterSettings();
            else
                this._settingsShowing = false;
        }
    },
    _initializeFromData : function (widgetData) {
        this.data = widgetData;
        Event.observe(this.settingsDiv.getElementsByTagName('a')[0], "click", this.onEnterSettings.bindAsEventListener(this));
        var inputs = Widget._getInputs(this.formDiv);
        if (inputs.submit)
            Event.observe(inputs.submit, "click", this.submitForm.bindAsEventListener(this));
        for (var key in inputs) {
            var inp = inputs[key];
            if (inp != inputs.submit)
                Event.observe(inp, "change", this.onInputChanged.bindAsEventListener(this));
        }

        this._applyData();
        this._fillFormFromData();
        this._applyDimensions();
    },
    _applyDimensions : function () {
        if (typeof Widget.EditID != 'undefined') {
            var parentWidget = window.parent.parent.Widget._getWidgetDivByID(Widget.EditID);
            var widgetViewNode = document.getElementsByClassName(this.type, this.mainDiv)[0];
            if (!widgetViewNode.offsetWidth && !this.settingsShowing) {
                var self = this;
                window.setTimeout(function () {self._applyDimensions();}, 250);
                return;
            }
            if (widgetViewNode.offsetWidth) {
                window.parent.parent.Widget._setDimentsions(parentWidget.mainIFrame, {
                    width: widgetViewNode.offsetLeft+widgetViewNode.offsetWidth+Widget.PADDING_WIDTH, 
                    height: widgetViewNode.offsetTop+widgetViewNode.offsetHeight+Widget.PADDING_HEIGHT
                });
            } else if (widgetViewNode.width) {
                window.parent.parent.Widget._setDimentsions(parentWidget.mainIFrame, {
                    width: parseInt(widgetViewNode.width, 10), 
                    height: parseInt(widgetViewNode.height, 10)
                });
            }
        }
    },
    _saveData : function () {
        if (typeof Widget.EditID != 'undefined') {
            var parentWidget = window.parent.parent.Widget._getWidgetDivByID(Widget.EditID);
            parentWidget.data = this.data;
            return;
        }
        Widget._updateDomFromData(this.dataDiv, this.data);
    },
    _fillDataFromForm : function() {
        var data = this.data[this.type];
        var inputs = Widget._getInputs(this.formDiv);
        for (var attr in inputs) {
            var input = inputs[attr];
            if (input.type == 'submit' || input.type == 'reset') continue;
            if (input.value)
                data[attr] = input.value;
            else if (data[attr])
                delete data[attr];
        }
    },
    _fillFormFromData : function() {
        var data = this.data[this.type];
        var inputs = Widget._getInputs(this.formDiv);
        for (var attr in data) {
            var input = inputs[attr];
            if (input)
                input.value = data[attr];
        }
    }
};

var AppleWidgetManager = Class.create();
AppleWidgetManager.prototype = {
    iframe : null,
    widget : null,
    widgetApi : null,
    data : null,
    identifier : null,
    startupRequest : null,
    onhide : null,
    onshow : null,
    onreceiverequest : null,

    initialize : function (widget, iframe, data) {
        this.iframe = iframe;
        this.widget = widget;
        this.widget.onEnterSettings = this.onEnterSettings;
        this.identifier = widget.type;
        this.data = data;
        var self = this;
        window.setTimeout(function() {self.start(); }, 250);
    },
    applyData : function(data) {
        this.data = data;
        if (this.widgetApi) {this.widgetApi.onDataChanged();}
    },
    start : function() {
        if (!window.WidgetApi) {
            var self = this;
            window.setTimeout(function() {self.start(); }, 250);
            return;
        }
        this.widgetApi = window.WidgetApi;
        this.widgetApi.start();
        this.widget.noSettings();
    },
    onEnterSettings : function() {
        if (this.widget)
            this.widget.settingsShowing = true;
        else
            return;
        if (!this.widgetApi) {
            var self = this;
            window.setTimeout(function() {self.onEnterSettings(); }, 250);
            return;
        }
        this.widgetApi.showbackside();
    },
    preferenceForKey : function(fullKey) {
        if (fullKey.indexOf(this.identifier) !== 0)
            return undefined;
        var key = fullKey.substring(this.identifier.length+1);
        return this.data[key] ? this.data[key] : undefined;
    },
    setPreferenceForKey : function(value, fullKey) {
        if (fullKey.indexOf(this.identifier) !== 0)
            return;
        var key = fullKey.substring(this.identifier.length+1);
        this.data[key] = value;
        this.widget._saveData();
    },
    resizeAndMoveTo : function(left, top, width, height) {},
    setCloseBoxOffset : function(left, top) {},
    setPositionOffset : function(left, top) {},
    prepareForTransition : function(toWhere) {},
    performTransition : function() {},
    createMenu : function() {},
    closestCity : function() {},
    setInnerText : function(node, text) { Widget.setInnerText(node, text); },
    setOpacity : function(node, opacity) { Widget.setOpacity(node, opacity); },
    getRequestUri : function(uri) { return Widget._getRequestUri(uri); },
    defaultShowSettings : function() { return Widget.Settings; },
    resize : function(width, height) {
        if (!document.body.filters) {

            width += 20;

            height += 20;

        } else {

            width += 10;

            height += 10;

        }

        if (window.frameElement) {

            window.frameElement.style.width = width + "px";

            window.frameElement.style.height = height + "px";

        }

        if (this.widget && this.widget.outerWidget) {

            if (!document.body.filters) {

                width += 40;

                height += 20;

            } else {

                width += 10;

                height += 10;

            }

            var bdy = this.widget.mainDiv.ownerDocument.body;

            this.widget.outerWidget.mainIFrame.style.width = parseInt(bdy.leftMargin,10) + parseInt(bdy.rightMargin,10) + width + "px";

            this.widget.outerWidget.mainIFrame.style.height = parseInt(bdy.topMargin,10) + parseInt(bdy.bottomMargin,10) + height + "px";

        }

    }
};
