// $Id: rollover_images.js 4458 2006-10-03 09:00:59Z henry $
// Henry Todd, Hildebrand

/*============================================================================

Image swapping script (rollover images) with preloading.

Example Usage:

    <body onload="preloadImages()">
    <img onmouseover="swap(this)" onmouseout="swap(this)"
     src="/images/example.jpg" class="preload" />
    </body>

So long as this script is loaded on the page, and there is an "_over" version
of example.jpg in the images dir (/images/example_over.jpg) it will be
preloaded ready for the mouse events. The key things are the naming of the
"_over" version of the image, and the assignment of the "rollover" class to
the <img>.

GOTCHA: the image filenames can only contain one dot (".")
    
============================================================================*/

function preloadImages() {
    /*
     *  This function is to be called by the onload event handler
     *  It will attempt to preload rollover images for any <img>s
     *  that it finds with the "rollover" class assigned to them.
     */
    var images = document.getElementsByTagName("img");
    var rollovers = new Array();
    
    for (var i = 0; i < images.length; i++) {
        var img = images[i];
        if (img.className == "preload") {
            // we're looking at an <img> with an associated rollover
            // build the URL for the rollover graphic to preload
            var rollover = new Image();
            rollover.src = calculateImagePath(img.src);
            rollovers.push(rollover);
        }
    }
    return true;
}

function swap(image) {
    image.src = calculateImagePath(image.src);
    return true;
}

function calculateImagePath(path) {
    // TODO?: use regex to find last dot instead of assuming there's only one
    bits = path.split("_over");
    if (bits.length == 1) {
        // no match, the path doesn't contain "_over", so add it
        var path_components = bits[0].split(".");
        var rollover_path = "";
        
        var filename = path_components.length - 2;
        path_components[filename] += "_over";
        
        return path_components.join(".");
    } else if (bits.length == 2) {
        // a match, the path contains "_over", so remove it
        return bits[0] + bits[1];
    } else {
        // error, string contains more than one "_over" substring
    }
    
}

function pageSwap(title, image) {
    var sectiontitle = document.getElementById('sectiontitle');
    if (sectiontitle) {
        // only attempt to alter the title if it exists
        sectiontitle.textContent = title; // w3c
        sectiontitle.innerText = title;   // IE
    }

    var sectionimage = document.getElementById('sectionimage');
    if (sectionimage) {
        // only attempt to alter the image if it exists
        sectionimage.src = image;
    }


}
