/**
 * Created by bjoso on 2017/5/4.
 */
var xh = xh || {};
var doc;
xh.elementsShareFamily = function (primaryEl, siblingEl) {
    var p = primaryEl, s = siblingEl;
    return (p.tagName === s.tagName &&
    (!p.className || p.className === s.className) &&
    (!p.id || p.id === s.id));
};
//获取元素所在父节点的索引位置
xh.getElementIndex = function (el) {
    var index = 1;  // XPath索引为1
    var sib;
    for (sib = el.previousSibling; sib; sib = sib.previousSibling) {
        if (sib.nodeType === Node.ELEMENT_NODE && xh.elementsShareFamily(el, sib)) {
            index++;
        }
    }
    if (index > 1) {
        return index;
    }
    for (sib = el.nextSibling; sib; sib = sib.nextSibling) {
        if (sib.nodeType === Node.ELEMENT_NODE && xh.elementsShareFamily(el, sib)) {
            return 1;
        }
    }
    return 0;
};
var type = 0;
function setType(param) {
    type = param;
}
//生成元素的xpath
xh.makeQueryForElement = function (el, type) {
    //type表示模式,值为0时启用精准模式(id&class),否则默认为列表模式
    var query = '';
    for (; el && el.nodeType === Node.ELEMENT_NODE; el = el.parentNode) {
        var component = el.tagName.toLowerCase();
        var index = xh.getElementIndex(el);
        //精准模式
        if (type === true) {
            if (el.id) {
                component += '[@id=\'' + el.id + '\']';
            } else if (el.className) {
                component += '[@class=\'' + el.className + '\']';
            }
            if (index >= 1) {
                component += '[' + index + ']';
            }
        }
        //如果最后一个标签是img,可以选择使用img/@src.
        if (query === '' && el.tagName.toLowerCase() === 'img') {
            component += '/@src';
        }
        query = '/' + component + query;
    }
    return query;
};
//根据xpath查询元素
xh.evaluateQuery = function (query, onclick) {
    var xpathResult = null;
    var nodeCount = 0;//元素数量
    var nodes = [];
    var toHighlight = [];
    var _viewNode = new Object();

    try {
        xpathResult = doc.evaluate(query, doc, null,
            XPathResult.ANY_TYPE, null);
    } catch (e) {
        str = '[无效的XPATH表达式]';
        nodeCount = 0;
    }

    if (!xpathResult) {
        return [str, nodeCount];
    }

    if (xpathResult.resultType === XPathResult.BOOLEAN_TYPE) {
        _viewNode.text = xpathResult.booleanValue ? '1' : '0';
        nodeCount = 1;
    } else if (xpathResult.resultType === XPathResult.NUMBER_TYPE) {
        _viewNode.text = xpathResult.numberValue.toString();
        nodeCount = 1;
    } else if (xpathResult.resultType === XPathResult.STRING_TYPE) {
        _viewNode.text = xpathResult.stringValue;
        nodeCount = 1;
    } else if (xpathResult.resultType === XPathResult.UNORDERED_NODE_ITERATOR_TYPE) {
        for (var node = xpathResult.iterateNext(); node; node = xpathResult.iterateNext()) {
            var viewNode = new Object();
            var urls = "";
            // var imgs = "";
            if (node.nodeType === Node.ELEMENT_NODE) {
                if (onclick === false) {
                    toHighlight.push(node);
                }
                viewNode.text = node.textContent;
                //获取节点链接
                var _urls = node.getElementsByTagName('a');
                for (var i = 0; i < _urls.length; i++) {
                    urls += _urls[i].href + '\n';
                }
                // //获取节点img
                // var _imgs = node.getElementsByTagName('img');
                // for (var i = 0; i < _imgs.length; i++) {
                //     imgs += _imgs[i].src + '\n';
                // }
            }
            viewNode.urls = urls;
            // viewNode.imgs = imgs;
            nodes.push(viewNode);
            nodeCount++;
        }
        if (nodeCount === 0) {
            _viewNode.text = '[NULL]';
            nodes.push(_viewNode);
        }
    } else {
        //因为XPathResult.ANY_TYPE传递给了document.evaluate(),
        //应该永远不会得到上面没有处理的结果类型
        _viewNode.text = '[内部错误]';
        nodeCount = 0;
    }
    if (_viewNode) {
        nodes.push(_viewNode);
    }
    nodes.pop();
    xh.highlight(toHighlight);//高亮函数
    return [nodeCount, nodes];
};

//判断元素是否在父节点中
xh.isTagXpathContains = function (xpath, subxpath) {
    return xpath.indexOf(subxpath) >= 0;
}

//获取DOM标题
xh.queryTitle = function () {
    return doc.title
}
//高亮函数
xh.highlight = function (els) {
    for (var i = 0, l = els.length; i < l; i++) {
        els[i].classList.add('xh-highlight');
    }
};
//清除高亮函数
xh.clearHighlights = function () {
    var els = doc.querySelectorAll('.xh-highlight');
    for (var i = 0, l = els.length; i < l; i++) {
        els[i].classList.remove('xh-highlight');
    }
};
//禁用document中的链接跳转
xh.disLink = function () {
    var links = doc.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].classList.add('disabled');
    }
}

function docClick(e, type) {
    var el = e.target;
    if (type===0) {
        var xpath = xh.makeQueryForElement(el, true);
        var data = xh.evaluateQuery(xpath);
        showLook(data, xpath);
    } else {
        var xpath = xh.makeQueryForElement(el);
        var data = xh.evaluateQuery(xpath);
        showLook(data, xpath,0);
    }
}
function init(docm) {
    // set  document
    doc = docm;
    //禁用document中的链接跳转
    xh.disLink();
    // 页面标题
    setFrameHtmlTitle(xh.queryTitle());
    //高亮
    doc.onmousemove = function (e) {
        //console.log("onmousemove");
        var el = e.target;
        var xpath = xh.makeQueryForElement(el, true);
        xh.evaluateQuery(xpath, false);
    }
    doc.onmouseout = function () {
        //console.log("onmouseout");
        xh.clearHighlights();
    }

    // 打开XPath页面
    // openXPathClick();
}
// window.onload = function () {
//
// doc = window.document;
// xh.disLink();
// console.log("=========函数执行标志=========");
// console.log(xh.queryTitle());
// document.onclick = function (e) {
// var el = e.target;
// var xpath = xh.makeQueryForElement(el);
// console.log("列表模式xpath:", xpath);
// console.log("列表模式DOM:", xh.evaluateQuery(xpath));
// var xp = xh.makeQueryForElement(el, 0)
// console.log("精准模式xpath:", xp);
// console.log("精准模式DOM:", xh.evaluateQuery(xp));
// xp = xp.replace('xh-highlight', '').replace('xh-disabled', '').replace("[@class='']", '');
// console.log("原始的xpath:" + xp);
// }
// document.onmousemove = function (e) {
// var el = e.target;
// var xpath = xh.makeQueryForElement(el, 0);
// xh.evaluateQuery(xpath, 0);
// }
// document.onmouseout = function () {
// xh.clearHighlights();
// }
// };
