/*
 * Copyright 2002-2006 Jahia Ltd
 *
 * Licensed under the JAHIA COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (JCDDL), 
 * Version 1.0 (the "License"), or (at your option) any later version; you may 
 * not use this file except in compliance with the License. You should have 
 * received a copy of the License along with this program; if not, you may obtain 
 * a copy of the License at 
 *
 *  http://www.jahia.org/license/
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
/**
 * Utility class to manage XML documents given as String
 */
function XmlUtils() {
}

/**
 * Returns the value of an XML tag
 */
XmlUtils.getNodeValue =
function (content, nodeName) {
    var tmp = content;
    var tag = "<" + nodeName;
    var start = tmp.indexOf(tag);
    if (start > -1) {
        tmp = tmp.substring(start + tag.length);
        start = tmp.indexOf(">") + 1;
    }

    var end = tmp.indexOf("</" + nodeName + ">");

    if (start != -1 && start < end) {
        return tmp.substring(start, end);
    } else {
        delete tmp;
        return null;
    }
}

/**
 * Returns the value of an XML attribute.
 */
XmlUtils.getAttrValue =
function (content, nodeName, attribute) {
    var tmp = content;
    var tag = "<" + nodeName;
    var start = tmp.indexOf(tag);
    if (start > -1) {
        tmp = tmp.substring(start);
    } else {
        return null;
    }
    var end = tmp.indexOf(">");
    tmp = tmp.substring(start, end);
    start = tmp.indexOf(" " + attribute + "=\"");
    if (start == -1) {
        start = tmp.indexOf(" " + attribute.toLowerCase() + "=\"");
    }
    if (start > -1) {
        var value = tmp.substring(start + attribute.length + 3);
        delete tmp;
        return value.substring(0, value.indexOf("\""));
    } else {
        delete tmp;
        return null;
    }
}

/**
 * Splits the Xml string into substrings. Each substring will be the what is betwwen the opening and closing
 * tagName given in parameter.
 */
XmlUtils.splitXml =
function (xmlString, tagName) {
    var result = new Array();
    for (var i = 0; ; i++) {
        var start = xmlString.indexOf("<" + tagName);
        if (start < 0) {
            return result;
        }
        var end = xmlString.indexOf("</" + tagName + ">");
        var offset = 3;
        if (end < 0) {
            end = xmlString.indexOf("/>");
            offset = 2 - tagName.length;
        }
        result[i] = xmlString.substring(start, end + tagName.length + offset);
        xmlString = xmlString.substring(end + tagName.length + offset);
    }
}
