Ext.define('TP.PanletUrl', {
    extend: 'TP.Panlet',

    title: 'url panlet',
    initComponent: function() {
        this.callParent();
        this.xdata.url      = '';
        this.xdata.selector = '';
        this.xdata.keepcss  = true;
        this.reloadOnSiteChanges = true;

        this.loader = {
            autoLoad: false,
            renderer: 'data',
            scope:    this,
            ajaxOptions: { method: 'POST' },
            callback: function(This, success, response, options) {
                var html;
                if(response.status == 200) {
                    /* should we pick only a part of the page */
                    var el;
                    if(this.xdata.selector != '') {
                        /* create pseudo window to render html */
                        el    = new Ext.window.Window({html: response.responseText, x: -10000, y: -10000}).show();
                        var q = el.body.select(this.xdata.selector).elements[0];
                        if(q == undefined) {
                            html = 'ERROR: selector not found';
                        } else {
                            html = q.outerHTML;
                        }
                    } else {
                        html  = response.responseText;
                    }

                    var head = '';
                    /* keep css links */
                    if(this.xdata.keepcss && this.xdata.selector != '') {
                        el.body.select('LINK').each(function(e) {
                            if(!e.dom.outerHTML.match(/thruk_noframes\.css/)) {
                                head = head + e.dom.outerHTML;
                            }
                        });
                        head = '<head>' + head + '<\/head>';
                    }
                    html = '<html style="overflow-x:hidden; overflow-y: hidden;">' + head + '<body>' + html + '<\/body><\/html>';
                    if(el != undefined) {
                        el.destroy();
                    }
                } else {
                    html = 'ERROR: request failed with status: ' + response.status;
                    debug(response);
                }

                /* replace iframe content */
                var iframe = this.items.getAt(1).getEl().dom;

                var ifrm = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
                try {
                    ifrm.document.open();
                    ifrm.document.write(html);
                    ifrm.document.close();
                } catch(e) {
                    /* first reload after changing from external to internal url does not work*/
                    iframe.src = 'about:blank';
                    window.setTimeout(Ext.bind(this.refreshHandler, this, []), 1000);
                }
            }
        };

        this.refreshHandler = function() {
            if(!TP.isSameOrigin(window.location, TP.getLocationObject(this.xdata.url))) {
                /* set external url as src */
                iframe     = this.items.getAt(1).getEl().dom;
                iframe.src = Ext.urlAppend(this.xdata.url, '_dc='+Ext.Date.now())
            } else {
                TP.defaultSiteRefreshHandler(this);
            }
        };

        /* url content should be in an iframe */
        this.add({
            xtype : 'component',
            autoEl : {
                tag : 'iframe',
                src : '',
                style: {
                    border: 0
                }
            }
        });

        this.down('form').add({
            fieldLabel: 'URL',
            xtype:      'textfield',
            name:       'url',
            listeners: {
                change: function(This, newV, oldV, eOpts) {
                    var pan = This.up('panel');
                    var sel = pan.items.getAt(4);
                    var css = pan.items.getAt(5);
                    if(!TP.isSameOrigin(window.location, TP.getLocationObject(newV))) {
                        sel.emptyText = "css selector only supported for internal urls";
                        sel.setValue("");
                        sel.disable();
                        css.disable();
                    } else {
                        sel.emptyText = " ";
                        sel.enable();
                        css.enable();
                        var old = sel.getValue();
                        sel.setValue("");
                        sel.setValue(old);
                    }
                }
            }
        }, {
            fieldLabel: 'CSS Selector',
            xtype:      'textfield',
            name:       'selector'
        }, {
            fieldLabel: 'Keep CSS',
            xtype:      'checkbox',
            name:       'keepcss'
        });

        /* auto load when url is set */
        this.addListener('afterrender', function() {
            if(this.xdata.url == '') {
                this.gearHandler();
            } else {
                this.refreshHandler();
            }
        });
    }
});
