/**
 * This file provides for generic support for generating
 * HTML (and XML). The idea is that you can deal with 
 * high level objects (nodes) and not worry about 
 * string processing and such.
 * 
 * Since version 1.2 relies on Prototype library. (http://prototype.conio.net/)
 *
 * version $Id: htmlGen.js,v 1.4 2007/06/21 15:03:12 kyevenko Exp $
 */


Element.addMethods({
    /**
     * Given an arbitrary node (found by using $(...) for example)
     * you can set its child node to some variable. This replaces
     * any children it may already have.
     */
    setChild: function(element, child) {
        element = $(element);
        element.update();//remove all children
        element.appendChild(child);
        return element;
    },
    
    /**
     * Places this element as a child of New element created from tagName.
     * Example: 
     * <p id="first">Some content...</p>
     * $('first').wrap('div');
     * <div><p id="first">Some content...</p></div> 
     */
    wrap: function(element, tagName) {
        element = $(element);
        var wrapper = document.createElement(tagName);
        element.parentNode.replaceChild(wrapper, element);
        wrapper.appendChild(element);
        return Element.extend(wrapper);
    }
});

//
// Create a fresh element (hence the E) and wire together
// its children.
//
// name - the element name
// attributes - the HTML elements you want for your tag
// content - any number of arguments, arrays, that will be treated
//       as children.
//
// Example:
//  $E('div', {css_fontFamiliy: 'arial', css_fontSize: '30pt'}, "Hello World");
//  $E('a', {href: 'http://www.google.com'}, "Google");
//
function $E(name, attributes, content) {
    function asElt(something) {
        if (typeof something == 'string') {
            var txt = document.createTextNode(something);
            return txt;
        } else {
            return something;
        }
    }

    var elt = document.createElement(name);
    for (var key in attributes) {
        value = attributes[key];
        
        if(!value) {
            // false values are skipped
            continue;
        }

        if (key.indexOf("css_")==0) {
            elt.style[key.substring(4,key.length)] = value;
        } else if(key == "className") {
            elt.className = value;
        } else {
            elt.setAttribute(key, value);
        }
    }
    
    for(var i = 2; i < arguments.length; i++) {
        if(arguments[i] instanceof Array) {
            for(var j = 0; j < arguments[i].length; j++) {
                elt.appendChild(asElt(arguments[i][j]));
            }
        } else {
            elt.appendChild(asElt(arguments[i]));
        }
    }

    return $(elt);
}

