// footer.html must be after email.js, header_frame and body_frame in email.html/email_rtl.html

var bodyDocument = parent.body_frame.document;

var timerId;

var initBodyCompleted = false;

// listen when DOM content of the body is loaded 
bodyDocument.addEventListener("DOMContentLoaded", initBody, false);

// just to be on the safer side (eg. broken css link -case), listen also the window onload
parent.body_frame.onload = bodyLoaded;

initBody();

function initBody() {
    if (/loaded|complete/.test(bodyDocument.readyState)) {
        bodyDocument.removeEventListener("DOMContentLoaded", initBody, false);

        // it might be that external css is not loaded yet => start polling it. 
        timerId = setInterval(pollCss, 50); // milliseconds
        pollCss();
    }
}

function pollCss() {
    var links = bodyDocument.getElementsByTagName("link");
    
    var cssLoaded = true;

    // check that every external stylesheet is populated into the document object
    for (var i = 0; i < links.length && cssLoaded; i++) {
        var link = links[i];
        if (link.rel === "stylesheet") {
            cssLoaded = findStyleSheet(link.href);
        }
    }
    
    if (cssLoaded && !initBodyCompleted) {
        clearInterval(timerId);
        parent.modifyIndent("body_frame");
        parent.modifyFontSizes("body_frame");
        initBodyCompleted = true;
    }
}

function findStyleSheet(href) {
    var ret = false;
    var styleSheets = bodyDocument.styleSheets;
    for (var i = 0; i < styleSheets.length && !ret; i++) {
        var sheet = styleSheets[i];
        if (sheet.href === href) {
            ret = true;
        }
    }
    return ret;
}

function bodyLoaded() {
    if (!initBodyCompleted) {
        clearInterval(timerId);
        parent.modifyIndent("body_frame");
        parent.modifyFontSizes("body_frame");
        initBodyCompleted = true;
    }
}
