// ==UserScript==
// @name           起点小说阅读器
// @namespace      q3boy
// @include        http://www.qidian.com/BookReader/*,*.aspx*
// @exclude       http://www.qidian.com/BookReader/vip,*,*.aspx*
// ==/UserScript==

GM_addStyle(".q3_book_content {padding:0px;margin:0}");
GM_addStyle(".q3_book_content p {text-indent:2em; color:#000000 ; font-size:32px; letter-spacing:1px; line-height:160% !important; font-family:'汉仪魏碑简','微软雅黑', Arial;}");
GM_addStyle(".q3_book_title {text-align:center; color:#990000; font-family:'汉仪魏碑简', '汉仪中隶书', Arial; font-size:24px; margin:10px; }");
GM_addStyle(".q3_book_nav {text-align:center; margin:10px;}");
GM_addStyle("a {color: #376F9A ;}a:visited {color: #781C45 ;}a:active {color: #6799C4 ;}");

var q3boyQidianChapter = function (){
	this.ok = 0;
	this.url = '';
	this.bookid = 0;
	this.chapid = 0;
	this.prevurl = '';
	this.nexturl = '';
	this.listurl = '';
	this.bookurl = '';
	this.scripturl = '';
	this.title = '';
	this.body = '';
	this.draw = function(clean){
		if (clean){
			document.body.innerHTML = '';
			unsafeWindow.document.onmouseup=function(){};
			unsafeWindow.document.onmousemove=function(){};
			unsafeWindow.document.onmousedown=function(){};
			unsafeWindow.document.onclick=function(){};
			unsafeWindow.document.body.onclick=function(){};
			unsafeWindow.document.oncontextmenu=function(){};
		}
		div = document.createElement('div');
		str = '<div class="q3_book_title">' + this.title + '</div>';
		str += '<div class="q3_book_nav"><a href="' + this.prevurl+ '"><<上一页</a> | <a href="' + this.listurl+ '">目录</a> | <a href="' + this.bookurl+ '">书页</a> | <a href="javascript:加入书架书签" onclick="javascript:MyAjax.AddBookMark(\'' + this.bookid + '\',\'' + this.chapid + '\',null)">书签</a> | <a href="' + this.nexturl+ '">下一页>></a></div>';
		str += '<div class="q3_book_content">' + this.body + '</div>';
                str += '<hr />';
		div.innerHTML = str;
		document.body.appendChild(div);
		unsafeWindow.prevpage = this.prevurl;
		unsafeWindow.nextpage = this.nexturl;
		unsafeWindow.bookpage = this.listurl;
	};

	this.txtload = function(res){
		obj = q3boyQidianChapter.loadingChapter;
		if (res.status == 200) {
			body = res.responseText.replace(/^.+?\('/im, '');
			body = body.replace(/'\).*?$/im, '');
			body = body.replace(/<(div|span|a|script).*?>.*?<\/\s*(div|span|a|script)>/ig, '');
			body = body.replace(/^(?:[\s　]+)?(.*?)(?:[\s　]+)?$/ig, '$1');
			body = body.replace(/<p>[\s　]*/ig, '</p><p>');
			body = body.replace(/^(?:<\/p>)?(.*?)(?:<p>)?$/ig, '$1');
			if (body.substr(0, 3) != '<p>'){
				body = '<p>' + body;
			}

			obj.body = body;
			obj.ok = 1;
			q3boyQidianBookReader.loadStatus.setStandby();
///			console.log('get txtbody ok');
		} else {
///			console.log('get txtbody failed.');
			obj.ok = -8;
			return false;
		}
	}

	this.chapload = function(res){
		obj = q3boyQidianChapter.loadingChapter;
		if (res.status == 200) {
			txtreg = res.responseText.match(/<span\s+.*?id="lbChapterName"\s*.*?>(.+?)<\/span>/im);
			if (txtreg) {
				obj.title = txtreg[1];
			} else {
				if (res.responseText.match(/以上就是本作品的最新更新内容/im)) {
					obj.ok = -100;
					q3boyQidianBookReader.loadStatus.setDone();
///					console.log('no more chapter.');
					return false;
				}
				obj.ok = -2;
///				console.log('get title failed.');
				return false;
			}
			txtreg = res.responseText.match(/<div\s+.*?id="content"\s*.*?>[.\s]*<script\s+.*?src='(.+?)'/im);
			if (txtreg) {
				obj.scripturl = txtreg[1];
			} else {
///				console.log('get scripturl failed.');
				obj.ok = -3;
				return false;
			}

			txtreg = res.responseText.match(/<script.*?>\s*prevpage='(.+?)'.*\s*nextpage='(.+?)'.*\s*bookpage='(.+?)'.*\s*<\/script>/im);
			if (txtreg)
			{
				urldir = obj.url.replace(/[^\/]+?$/ig, '');
				obj.prevurl = urldir + txtreg[1];
				obj.nexturl = urldir + txtreg[2];
				obj.listurl = urldir + txtreg[3].replace(/^.*\/([^\/]+)$/ig, '$1');;
				obj.bookurl = urldir.replace(/^(http:\/\/.+?)\/.*$/ig, '$1') + txtreg[3];
///				console.log('get page ok.');
			} else {
///				console.log('get page failed.');
				obj.ok = -4;
				return false;
			}
			GM_xmlhttpRequest({
				url:obj.scripturl,
				method:"GET",
				overrideMimeType:'text/plain;charset=gb2312',
				onload:q3boyQidianChapter.loadingChapter.txtload
			});
			
		} else {
			obj.ok = -1;
			return false;
		}
	}
}


q3boyQidianChapter.loadFromPage = function(){
	var chapter = new q3boyQidianChapter();
	chapter.url = location.href.toString();

	reg = chapter.url.match(/^.+BookReader\/(\d+),(\d+)\..*$/im);
	if (reg){
		chapter.bookid = parseInt(reg[1]);
		chapter.chapid = parseInt(reg[2]);
	} else{
		chapter.ok = -30
		return null;
	}

	urldir = chapter.url .replace(/[^\/]+?$/ig, '');
	chapter.prevurl = urldir + unsafeWindow.prevpage;
	chapter.nexturl = urldir + unsafeWindow.nextpage;
	chapter.listurl = urldir + unsafeWindow.bookpage.replace(/^.*\/([^\/]+)$/ig, '$1');
	chapter.bookurl = chapter.url .replace(/^(http:\/\/.+?)\/.*$/ig, '$1') + unsafeWindow.bookpage;
	
	cont = document.getElementById('content');
	title = document.getElementById('lbChapterName');

	body = cont.innerHTML.replace(/<(div|span|script).*?>.*?<\/\s*(div|span|script)>/ig, '');
	body = body.replace(/<\/?a[^>]+?>/ig, '');
	body = body.replace(/^(?:[\s　]+)?(.*?)(?:[\s　]+)?$/ig, '$1');
	body = body.replace(/<p><\/p>[\s　]*/ig, '</p><p>');
	body = body.replace(/<p>[\s　]*/ig, '</p><p>');
	body = body.replace(/^(?:<\/p>)?(.*?)(?:<p>)?$/ig, '$1');
//	body = body.replace('起点中文网 www.qidian.com 欢迎广大书友光临阅读，最新、最快、最火的连载作品尽在起点原创！', '');
               if (body.substr(0, 3) != '<p>'){
		body = '<p>' + body;
	}
	chapter.body = body;
	chapter.title = title.innerHTML
	chapter.ok = 10;
	return chapter;
}

q3boyQidianChapter.loadFromUrl = function(url){
	var url = url.toString();
	var chapter = new q3boyQidianChapter();
	q3boyQidianBookReader.loadStatus.setLoading();
	q3boyQidianChapter.loadingChapter = chapter;

	chapter.url = url;

	reg = url.match(/^.+BookReader\/(\d+),(\d+)\..*$/im);
	if (reg){
		chapter.bookid = parseInt(reg[1]);
		chapter.chapid = parseInt(reg[2]);
		urldir = url.replace(/[^\/]+?$/ig, '');
		GM_xmlhttpRequest({
			url:url,
			method:"GET",
			overrideMimeType:'text/plain;charset=gb2312',
			onload:chapter.chapload
		});
	} else if (url.match(/^.+BookReader\/LastPage\.aspx/im)) {
		chapter.ok = -100;
		q3boyQidianBookReader.loadStatus.setDone();
///		console.log('no more chapter.');
	} else {
		chapter.ok = -30
		return null;
	}
	return chapter;
}

function q3boyQidianBookReader() {

	chapter = q3boyQidianChapter.loadFromPage();
	chapter.draw(true);
	
	q3boyQidianBookReader.loadStatus = new q3boyQidianBookReaderStatus();
	
	q3boyQidianBookReader.nextChapter = q3boyQidianChapter.loadFromUrl(chapter.nexturl);

	q3boyQidianBookReader.chapter = chapter;
	this.watch = function(){
		var sc = document.body.scrollTop;
		var wh = window.innerHeight ? window.innerHeight : document.body.clientHeight;
		var total = (document.body.scrollHeight - wh);
		var remain = total - sc;
		if(remain < 300 && !q3boyQidianBookReader.processing && q3boyQidianBookReader.nextChapter.ok > 0 && q3boyQidianBookReader.chapter.ok > 0) {
			q3boyQidianBookReader.shownext();
		}
		var self = arguments.callee;
		window.setTimeout(self, 300);
	};
	this.watch();
}
q3boyQidianBookReader.shownext = function (){
	q3boyQidianBookReader.processing = true;
	chapter = q3boyQidianBookReader.chapter;
	nextChapter = q3boyQidianBookReader.nextChapter;
	if (nextChapter) {
		if (nextChapter.ok > 0) {
			nextChapter.draw();
			q3boyQidianBookReader.chapter = nextChapter;
			q3boyQidianBookReader.nextChapter = q3boyQidianChapter.loadFromUrl(nextChapter.nexturl);
///			console.log('shownext ok');
		} else {
///			console.log('next not reader');
			
		}
	} else {
///		console.log('no next');
	}
	q3boyQidianBookReader.processing = false;
}

function q3boyQidianBookReaderStatus() {
	this.element = null;
	this.timer = function(){
		try{
			var dat = new Date();
			var h = dat.getHours();
			var m = dat.getMinutes();
			if(h < 10){
				h = '0' + h;
			}
			if(m < 10){
				m = '0' + m;
			}
			var tm = h + ':' + m;
			document.getElementById('q3_statusbar').innerHTML = tm;
		}catch(e){

		}
		var self = arguments.callee;
		window.setTimeout(self,30000);
	}

	this.init = function(element){
		var div = document.createElement('div');
		div.style.margin='0';
		div.style.padding='0.2em';
		div.style.border='1px solid gray';
		div.style.position='fixed';
		div.style.right='2px';
		div.style.bottom='2px';
		div.style.zIndex='999999';
		div.style.lineHeight='1.2em';
		div.style.weight='bold';
		div.style.fontSize='11px';
		div.style.color='white';
		div.id = 'q3_statusbar';
//		document.body.appendChild(div);
		this.element = div;
		element = div;
		this.timer();
	};
	this.setLoading = function(){
		this.element.style.backgroundColor='#790619';
	};
	this.setStandby = function(){
		this.element.style.backgroundColor='#0075be';
	};
	this.setDone = function(){
		this.element.style.backgroundColor='#00681c';
	};
	this.init();
}
new q3boyQidianBookReader();
q3boyQidianBookReader.processing = false;
