//version: 9.11
//wangli 修改于2013/6/21 9:35
;jQuery.noConflict();
;(function() {

    var isQuirksMode = (document.compatMode != "CSS1Compat");
    var savedHTML = document.documentElement.outerHTML;
    var clearHTML = function(html) {
        //清楚ie中的一些奇葩字符
        html = html.replace(/<\/%\\<br>/, '');
        html = html.replace(/<%\\<br>/, '');
        html = html.replace(/<span.*>上一张<\/span>/, '');
        html = html.replace(/<span.*>下一张<\/span>/, '');
        return html;
    }
    savedHTML = clearHTML(savedHTML);

    var console = { log: function(str) { } };
    var $ = window.jQuery;
    var qqreaderIframe = null;
    var savedXpath = '';
    var parsedSelector = {};
    var preloadIframeId = 'qqreader-preload-' + parseInt(Math.random() * 100000, 10);
    var nextiframe = document.createElement('iframe');
    nextiframe.id = preloadIframeId;
    var removeIfrTimer = 0;
    var checkReadyStateTimer = 0;
    var locationProtocal = location.protocol;
    var locationHostName = location.hostname;
    var locationHref = location.href;
    var lastPageUrl = location.href; //最新的nextpageurl
    var currentPageUrl = location.href; //最新加载的页面
    var retPageUrl = location.href; //返回要跳转的页面

    var updateJsNextPageUrl = function(win) {
        window.top.npage = win.npage; //lcread.com
    }
    var getNextPage = function(pagenum, url) {
        if (removeIfrTimer > 0) {
            clearTimeout(removeIfrTimer);
            removeIfrTimer = 0;
        }
        var iframe = nextiframe;
        var id = preloadIframeId;

        iframe.attachEvent('onload', function onIframeloaded() {
            clearInterval(checkReadyStateTimer);
            checkReadyStateTimer = 0;
            try {
                var doc = document.frames[id].document;
                var html = doc.documentElement.outerHTML;
                html = clearHTML(html);
                locationProtocal = doc.location.protocol;
                locationHostName = doc.location.hostname;
                locationHref = doc.location.href;
                if (document.frames[id] && html) {
                    com.qq.setContentAndTitleXpath(pagenum, '', html);
                }
                updateJsNextPageUrl(document.frames[id].contentWindow || document.frames[id]);
            } catch (e) {
                setTimeout(function() { window.external.getContent(escape(pagenum), '', '', ''); })
                console.log(e);
            }
            iframe.detachEvent('onload', arguments.callee);

            removeIfrTimer = setTimeout(function() {
                //延缓remove iframe的时机，在此期间如果还有加载则取消remove
                document.body.removeChild(iframe);
            }, 5000);
        });
        iframe.src = url;

        checkReadyStateTimer = setInterval(function() {
            if ('complete' == iframe.readyState) {
                onIframeloaded();
            }
        }, 1000);
        if (!document.getElementById(preloadIframeId)) {
            document.body.appendChild(iframe);
        }
    };

    var convertToAbsoluteUrl = (function() {
        return function(url) {
            if (!url) {
                return undefined;
            }
            var rootpath = locationProtocal + '//' + locationHostName;
            var dirpath = locationHref.replace(/\/[^\/]*$/, '/');
            if (/^[a-zA-Z]+:.*/.test(url)) {
                //绝对路径
                return url;
            }

            //相邻的'//'去掉一个'/'
            url = url.replace(/\/\//g, '//');
            if (/^\//.test(url)) {
                return rootpath + url;
            } else {
                return dirpath + url;
            }
        };
    })();

    var replaceRelativeUrl = function($dom) {
        $dom.find('[href], [src]').each(function() {
            if ($(this).attr('href')) {
                $(this).attr('href', convertToAbsoluteUrl($(this).attr('href')));
            }
            if ($(this).attr('src')) {
                $(this).attr('src', convertToAbsoluteUrl($(this).attr('src')));
            }
        });
    };

    var bodyCssText = '';
    var htmlCssText = '';
    var bodyScroll = '';
    var html = document.getElementsByTagName('html')[0];
    var getReaderIframe = function(id, url) {
        if (null == qqreaderIframe) {
            qqreaderIframe = $('<iframe></iframe>').css({
                'position': isQuirksMode ? 'absolute' : 'fixed',
                'zIndex': 2147483647,
                'width': '100%',
                'height': '100%',
                'left': '0px',
                'top': '0px'
            }).attr({
                'id': id,
                'src': url,
                'frameBorder': 'no'
            }); //.appendTo($(document.body));
            document.body.insertBefore(qqreaderIframe.get(0), document.body.firstChild);
        } else {
            qqreaderIframe.show();
        }
    }
    var createReaderIFrame = function(id, url) {

        if (isQuirksMode) {
            document.body.innerHTML = '';
        }

        beginReader = true;
        var $ = window.jQuery;
        getReaderIframe(id, url);
        $(qqreaderIframe).focus();
        bodyCssText = document.body.style.cssText;
        htmlCssText = html.style.cssText;
        html.style.overflow = 'hidden';
        bodyScroll = document.body.scroll;
        document.body.scroll = 'no';
    };

    var onReaderExit = function() {
        if (retPageUrl) {
            window.location.href = retPageUrl;
            return;
        }
        if (isQuirksMode) {
            location.href = location.href;
            window.top.location.reload();
            return;
        }
        if (bodyScroll) {
            document.body.scroll = bodyScroll;
        }
        else {
            document.body.removeAttribute('scroll');
        }
        qqreaderIframe.hide();
        html.style.cssText = htmlCssText;
        document.body.style.cssText = bodyCssText;
    }

    var onIframeload = function($iframe, cb) {
        if (!$iframe) {
            console.log('no iframe');
            return;
        }
        if ($iframe.get(0).readyState == 'complete') {
            cb();
        } else {
            $iframe.load(cb);
        }
    };

    var trim = function(str) {
        str = str || '';
        return str.replace(/^\s+/, '').replace(/\s+$/, '');
    };

    // fixed bug 9745025 http://finance.people.com.cn/n/2013/0325/c1004-20896805.html 
    var DEFAULT_TAGLIST = ['script', 'iframe', 'style', 'object', 'embed'];
    //script标签必须被最先移除，因为里面可能崔在<iframe>这样的字符
    var DEFAULT_TAGLIST_REG = [];
    for (var i = 0, l = DEFAULT_TAGLIST.length; i < l; i++) {
        DEFAULT_TAGLIST_REG.push(new RegExp("<\\s*(" + DEFAULT_TAGLIST[i] + ")\\s?[^>]*?>[\\s\\S]*?<\\/\\1>", "gi"));
    }

    var removeTags = function(html, tagList) {
        html = html || '';
        if (tagList) {
            html = html.replace(new RegExp("<\\s*(" + tagList.join('|') + ")\\s?[^>]*?>[\\s\\S]*?<\\/\\1>", "gi"), '');
        }
        else {
            for (var i = 0, l = DEFAULT_TAGLIST_REG.length; i < l; i++) {
                html = html.replace(DEFAULT_TAGLIST_REG[i], '');
            }
        }
        return html;
    };

    var removeInlineStyle = function(html) {
        html = html || '';
        //清空大部分标签的属性， 清除段首空格
        return html.replace(/(<\s*(h[1-6]{1}|label|li|ul|ol|p|div|em|strong|font|span))\s+[^>]+?>/gi, '$1>').replace(/(<\s*(div|p|span|strong)\s*\/?>)(&nbsp;|\s|\u3000)+/gi, '$1');
    };

    var getInnerText = function(e) {
        return e.innerText || e.textContent;
    };

    var getArticleTitle = function($fragement, pagenum) {
        var curTitle = "",
            origTitle = "";

        try {
            curTitle = origTitle = document.title;

            if (typeof curTitle !== "string") { /* If they had an element with id "title" in their HTML */
                curTitle = origTitle = getInnerText(document.getElementsByTagName('title')[0]);
            }
        }
        catch (e) { }

        if (!curTitle || pagenum > 0) {
            var tmpTitle;
            for (var i = 1; i < 4; ++i) {
                if ($('h' + i).size() == 1) {
                    tmpTitle = $('h' + i, $fragement).text();
                }
            }
            if (tmpTitle) {
                curTitle = tmpTitle;
            }
        }
        return curTitle;
    };

    var selectNextPage = (function() {
        var regex = /(下一?|next|weiter|nextpage|continue|>([^\|]|$)|»([^\|]|$))/i;
        var selectedHash = {};
        selectedHash[location.href] = true;
        return function(candidates) {
            //从一堆备选链接中挑出最可能是下一页链接的
            var $dom, href, id, className, text;
            var possible = {};
            for (var i = 0, n = candidates.length; i < n; ++i) {
                $dom = candidates[i];
                if (/javascript/gi.test($dom.attr('href'))) {
                    possible[$dom.attr('href')] = 0;
                    continue;
                }
                // fixed bug 48681309 http://3ds.tgbus.com/news/201304/20130416135454.shtml 无法续页
                if (!$dom.attr('href')) {
                    continue;
                }
                href = convertToAbsoluteUrl($dom.attr('href'));
                if (!href) {
                    continue;
                }
                if (selectedHash[href]) {
                    //已加载过，不考虑
                    continue;
                }
                if (window.location.host !== href.split(/\/+/g)[1]) {
                    //不在一个域下
                    continue;
                }

                var score = 0;

                text = $dom.text();
                if (regex.test(text)) {
                    //锚文本权重最高
                    score += 4;
                }

                if (regex.test($dom.attr('id'))) {
                    score += 2;
                }
                if (regex.test($dom.attr('class'))) {
                    score += 1;
                }
                possible[href] = score;
            }

            //挑出分数最高的
            var maxScore = -1;
            var selected = '';
            for (var k in possible) {
                if (possible[k] >= maxScore) {
                    maxScore = possible[k];
                    selected = k;
                }
            }
            if (selected) {
                selectedHash[selected] = true;
            }
            return selected;
        };
    })();

    var guessNextPageUrl = function() {
        var ret = '';
        if ('www.quanben.com' == location.host) {
            var matches = /.*\/([0-9]+)\.html?$/.exec(lastPageUrl);
            if (matches && matches.length >= 2) {
                var currentPage = parseInt(matches[1]) + 1;
                ret = lastPageUrl.replace(matches[1], currentPage.toString());
            }
        }
        return ret;
    }

    var isJavascript = function(url) {
        return /javascript/gi.test(url);
    }

    var getJSNextPageUrl = function(url) {
        var retUrl;
        retUrl = npage; //lcread.com
        return retUrl;
    }

    var setContentAndTitleXpath = function(pagenum, selectorsArr, html) {
        var fragement, $fragement;
        var title = '';
        var content = '';
        var $content;
        var nextpageurl = '';
        var tmp;

        if (!html) {
            html = savedHTML;
        }

        fragement = document.createElement('body');
        var keepScript = function() {
            return "www.quanben.com" == location.host ||
            "www.tianyabook.com" == location.host;
            //全本小说会把内容放到script标签里，所以在此处不剔除script标签
        }
        if (keepScript()) {
            fragement.innerHTML = removeTags(html, ['iframe', 'style', 'object', 'embed']);
        } else {
            fragement.innerHTML = removeTags(html);
        }
        $fragement = $(fragement);
        replaceRelativeUrl($fragement);
        if (selectorsArr) {
            //如果传了xpath重新解析一遍，否则用缓存的结果
            selectorsArr = selectorsArr.split('****');
        } else {
            selectorsArr = [stringSelectors];
        }
        try {
            var i, n;
            for (i = 0; i < selectorsArr.length; ++i) {
                var ret = (function() {
                    selectors = selectorsArr[i];
                    if (!selectors) {
                        return;
                    }
                    stringSelectors = selectors;
                    parsedSelector = $.parseJSON(selectors);
                    selectors = parsedSelector;
                    if (selectors['page']) {
                        var tryAllLinks = true;
                        var candidateLinks = [];
                        $(selectors['page'].join(','), $fragement).each(function() {
                            tryAllLinks = false;
                            if ('a' == this.tagName || 'A' == this.tagName) {
                                candidateLinks.push($(this));
                            }
                            $(this).find('a').each(function() {
                                candidateLinks.push($(this));
                            });
                            $(this).remove();
                        });
                        //fixed bug 48681309 http://news.163.com/13/0415/03/8SFLBCG60001124J.html 无法续页
                        var pageURL = selectNextPage(candidateLinks);
                        if (pageURL) {
                            nextpageurl = pageURL;
                        }

                        if (!nextpageurl && tryAllLinks) {
                            //没提取到链接，或者按规则选不到分页的div,尝试用全部url试一下。
                            $fragement.find('a').each(function() {
                                var text = $(this).text();
                                if (/下一?(篇|章|节|页)/.test(text)) {
                                    nextpageurl = $(this).attr('href');
                                }
                            });
                        }

                        if (isJavascript(nextpageurl)) {
                            nextpageurl = getJSNextPageUrl(nextpageurl);
                        }
                        if (!nextpageurl) {//如果nextpageurl是空，则猜测下一页
                            nextpageurl = guessNextPageUrl();
                        }
                        retPageUrl = currentPageUrl;
                        currentPageUrl = lastPageUrl;
                        lastPageUrl = nextpageurl;
                    }
                    if (selectors['dust']) {
                        try {
                            $(selectors['dust'].join(','), $fragement).remove();
                        } catch (e) {
                            console.log(e.stack);
                        }
                    }

                    try {
                        title = trim(selectors['title'] && $(selectors['title'].join(','), $fragement).text());
                        title.replace(/\u3000|&nbsp;/g, ' '); //全角空格换成半角，解决标题折行问题。
                        if (!(title && /[^\s]/.test(title))) {
                            //没有提取成功，猜一个
                            title = getArticleTitle($fragement, pagenum);
                        }
                    } catch (e) {
                        console.log(e.stack);
                    }

                    try {
                        if (selectors['content']) {
                            content = '';
                            $(selectors['content'].join(','), $fragement).each(function() {
                                $(this).find('a').each(function() {
                                    var text = trim($(this).text());
                                    if (!text && !$(this).find('img')) {
                                        $(this).remove();
                                        return;
                                    }
                                    if (text && text.length >= 20) {
                                        //或锚文本很长的
                                        $(this).remove();
                                    }
                                });
                                $(this).find('ul, ol, li').each(function() {
                                    var text = trim($(this).text());
                                    if (!text) {
                                        $(this).remove();
                                    }
                                });
                                $(this).find('textarea, select, input, button').remove();
                                content += removeInlineStyle(this.innerHTML);
                            });
                            content = '<div>' + content + '</div>';
                        } else {
                            //no content;
                            return;
                        }
                    } catch (e) {
                        console.log(e.stack);
                    }
                    console.log(['title', title]);
                    console.log(['content', content]);
                    if (content.length > 100) {
                        return true;
                    } else {
                        return false;
                    }
                })();
                if (ret) {
                    break;
                }
            }
            $fragement = null;
            fragemenet = null;

            //QBReaderTestInjection

            onIframeload(qqreaderIframe, function() {
                try {
                    setTimeout(function() {
                        window.external.getContent(escape(pagenum), escape(title), escape(content), escape(nextpageurl));
                    }, 0);
                } catch (e) {
                    console.log(e.stack);
                }
            });
        } catch (e) {
        }
    };

    var com = window.com = window.com || {};
    com.qq = com.qq || {};
    com.qq.setContentAndTitleXpath = setContentAndTitleXpath;
    com.qq.createReaderIFrame = createReaderIFrame;
    com.qq.getNextPage = getNextPage;
    com.qq.onReaderExit = onReaderExit;


    $(document).ready(function() {
        //clear ads
        (function() {
            $('*').filter(function() {
                return (this.id != preloadIframeId) &&
             (this.id != 'qqReaderIfr') &&
             (this.style.zIndex == 2147483647);
            }).remove();
        })();
    });

})();
