/*
 * $Id:$
 *
 * Provide support functions for generating HTML easily.
 */


/*
 * 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.
 * created by FIXIA  2007 -  sales@fixia.com
 */
function $E(name, attrs) {    
    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 {
            e.setAttribute(a, attrs[a]);
        }
    }

    // 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") {
            var holder = document.createTextNode((c + "").replace(/&nbsp;/g,"\u00a0"));
            e.appendChild(holder);
        } else {
            e.appendChild(c);
        }
    }
    return e;
}

/*
 * Provide a mechanism for placing an HTML element
 * near another
 */
var 
Arrange =  {
    /*
     * make html element target be near the goal
     *
     */
    near: function(target, goal) {
        function hasWidth(elt) {
            return elt.offsetWidth != document.body.offsetWidth && elt.offsetWidth != document.body.clientWidth;
        }
        function hasHeight(elt) {
            return elt.offsetHeight != document.body.offsetHeight && elt.offsetHeight != document.body.clientHeight;
        }

        var pos = RicoUtil.toDocumentPosition(goal);
        if((pos.y >  document.body.offsetHeight / 2)  && hasHeight(target)) {
            pos.y -= target.offsetHeight - goal.offsetHeight;
        }
        if((pos.x > document.body.offsetWidth / 2) && hasWidth(target)) {
            pos.x -= target.offsetWidth - goal.offsetWidth;
        }

        target.style.position = 'absolute';
        target.style.top =  pos.y + "px";
        target.style.left = pos.x + "px";
    }

}

/*
 * Trim function, used to trim a string like you would want it to
 */
String.prototype.trim =  function(str) {
    str = this != window? this : str;
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
