/**********
Copyright 2010 Micah J Cowan. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, this list of
      conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer in the documentation and/or other materials
      provided with the distribution.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Micah J Cowan.

**********/

/*
    This file comprises my JavaScript hack to provide "ruby" text (furigana) and
    inline translation snippets, for Japanese text.  - Micah
*/

function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
                obj = obj.offsetParent;
        }
    }
    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
                obj = obj.offsetParent;
        }
    }
    return curtop;
}

var savedHTML = null;
function put(msg) {
    var output = document.getElementById("output");

    output.innerHTML += msg + "<br/ >";
}

function doResize() {
    // Restore previous contents of the div.
    var savedNum = 0;
    for (var i=0; i < document.body.childNodes.length; ++i) {
        var s = document.body.childNodes[i];
        if (s.className != "nihongo-save")
            continue;
        if (savedHTML[savedNum])
            s.innerHTML = savedHTML[savedNum++];
    }
    positionRuby();
    positionRuby();
}

function positionRuby() {
    // Save "nihongo" contents. NOTE: assumes the number and order of
    // elements with class "nihongo-save" do not change over the course
    // of numerous resizes.
    if (!savedHTML) {
        savedHTML = {};
        var savedNum = 0;
        for (var i=0; i < document.body.childNodes.length; ++i) {
            var s = document.body.childNodes[i];
            if (s.className != "nihongo-save")
                continue;
            savedHTML[savedNum++] = s.innerHTML;
        }
    }

    // Should ruby be handled by us, or will browser do it? Try to find out.
    // XXX: this test doesn't work on MSIE 6, which is incorrectly
    // detected as unsupporting.
    var fixRuby = true;
    try {
        var rps = document.getElementsByTagName("rp");
        var cs = document.defaultView.getComputedStyle(rps[0], null);
        if (cs.getPropertyValue("display") == "none")
            fixRuby = false;
    } catch (err) {
    }

    if (fixRuby) {
        var rts = document.getElementsByTagName("rt");

        // Hide all rp. Better way to do this is to edit the CSS,
        // but not sure how portable that is.
        var rps = document.getElementsByTagName("rp");
        for (var i=0; i < rps.length; ++i) {
            rps[i].style.display = "none";
        }

        for (var i=0; i < rts.length; ++i) {
            var rt = rts[i];
            var tank;
            var ruby = rt.parentNode;

            if (ruby.tagName.toUpperCase() != "RUBY")
                continue;

            // Walk through the children, collecting nodes.
            var sibling = rt.previousSibling;
            if (!sibling || (sibling.tagName && sibling.tagName.toUpperCase() == "RT"))
                continue;

            if (!sibling.tagName
                || !(sibling.tagName.toUpperCase() == "SPAN"
                     && sibling.className == "pre-rt")) {
                // Create a holding "tank" for all non-rt elements,
                // so we can track a total width, etc.
                tank = document.createElement("span");
                tank.className = "pre-rt";
                ruby.insertBefore(tank, rt);
                do {
                    prevSibling = sibling.previousSibling;

                    // Move this into the tank.
                    ruby.removeChild(sibling);
                    tank.insertBefore(sibling, tank.firstChild);
                    if (sibling.tagName
                        && sibling.tagName.toUpperCase() == "RP")
                        sibling.style.display = "none";
                    sibling = prevSibling;
                } while (sibling && (!sibling.tagName ||
                                     sibling.tagName.toUpperCase() != "RT"));
            } else {
                tank = sibling;
            }

            var savedHeight = rt.offsetHeight + 0;
            rt.style.display = "inline-block";
            rt.style.position = "absolute";
            rt.style.textAlign = "center";
            rt.style.top = findPosY(tank) -
                savedHeight * 1.2 + "px";
            rt.style.left = findPosX(tank) + "px";

            if (rt.clientWidth > tank.clientWidth)
                tank.style.width = rt.clientWidth + "px";
            if (rt.clientWidth < tank.clientWidth)
                rt.style.width = tank.clientWidth + "px";
        }
    }

    // Handle translation texts
    var spans = document.getElementsByTagName("span");

    var lastLeft;
    var lastRight;
    var lastTop = 0;
    for (var i = 0; i < spans.length; ++i) {
        var s = spans[i];
        r = s.previousSibling;

        if (s.className != "trx")
            continue;

        s.style.position = "absolute";
        s.style.visibility = "hidden";
        s.style.display = "inline-block";

        // XXX: MSIE counts line-height (which is also too high)
        // as part of the offsetHeight.
        var baseTop = findPosY(r);
        var newTop = baseTop + r.offsetHeight * 1.2;
        var left = findPosX(r);
        var right= left + s.offsetWidth;
        if (s.offsetWidth < r.offsetWidth) {
            s.style.width = r.offsetWidth + "px";
            right = left + r.offsetWidth;
        }
        if (Math.abs(newTop - lastTop) <= 4
            && left <= lastRight) {
            newTop += r.offsetHeight * 0.8;
        }

        lastTop = newTop;
        lastLeft = left;
        lastRight = right;

        s.style.top = newTop + "px";
        s.style.left = lastLeft + "px";
        s.style.visibility = "visible";
    }

    // Install handler on window resize.
    try {
        window.addEventListener('resize', doResize, false);
    } catch (err) {
    }

    // TODO: Make it walk backwards from <rt>, rather than forward from
    // first ruby child; this way we can detect if there's already a
    // span (use an identifying class?), and avoid duplication on
    // reinvocation. Also: why doesn't the ruby move, though the
    // translations do?
}


