var scripts = document.getElementsByTagName('script');
for ( i in scripts ) {
    var script = scripts[i];
    
    if ( !/csrhub\.com\/files\/api\/embed\.js/.test(script.src) )
        continue;
    if ( script.getAttribute('csrhub_widget_initialized') )
        continue;
    
    createWidgetFrame(script);
    script.setAttribute('csrhub_widget_initialized', true);
}

function createWidgetFrame(script) {
    var widgetId = 'csrhubwidget' + Math.floor(Math.random() * 100000);
    
    document.write('<iframe frameborder=\"0\" scrolling=\"no\" style=\"width: 1px; height: 1px;\" id=\"'
        + widgetId
        + '\"></iframe>');
    var widgetRoot = document.getElementById(widgetId);
    if ( widgetRoot.contentDocument )
        widgetRoot = widgetRoot.contentDocument;
    else if ( widgetRoot.contentWindow )
        widgetRoot = widgetRoot.contentWindow.document;
    else
        widgetRoot = widgetRoot.document;
    
    var widgetScript = document.createElement('SCRIPT');
    var attrs = ['rel', 'hash', 'teaser', 'company', 'country', 'cobrand', 'size'];
    for ( i in attrs ) {
        var value = script.getAttribute(attrs[i]);
        if ( value )
            widgetScript.setAttribute(attrs[i], value);
    }
    widgetScript.setAttribute('host_full_url', window.location);
    widgetScript.src = script.src.substring(0, script.src.lastIndexOf('/')) + '/widget-engine.js';
    widgetScript.type = 'text/javascript';

    widgetRoot.open();
    widgetRoot.write(
        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
        + '<html>'
            + '<head>'
                + '<style>body{margin:0px;padding:0px;background:white;}</style>'
                + '<script>widgetId = \"' + widgetId + '\"</script>'
            + '</head>'
            + '<body>'
            + '</body>'
        + '</html>'
    );
    widgetRoot.close();
    widgetRoot.body.appendChild(widgetScript);
}

function resizeWidgetFrame(id, width, height) {
    //alert(id + ' ' + width + ' ' + height);
    var widgetFrame = document.getElementById(id);
    if ( widgetFrame == null )
        return;
    widgetFrame.style.width = width + 'px';
    widgetFrame.style.height = height + 'px';
    widgetFrame.style.display = '';
}

