// Original image sources are stored in this array
var originalImageSources = new Array();

// Number of images hidden (or replaced with our placeholder image)
var hiddenCount = 0;


function modifyEmail( frameId ) {
	hideImages(frameId);
}

// Replace image sources with our placeholder (if the autoloading is disabled)
function hideImages(frameId) {
    if (parent.header_frame.g_autoLoadImages == 0) {
        var doc = document.getElementById(frameId).contentDocument;
        if (!doc) {
            doc = document.frames[frameId].document;
        }
        for (i = 0; i < doc.images.length; i++) {
        	var image = doc.images[i];
            originalImageSources.push(image.src);
            if (image.src.length > 0) {
                doc.images[i].src = "../hidden.png";
                hiddenCount++;
            }
        }
        if (hiddenCount == 0) {
            parent.header_frame.hideDisplayImagesButton();
        } else {
            parent.header_frame.showDisplayImagesButton();
        }
    } else if (typeof(parent.header_frame.updateHeader) == "function") {
        parent.header_frame.updateHeader();
    }
    requestLoadImages();
}

// Restore original images sources
function restoreImages(frameId) {
    if (parent.header_frame.g_autoLoadImages == 0) {
        var doc = document.getElementById(frameId).contentDocument;
        if (!doc) {
            doc = document.frames[frameId].document;
        }
        for (i = 0; i < originalImageSources.length; i++) {
            doc.images[i].src = originalImageSources[i];
        }
    }
}

// Causes application to reload images
function requestLoadImages() {
    location.href = "cmail://loadImages/";
}

function getNodeAtScrollPosition(nodes, scrollPos) {
    var currentNode = null;
    for (var i = 0; i < nodes.length; i++) {

        var node = nodes[i];

        if (node.offsetTop < scrollPos && scrollPos < (node.offsetTop + node.offsetHeight)) {
            if (node.children) {
                // Parent can overlap it's children. Check position of the children also. If there
                // is a proper child element return that instead of the parent.
                // warning: recursion
                var temp = getNodeAtScrollPosition(node.children, scrollPos);
                if (temp) {
                    return temp;
                }
            }
        } else if (node && node.offsetTop > scrollPos) {
            return currentNode;
        }
        currentNode = node;
    }
    return null;
}

var pxfontlowlimit = 22;
var pxfontlowlimit_vga = 26;
var pxfontupperlimit = 102;

// "normalizes" font sizes and line heights so that text is readable in all devices
function modifyFontSizes(frameId) {
    if (parent.body_frame.g_modifyFontSizes == true) {
        var doc = document.getElementById(frameId).contentDocument;
        var nodes = doc.body.childNodes;

        // in vga resolution the minimum font needs to be a little bit bigger to be readable
        if (screen.width == 640 && screen.height == 480) {
            pxfontlowlimit = pxfontlowlimit_vga;
        }

        var modified = [];
    
        // finds the elements needing resizing
        findElementsNeedingNormalization(nodes, modified);
    
        // keep the scroll position
        var node = null;
    	if (parent.pageYOffset != 0) {
    	    node = getNodeAtScrollPosition(nodes, parent.pageYOffset);
    	}

        if (node && node.offsetHeight != 0) {
            // Calculate the repositioning factor for the node to move scroll position
            // after modifications to it's correct relative position. 
            // (scroll position - y position of the node) / node height.
            var fragmentOffsetHeight = (parent.pageYOffset - node.offsetTop) / node.offsetHeight;
            doResize(modified);
            // Scroll window to new position using the factor.
            parent.window.scrollTo(0, node.offsetTop + node.offsetHeight * fragmentOffsetHeight);
        } else {
            // node not found – just resize fonts
            doResize(modified);
        }
    }
}

