// Version 2010.08.11
//  by Solomon Chang, changyj@rtfiber.com
function str_to_nodes()
{ var string,
      obj_type, // e.g., `span', `div'
      node_r,   // top node to return at the end of this call
      node_t;

      string   = str_to_nodes.arguments[0];
      obj_type = str_to_nodes.arguments[1];
      node_r = document.createElement(obj_type);

  while(string != '')
   { var re = new RegExp('<[^>/]+>','g'); 
     // `g' must be used or lastIndex will ALWAYS be ZERO!
     var results = [];

     results = re.exec(string);
     if(results == null)
      { // no tags included
        string = string.replace(/&lt;/g,'<');
        string = string.replace(/&gt;/g,'>');
        node_t = document.createTextNode(string);
        node_r.appendChild(node_t);
        return node_r;
      }
     else
      { // one opening tag is found
        var tag, left, right, node_e;

        tag = results[0];  // with enclosing `<' and `>'

        // process pure text before the opening tag
        left = string.slice(0,results.index);
        string = string.slice(results.index);

        node_t = document.createTextNode(left);
        node_r.appendChild(node_t);


        re = RegExp('<([^>/]+)>','g');
        results = re.exec(tag);
        tag = results[1];  // remove enclosing `<' and '>'

        // to find out the correspoding closing tag
        // (NOT necessarily the right-outermost!)
        var depth = -1,
            open  = '<' + tag + '>',
            close = '</' + tag + '>',
            start = -1;

        re = RegExp('</?' + tag + '>','g');
        while(results = re.exec(string))
         { if(results[0] == open)
            { // a opening tag is found
              depth++;
              if(start == -1) { start = re.lastIndex; }
            }
           else
            { // a closing tag is found
              if(depth == 0) { break; }
              depth--;
            }
         }

        // pass the text between the opening and the closing tags to
        // a recursive call
        node_r.appendChild(str_to_nodes(string.slice(start,results.index),tag));

        // save the text after the closing tag for later processing
        string = string.slice(re.lastIndex);
      }
   }
  return node_r;
}

