﻿var XBXPath = function() {
    this.isOpera = false;
    this.isIE = false;
    this.isMozilla = false;
    if (typeof (ActiveXObject) != 'undefined')
        this.isIE = true;
    else if (typeof (XPathEvaluator) != 'undefined')
        this.isMozilla = true;
    else if (window.opera)
        this.isOpera = true;
}

XBXPath.prototype.selectSingleNode = function(xmlDoc, elementPath) {
    if (this.isIE) {
        return xmlDoc.selectSingleNode(elementPath);
    }
    else if (this.isMozilla) {
        var xpe = new XPathEvaluator();
        var results = xpe.evaluate(elementPath, xmlDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        return results.singleNodeValue;
    }
    else if (this.isOpera) {
        var xpe = xmlDoc;
        if (!xpe.evaluate)
            xpe = xpe ? xpe.ownerDocument : false;
        if (xpe && xpe.evaluate) {
            var results = xpe.evaluate(elementPath, xmlDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            return results.singleNodeValue;
        }
    }
}

XBXPath.prototype.selectNodes = function(xmlDoc, elementPath) {
    var res = [];
    if (this.isIE) {
        res = xmlDoc.selectNodes(elementPath);
    }
    else if (this.isMozilla) {
        var xp = new XPathEvaluator();
        var xpr = xp.evaluate(elementPath, xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    }
    else if (this.isOpera) {
        var xpe = xmlDoc;
        if (!xpe.evaluate)
            xpe = xpe ? xpe.ownerDocument : false;
        if (xpe && xpe.evaluate) {
            xpr = xmlDoc.evaluate(elementPath, xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
        }
    }
    if ((this.isOpera || this.isMozilla) && xpr) {
        var xpn = xpr.iterateNext();
        while (xpn) {
            res.push(xpn);
            xpn = xpr.iterateNext();
        }
    }
    return res;
}


XBXPath.prototype.getNodeText = function(node) {
    if (node)
        return this.isIE ? node.text : node.textContent;
    return null;
}
