/**
 * Dom Utilities
 * Author: Nick Crohn (nick@meltmedia.com)
 */

meld.utilities.DomUtil = {

    /** 
     * XML to HTML Dom converter specifically for IE
     * author: Nick Crohn (nick@meltmedia.com)
     * This utility will create a HTML Dom from a XML node
     */
    xmlToHtmlDom : function(node) {
        var newNode = Element.extend(this.cloneNode(node));
        return newNode;
    },

    /*
     * Wraps any node to mimic the HTML Dom spec
     * Requires: meld.node.NodeWrapper
     */

    wrapNode : function(node) {
        return new meld.node.NodeWrapper(node);
    },

    nodeToString : function(node) {
        var nodeString = "<";
        nodeString += node.nodeName.toLowerCase()+" ";
        for(var i=0;i<node.attributes.length;i++) {
            nodeString += node.attributes[i].nodeName;
            nodeString += "=\""+node.attributes[i].nodeValue+"\" ";
        }
        nodeString += "/>";
        return nodeString;
    },

    /**
     * Will clone any dom node and create a new with all attributes
     */
    cloneNode : function(node, deep) {
        var newNode;
        switch(node.nodeType) {
        case 1:
            // script tag cloning doesn't seem to work, disallow it
            if(node.nodeName.toLowerCase() != "script"){
              if(node.nodeName.toLowerCase() == "input") {
                  // Again for IE as inputs won't take type or name attributes when set through the dom
                  newNode = this.nodeToString(node);
              } else {
                  newNode = new Element(node.nodeName);

                  for(var i=0;i<node.attributes.length;i++) {
                      if(node.attributes[i].nodeName.toLowerCase() == "class") {
                          // This is for IE because it's lame and doesn't properly handle class as an attribute
                          newNode.className = node.attributes[i].nodeValue;
                      } else {
                          newNode.setAttribute(node.attributes[i].nodeName, node.attributes[i].nodeValue);
                      }
                  }
              }
              if(deep) {
                  var next = node.firstChild;
                  while (next) {
                      var childNode = this.cloneNode(next, deep);
                      if(typeof childNode != "object") {
                          newNode.innerHTML += childNode;
                      } else {
                          newNode.appendChild(childNode);
                      }
                      next = next.nextSibling;
                  }
              }
            }
            break;
        case 3:
            newNode = document.createTextNode(node.nodeValue);
            break;
        default:
            //Do Nothing
        }
        return newNode;
    }
};
