/*
 * $Id:$
 *
 * Provide support functions for generating HTML easily.
 *
 * Created by Ben of Ideas2Executables
 */


/*
 * Make a new HTML element named "name" using attributes
 * provided by the map of attrs.
 *
 * Extra arguments can be sent in which are the children to use
 * for subnodes of this element.
 *
 * provides a fairly clean way to build up HTML documents.
 */
function $E(name, attrs) {    
    function addTextNode(e, c) {
        var holder = document.createTextNode((c + "").
                                             replace(/&lt;/g, "<").
                                             replace(/&gt;/g, ">").
                                             replace(/&#39;/g, "'").
                                             replace(/&nbsp;/g,"\u00a0").
                                             replace(/&raquo;/g,"\u00BB").
                                             replace(/&laquo;/g,"\u00AB"));
        e.appendChild(holder);
    }
    var autobr = false;
    var e      = null;
    if(attrs) {
        if(attrs['name']) {
            try {
                e = document.createElement("<" + name + " name='" + attrs['name'] + "'>");
            } catch(ex) {
                e = document.createElement(name);
            }
        } else {
            var e = document.createElement(name);
        }
        for(a in attrs) {
            if(a == "class") {
                throw new Error("used an attribute named class in: " + name + ", " + attrs + ". " +
                                "This won't work in IE. Don't do it.");
            }
            
            if(a == "onclick") {
                e.onclick = attrs[a];
            } else if(a == "onchange") {
            e.onchange = attrs[a];
            } else if(a == "onkeyup") {
                e.onkeyup = attrs[a];
            } else if(a == "onkeydown") {
            e.onkeydown = attrs[a];
            } else if(a == "className") {
                e.className = attrs[a];
            } else if(a == "disabled") {
                e.disabled = attrs[a];
            } else if(a.match(/^style_/)) {
                e.style[a.substring(6)] = attrs[a];
            } else if(a == "autobr") {
                autobr = attrs[a];
            } else if(a == "checked") {
                e.checked = e.defaultChecked = attrs[a];
            } else if(a == "for") {
                e.setAttribute(a, attrs[a]);
                e.setAttribute("htmlFor", attrs[a]);
            } else {
                e.setAttribute(a, attrs[a]);
            }
        }
    } else {
        e = document.createElement(name);
    }

    // our children are found as extra arguments sent
    // in
    for(var i = 2; i < arguments.length; i++) {
        var c = arguments[i];
        if(typeof(c) != "object") {
          addTextNode(e, c);
        } else {
            e.appendChild(c);
        }
    }
    return e;
}

