/*
Copyright (c) 2006 Author
Author: Anil Sharma for the book "Real-World AJAX: Secrets of the Masters"

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/** The following function (class) converts  XML to a tree of objects.
"this.data" gives the top level object that corresponds to the first element of the XML (excluding header).
A nested element is represented by a JavaScript object. By default a nested element is treated as
list type (one to many association). Therefore it is added to an array, which in-turn is stored as the
attribute of the parent object using 'tag name' as the attribute name. If a nested element
has a special attribute called association="one-to-one" then the object is directly stored as the
attribute of the parent object.
Simple nested elements are stored as the attributes of the corresponding JavaScript object.

'class' and 'id' are treated as special attributes. 'class' indicates the class of the object.
'id' represents object identifier. They are stored using __class and __id as attribute names.
*/

function XMLToDataSet() {
   
   this.data = new Object();
}

XMLToDataSet.prototype.fromXml = function(xml) {
    // Special case when JavaScript is loaded from the file system during the development and
    // data is loaded from a WEB server. Firefox requires that the privilege is enabled.
    // It is not required if JavaScript and data are accessed from the same server.
    if (!is_ie && is_ns) {
        try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        } catch (e) {
        alert("Permission UniversalBrowserRead denied.");
        }
    }
    
    // top level object
    this.data = new Object();
    
    var nodes = xml.childNodes;
    
    var rootNode = nodes[nodes.length-1];
    
    
    // store top level objects class and attributes
    if (rootNode.attributes != null) {
        var attr = rootNode.attributes.getNamedItem('class');
        if (attr != null) {
        this.data.__className = attr.value;
        }
        attr = rootNode.attributes.getNamedItem('id');
        if (attr != null) {
        this.data.__id = attr.value;
        }
    }
    
    this.processXMLNode(this.data, rootNode);
    return this.data;
}

XMLToDataSet.prototype.processXMLNode = function(data, parent) {
    
    
    var nodes = parent.childNodes;
    // process the child nodes of the give parent node.
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        
        var doProcess = node.nodeType == Node.ELEMENT_NODE ||
        node.nodeType == Node.DOCUMENT_NODE
        || node.nodeType == Node.DOCUMENT_FRAGMENT_NODE;
        
        if (!doProcess) {
        continue;
        }
        
        var a = node.childNodes;
        if (a.length == 1) {
        var gchild = a[0];
        // This is a simple element case. Store as the attribute of the given object (data).
        if (gchild.nodeType == Node.TEXT_NODE) {
            data[node.tagName] = gchild.data;
            continue;
        }
        }
        
        
        // This is a nested element case.
        // Extract special attributes, class, id and association.
        var myClass = null;
        var id = null;
        var assoc = null;
        var attrs = node.attributes;
        
        if (attrs != null) {
        for (var j = 0; j<attrs.length; j++) {
            var attr = attrs[j];
            data[attr.name] = attr.value;
            if (attr.name == 'class') {
                myClass = attr.value;
                
                } else if (attr.name == 'id') {
                id = attr.value;
                } else if (attr.name == 'association') {
                assoc = attr.value;
            }
        }
        }
        
        // tag name of the nested element that will be used as the attribute name
        var s = nodes[i].tagName;
        
        // JavaScript object is created for the nested element.
        
        var data2 = new Object();
        
        // store reference of the parent usign special attribute name
        data2.__parent = data;
        // store class and id using special attribute names
        data2.__className = myClass;
        data2.__id = id;
        
        if (assoc == 'one_to_one') {
        // it is an one-to-one association case.
        // add the object as an attribute of the parent.
        data[s] = data2;
        } else {
        // it is a one-to-many association case
        
        // retrieve the list (array) that stores the multiple nested elements of the same
        // tag name. This will be present if this is not the first nested element.
        var c = data[s];
        
        if (c) {
            // if the list (array) is present, simply add to it.
            c.push(data2);
            } else {
            // this is the first nested element of the tag name given by 's'.
            // constuct a new list
            c = new Array();
            // list parent is the parent of the objects held by it
            c.__parent = data;
            // the class of the parent is same as the class of objects held by it
            c.__className = myClass;
            // point to the list from the parent using tag name as the attribute
            data[s] = c;
            c.push(data2);
        }
        }
        // recursively process the nested elements of the 'data2'.
        this.processXMLNode(data2, node);
    }
}
