﻿var _xmlFilename = null;
var _idToReplace = null;

/*
    Function for swapping out DOM elements with HTML stored in external XML files
*/
function DOMSwap(xmlFilename, idToReplace) {
    _xmlFilename = xmlFilename;
    _idToReplace = idToReplace;
    _xml = null;
    
    if (_xmlFilename != null && _idToReplace != null)
        AttachEvent(window, 'load', domReadyCallback, false);
        //window.addEvent('domready', domReadyCallback);
}

function xmlLoadCallback(xmlDOM) {
    var elem = document.getElementById(_idToReplace);
    if (elem != null && xmlDOM != null) {
        // Transfer the XML DOM to the insertion point
        var html = get_html_dom(xmlDOM);
        
        // Insert document nodes
        if (html != null) {
            for (i=0; i<html.childNodes.length; i++)
                elem.parentNode.insertBefore(html.childNodes[i], elem);
        }
        
        // Remove image
        elem.parentNode.removeChild(elem);
    }
}

function domReadyCallback() {
    var elem = document.getElementById(_idToReplace);
    if (elem != null) {
        // Load text ISI XML
        importXML(_xmlFilename, 'xmlLoadCallback');
    }
}

/*
    Converts an XML DOM to an HTML DOM
*/
function get_html_dom(xmlDOM)
{
    if (xmlDOM == null)
        return null;
    
    // Create document fragment node
    var doc = document.createDocumentFragment();
    
    // Recurse through XML tree and append to the HTML document
    get_html_dom_core(xmlDOM.documentElement, doc);
    
    // Return
    return doc;
}

/*
    Recursive core for get_html_dom
*/
function get_html_dom_core(srcXMLNode, dstHTMLNode)
{
    if (srcXMLNode == null || dstHTMLNode == null)
        return;
    
    switch (srcXMLNode.nodeType) {
        case 1: //ELEMENT_NODE
            var elem = document.createElement(srcXMLNode.nodeName);
            var i;
            
            // Get attributes
            for (i=0; i<srcXMLNode.attributes.length; i++)
                get_html_dom_core(srcXMLNode.attributes[i], elem);
            
            // Recurse through child elements
            for (i=0; i<srcXMLNode.childNodes.length; i++)
                get_html_dom_core(srcXMLNode.childNodes[i], elem);
            
            // Add to parent
            dstHTMLNode.appendChild(elem);
            break;
            
        case 2: //ATTRIBUTE_NODE
            dstHTMLNode.setAttribute(srcXMLNode.nodeName, srcXMLNode.nodeValue);
            if (srcXMLNode.nodeName == "class")
                dstHTMLNode.setAttribute("className", srcXMLNode.nodeValue);
            break;
            
        case 3: //TEXT_NODE
            // Add to parent
            dstHTMLNode.appendChild(document.createTextNode(srcXMLNode.nodeValue));
            break;
            
        case 9: //DOCUMENT_NODE
            insertHTML(srcXMLNode.documentElement, dstHTMLNode);
            break;
    };
}