// finds all the text nodes and if needed re-calculates the font size of their parent elements
function findElementsNeedingNormalization(nodes, modified) {
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (!(node.tagName && node.tagName.match("TABLE"))) { // do not change the font of tables
            if (node.nodeType == 3 && node.parentNode) { // nodeType == 3 => text node
                var parent = node.parentNode;
                // get the actual computed style of the element
                var style = window.getComputedStyle(parent, "");
                // parse font size
                var fs = parseFloat(style.fontSize); // fontSize is px value
                if (!isNaN(fs)) {
                    var normFs = fs;
                    normFs = Math.max(pxfontlowlimit, normFs);
                    normFs = Math.min(pxfontupperlimit, normFs);
                    if (fs != normFs) {
                        // resizing fonts slows next window.getComputedStyle() VERY significantly
                        // store normalized values and modify only after all have been computed
                        modified[modified.length] = parent;
                        modified[modified.length] = normFs + "px";
                        modified[modified.length] = style.lineHeight;
                        // ensure text fits into the line
                        var lh = parseFloat(style.lineHeight); // lineHeight is 'normal' or px
                        if (!isNaN(lh) && normFs >= lh) {
                            var padding = lh - fs; // calculate original padding
                            if (padding > 0) {
                                // if there was some padding in the original document and now the
                                // text is not fitting anymore set line-height to normal =>
                                // browser sets the line-height according to the font-size
                                modified[modified.length - 1] = "normal";
                            } else { // set line-height to be equal to the font-size
                                modified[modified.length - 1] = normFs + "px";
                            }
                        }
                    }
                }
            }
            findElementsNeedingNormalization(node.childNodes, modified);
        }
    }
}

// do the resizing, check findElementsNeedingNormalization for the data structure of 'modified'
function doResize(modified) {
    for (var i = 0; i < modified.length; i++) {
        var node = modified[i++];
        node.style.fontSize = modified[i++];
        node.style.lineHeight = modified[i]; //incremented in the for-clause
    }
}

// Sets the body direction to ltr in mirrored layout if not already set to rtl
function setEmailBodyDirection() {
    var d = parent.frames['body_frame'].document;
    var a = d.getElementsByTagName('html');
    if (a.length > 0) {
        if (a[0].getAttribute('dir') != 'rtl') {
            a = document.getElementsByTagName('html');
            if (a.length > 0) {
                a[0].setAttribute('dir', 'ltr');
            }
        }
    }
}

// Appends body and its childs to left-aligned <p> element in mirrored layout
// if the document direction is not rtl
function setHeaderDirection() {
    var a = document.getElementsByTagName('html');
    if (a.length > 0) {
        if (a[0].getAttribute('dir') != 'rtl') {
            var hd = parent.frames['header_frame'].document;
            var p = hd.createElement('p');
            p.setAttribute('align', 'left');
            var body = hd.getElementsByTagName('body');
            if (body.length > 0) {
                while (body[0].childNodes.length > 0) {
                    p.appendChild(body[0].childNodes[0]);
                }
                body[0].appendChild(p);
            }
        }
    }
}

// Used onLoad when opening mail body frame in mirrored layout
function setDirections() {
    if (parent.body_frame.g_setDirections == true) {
        setEmailBodyDirection();
        setHeaderDirection();
    }
}

// If mail truncate is used in MfE account, it removes all style definitions
// which are needed to show bulleted list correctly.
// We must modify all negative indentions to zero ("0pt") to get bullets shown.
function modifyIndent( frameId ) {
    var doc = document.getElementById(frameId).contentDocument;
    var nodes = doc.body.children;
    doModifyIndent(nodes);
}

function doModifyIndent( nodes ) {
    for (var i=0; i < nodes.length; i++)
    {
        var node = nodes[i];
        var nodestyle = node.style;
        for (var ii=0; ii<nodestyle.length; ii++) {
            if (nodestyle[ii] == "text-indent") {
                var txtIndent = nodestyle.textIndent;
                if( txtIndent.match("-") && txtIndent.match("pt") ) {
                    nodestyle.textIndent = "0pt";
                }
            }
        }
        if (node.children.length) {
        doModifyIndent(node.children);        
        }
    }
}
