// ==UserScript==
// @name                豆瓣助手 douban helper
// @namespace           http://userscripts.org/scripts/show/49911
// @description         为豆瓣(www.douban.com)添加各种人性化的功能。
// @require             http://js-addon.googlecode.com/files/autoupdatehelper.js
// @include             *
// @version             3.83
/* @reason
增加：置顶小组导航条，方便鼠标翻页
改善：将更多的搜索引擎改为可自定义
（下个版本修改一下架构就能全部自定义了）
修正：某些情况讨论增强失效的BUG
（如果还有问题，可以尝试卸载重装）
@end*/
// ==/UserScript==

/* ************************ 备注 ************************ */
/**
 * 看到这的同学，如果希望帮助完善豆瓣助手，请在豆瓣插件小组回复: http://www.douban.com/group/topic/6604219/
 * 如果是看到某些代码还合眼，直接使用就可以了，无需申请，也欢迎感谢我:-)
 *
 * ====== 未来计划: ======
 * 在电影评论页面，如果回复中有lz的回复，那下一个回复没办法正常使用引用等功能
 * 重新整理一下混乱的内部逻辑
 * 楼主引用回复
 * 建立自定义快捷键哈希表，如有一致就执行
 * 检测是否已加入该小组
 * 无刷新看直播
 * 刷新、翻页后仍保留 高亮/忽略
 * 默认高亮楼主
 * 预读下一页
 * 高亮引用文字
 * 在小组标题栏添加直达最后一页的链接
 * 当话题有新回复时弹出提醒
 * 关注某人（自动高亮名字或提醒有新发言）
 */

/* ************************ 判断执行 ************************ */

var t1 = new Date();//时间1
new Updater({name: "豆瓣助手 douban helper",id: "49911",version: "3.83"}).check();//自动更新
Douban = (location.hostname == 'www.douban.com') ? true: false;//判断是否豆瓣
hl_input(); //输入框高亮
if (Douban){
	add_search_bar(); //添加搜索条
	exGroup();// 添加小组增强菜单
	alb_big(); //相册显示大图
	set_bar();//添加导航栏按钮
	settle();//浮动定位工具
	add_setting();//添加设置栏
	addHotKey(GM_getValue('hk_db', 'alt+Q'),function(){sw_set(false)});
	ctrlenter();//快速回复
	$('#db_hp').title = "用时：" + (new Date() - t1)/1000 + " 秒";
};
!Douban && openDouban();//秘籍 '↑↑↓↓←→←→' 打开豆瓣
show_pic(); //显示链接图片
// alert("耗时：" + (new Date() - t1) + " 毫秒");//时间总计


/* ************************ 基本函数准备 ************************ */

// 获取URL参数
function QueryString(item){
     var sValue=location.search.match(new RegExp("[\?\&]"+item+"=([^\&]*)","i"));
	 return (sValue && sValue[1]!= '')?sValue[1]:0;
};

// 获取Cookie 函数
function getCookie(c_name){
	if (document.cookie.length > 0){
		c_start = document.cookie.indexOf(c_name + '=');
		if (c_start!=-1){ 
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(';',c_start);
			if (c_end == -1){ c_end = document.cookie.length;}
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return '';
};

// 自造 selecter ,节省一点打字时间
function $(select){
	var name = select.substring(1);
	switch(select.charAt(0)){
		case '#':
			return document.getElementById(name);
		case '.':
			return document.getElementsByClassName(name);
		case '/':
			return document.getElementsByTagName(name);
		default:
			return document.getElementsByName(select);
	}
};

// 隐藏或显示
function toggle(obj){
	obj.style.display = (obj.style.display == 'none')?'':'none';
	return true;
};

// keycode 转换
function getKeys(e){
	var codetable={'96':'Numpad 0','97':'Numpad 1','98':'Numpad 2','99':'Numpad 3','100':'Numpad 4','101':'Numpad 5','102':'Numpad 6','103':'Numpad 7','104':'Numpad 8','105':'Numpad 9','106':'Numpad *','107':'Numpad +','108':'Numpad Enter','109':'Numpad -','110':'Numpad .','111':'Numpad /','112':'F1','113':'F2','114':'F3','115':'F4','116':'F5','117':'F6','118':'F7','119':'F8','120':'F9','121':'F10','122':'F11','123':'F12','8':'BackSpace','9':'Tab','12':'Clear','13':'Enter','16':'Shift','17':'Ctrl','18':'Alt','20':'Cape Lock','27':'Esc','32':'Spacebar','33':'Page Up','34':'Page Down','35':'End','36':'Home','37':'←','38':'↑','39':'→','40':'↓','45':'Insert','46':'Delete','144':'Num Lock','186':';:','187':'=+','188':',<','189':'-_','190':'.>','191':'/?','192':'`~','219':'[{','220':'\|','221':']}','222':'"'};
	var Keys = '';
	e.shiftKey && (e.keyCode != 16) && (Keys += 'shift+');
	e.ctrlKey && (e.keyCode != 17) && (Keys += 'ctrl+');
	e.altKey && (e.keyCode != 18) && (Keys += 'alt+');
	return Keys + (codetable[e.keyCode] || String.fromCharCode(e.keyCode) || '');
};

// 即时显示快捷键
function trans_code(ID, codes){
	var cobj = $('#'+ID);
	cobj.value = GM_getValue(ID, codes);
	cobj.addEventListener('keydown',function(e){
		this.value = getKeys(e);
		e.preventDefault();
		e.stopPropagation();
	},false);
};

// 监视并执行快捷键对应的函数
function addHotKey(codes,func){
	document.addEventListener('keydown', function(e){
		if ((e.target.tagName != 'INPUT') && (e.target.tagName != 'TEXTAREA') && getKeys(e) == codes){
			func();
			e.preventDefault();
			e.stopPropagation();
		}
	}, false);
};

/* ************************ 豆瓣助手设置界面 ************************ */

// 添加导航栏按钮
function set_bar(){
	var _status = $('#status');
	var db_hp = document.createElement("a");
	db_hp.id = "db_hp";
	db_hp.innerHTML = '豆瓣助手';
	if (_status.lastChild.innerHTML){
		_status.appendChild(db_hp);
	}else{
		_status.insertBefore(db_hp, _status.lastChild.previousSibling);
	};
	$('#db_hp').addEventListener('click', function(){sw_set(false);}, false);
};

// 加载设置栏
function add_setting(){
	if (GM_getValue("newui", true)){var idname = "#db_set";}
	GM_addStyle('\
		'+ idname +' {\
			width:100%;\
			height:100%;\
			position:fixed;\
			top:0px;\
			left:0px;\
			z-index:98;\
			opacity:0.8;\
			background:#000;\
		}\
		#db_div{\
			position:fixed;;\
			width: 500px;\
			top:10%;\
			left:30%;\
			z-index:99;\
			color:#fff;\
			background:#000;\
			border:1px solid #fff;\
			-moz-border-radius:10px;\
			}\
		#db_div legend {\
			color:#fff;\
			border:1px solid #fff;\
			-moz-border-radius:10px;\
			font-weight:bold;\
			}\
		#db_div fieldset {\
			padding:5px;\
			margin: 1em 0.5em;\
		}\
		#db_div div {\
			margin:0.3em 0em;\
		}\
		#db_div label {\
			cursor:pointer;\
			margin:20px 18px;\
			padding:2px;\
		}\
		#db_div label:hover {\
			background: #eef9eb;\
			-moz-border-radius:3px;\
			color:#000;\
		}\
		#db_div textarea {\
			margin:0px 20px;\
			font-size:12px;\
		}\
		#db_div .gact a {\
			-moz-border-radius:10px;\
			padding:2px 20px;\
		}\
	');
	var db_set = document.createElement("div");
	db_set.id = "db_set";
	db_set.style.display = "none";
	db_set.innerHTML = '\
		<div id="db_div">\
			<fieldset>\
				<legend>快速搜索</legend>\
					<label><input type="checkbox" id="search_bar" />开启快速搜索条</label>\
					<label>添加自定义搜索引擎(使用说明详见底部链接)↓</label>\
					<br>\
					<textarea rows="4" cols="77" id="otherEngines"></textarea>\
			</fieldset>\
			<fieldset>\
				<legend>讨论增强</legend>\
					<label><input type="checkbox" id="count" />开启显示楼层数</label>\
					<label><input type="checkbox" id="requote" />开启引用回复</label>\
					<label><input type="checkbox" id="just_view" />开启只看高亮忽略</label>\
					<br>\
					<label><input type="checkbox" id="tidybar" />使用紧凑工具条</label>\
					<label><input type="checkbox" id="auto_hide" />自动隐藏工具条</label>\
					<label><input id="hlcolor" size=4 onMouseover="this.style.background=\'#fff\';" onKeyup="this.style.background=this.value" onMouseout="this.style.background=this.value" />高亮背景色</label>\
					<label><input id="diylen" size=2 />当引用文字超过该长度，提示是否截断</label>\
			</fieldset>\
			<fieldset>\
				<legend>图片识别</legend>\
					<label><input type="radio" name="showpic" />不开启图片识别</label>\
					<label><input type="radio" name="showpic" />只对豆瓣网开启</label>\
					<label><input type="radio" name="showpic" />对所有网页开启</label>\
					<br>\
					<label><input type="radio" name="showpic" />对所有网页开启，点击鼠标中键时才加载（速度最快，推荐选项）</label>\
			</fieldset>\
			<fieldset>\
				<legend>其他功能</legend>\
					<label><input type="checkbox" id="hl_input" />高亮焦点输入框</label>\
					<label><input type="checkbox" id="alb_big" />在相册缩略图上点击鼠标中键显示大图</label>\
					<br>\
					<label><input type="checkbox" id="newui" />半透明设置界面</label>\
					<label>设置界面快捷键<input size=8 id="hk_db"/></label>\
					<br>\
					<label><input type="checkbox" id="settler" />开启浮动定位条</label>\
					<label>浮动定位条快捷键↓</label>\
					<br>\
					<label>置顶：<input size=1 id="hk_top"/></label>\
					<label>置底：<input size=1 id="hk_btm"/></label>\
					<label>上页：<input size=1 id="hk_pre"/></label>\
					<label>下页：<input size=1 id="hk_nxt"/></label>\
					<br>\
					<label><a href="http://userscripts.org/scripts/show/49911" target=_blank>详细介绍及使用说明</a></label>\
					<label><a href="http://www.douban.com/group/topic/6604219/" target=_blank>反馈意见</a></label>\
			</fieldset>\
			<div class="gact">\
				<a href="javascript:void(0)" title="部分选项需要刷新页面才能生效" id="s_ok" >√ 确认</a>\
				&nbsp;&nbsp; \
				<a href="javascript:void(0)" title="取消本次设定，所有选项还原" id="s_cl" >X 取消</a>\
			</div>\
		</div>\
	';
	document.getElementsByTagName('body')[0].appendChild(db_set);
	$('#s_ok').addEventListener('click', function(){sw_set(true);}, false);
	$('#s_cl').addEventListener('click', function(){sw_set(false);}, false);
};

// 显示\隐藏设置栏
function sw_set(ch){
	toggle($('#db_set'));
	if (ch){
		//写入图片识别选项
		var pic_sw = document.getElementsByName('showpic');
		for (var i=0,j=pic_sw.length; i<j; i++){
			if (pic_sw[i].checked){GM_setValue('choice', i);}
		};
		GM_setValue('hlcolor', $('#hlcolor').value);//写入高亮背景色
		GM_setValue('otherEngines', $('#otherEngines').value);//写入自定义搜索引擎
		GM_setValue('diylen', parseInt($('#diylen').value) );//自定义引文截断长度
		db_write('just_view');//写入只看、高亮、忽略选项
		db_write('search_bar');//写入搜索条选项
		db_write('newui');//写入设置界面选项
		db_write('hl_input');//写入高亮输入框选项
		db_write('alb_big');//写入相册大图选项
		db_write('count');//写入数楼选项
		db_write('auto_hide');//写入自动隐藏选项
		db_write('tidybar');//写入工具条样式
		db_write('requote');//写入工具条样式
		db_write('settler');//写入浮动定位工具选项
		GM_setValue('hk_db', $('#hk_db').value);//写入自定义搜索引擎
		GM_setValue('hk_top', $('#hk_top').value);//写入置顶快捷键
		GM_setValue('hk_btm', $('#hk_btm').value);//写入置底快捷键
		GM_setValue('hk_pre', $('#hk_pre').value);//写入上一页快捷键
		GM_setValue('hk_nxt', $('#hk_nxt').value);//写入下一页快捷键
	}else{                                           
		//读取高亮背景色
		$('#hlcolor').value = GM_getValue('hlcolor', '#eeffee');
		$('#hlcolor').style.background = GM_getValue('hlcolor');
		document.getElementsByName('showpic')[GM_getValue('choice', 1)].checked = true;//读取图片识别选项
		$('#otherEngines').value = GM_getValue('otherEngines', "土豆豆单|http://so.tudou.com/psearch/{word}\n土豆视频|http://so.tudou.com/isearch/{word}\n优酷视频|http://so.youku.com/search_video/q_{word}\n优酷列表|http://so.youku.com/search_playlist/q_{word}\n豆瓣小组|http://www.douban.com/group/search?q={word}\n百度知道|http://zhidao.baidu.com/q?word={gb:word}&ct=17&tn=ikaslist&rn=10");//读取自定义搜索引擎
		$('#diylen').value = GM_getValue('diylen', 500);//自定义引文截断长度
		db_read('just_view',true);//读取只看、高亮、忽略选项
		db_read('search_bar',true);//读取搜索条选项
		db_read('newui',true);//读取设置界面选项
		db_read('hl_input',true);//读取高亮输入框选项
		db_read('alb_big',true);//读取相册大图选项
		db_read('count',true);//读取数楼选项
		db_read('auto_hide',false);//读取自动隐藏选项
		db_read('tidybar', true);//读取工具条样式
		db_read('requote', true);//读取引用回复选项
		db_read('settler', true);//读取浮动定位工具选项
		trans_code('hk_db', 'alt+Q');//显示豆瓣助手设置界面快捷键
		trans_code('hk_top', '↑');//显示置顶快捷键
		trans_code('hk_btm', '↓');//显示置底快捷键
		trans_code('hk_pre', '←');//显示上一页快捷键
		trans_code('hk_nxt', '→');//显示下一页快捷键
	}              
};

//checkbox通用读取、写入函数
function db_read(id,value){$('#'+id).checked = GM_getValue(id, value);}
function db_write(id){GM_setValue(id, $('#'+id).checked);}


/* ************************ 豆瓣相册处理 ************************ */

// 识别相册大图函数
function alb_big(){
	if (GM_getValue("alb_big", true) && /album/i.test(location.href)){
		alb_all(true);
		var photitle = $('.photitle')[0];
		photitle.innerHTML = '&nbsp;&gt;<a href="javascript:void(0)" id="photitle_id" title="点击显示全部大图，再次点击全部还原">显示全部大图</a>' + photitle.innerHTML;
		window.status='在缩略图上点击鼠标中键显示大图';
		$('#photitle_id').addEventListener("click", function(){alb_all(false);}, false);
		GM_addStyle('.album_photo {height:auto;overflow:auto;width:auto}');
	}
};

// 监视中键或全部显示
function alb_all(b){
	var imgs = document.getElementsByClassName('article')[0].getElementsByTagName('img');
	for (var i=0,j=imgs.length; i<j; i++){
		b && imgs[i].parentNode.addEventListener("mousedown", function(e){if (e.button == 1){chk_big(this)}}, false);
		!b && chk_big(imgs[i].parentNode);
	}
};

// 相册切换大小图
function chk_big(p){
	p.innerHTML = /thumb/i.test(p.innerHTML) ? p.innerHTML.replace(/thumb/, 'photo') : p.innerHTML.replace(/photo\/photo/, 'photo/thumb');
	p.parentNode.style.width = (p.parentNode.style.width == 'auto') ? '170px': 'auto';
};

/* ************************ 书影音页面处理 ************************ */

// 添加搜索条函数
function add_search_bar() {
	if ($('#mainpic') && GM_getValue("search_bar", true)) {
		GM_addStyle('\
			#mainpic {\
				overflow: visible;\
			}\
			.s_bar {\
				z-index: 97;\
				position: absolute;\
			}\
			.s_lin {\
				position: absolute;\
				top: -62px;\
				left: 0px;\
				visibility: hidden;\
			}\
			.s_lin2 {\
				position: absolute;\
				top: -62px;\
				left: 62px;\
				visibility: hidden;\
			}\
			.s_bar a {\
				-moz-border-radius: 7px;\
				display: block;\
				background: #eef9eb;\
				padding: 5px;\
				width: 50px;\
				border: 1px solid #fff;\
				line-height: 160%;\
			}\
			.s_bar a:hover {\
				border: 1px solid #aaa;\
				background: #fff;\
				color: #000;\
			}\
			.s_bar:hover .s_tt {\
				visibility: hidden;\
			}\
			.s_bar:hover .s_lin, .s_bar:hover .s_lin2 {\
				visibility: visible;\
			}\
			.s_bar .s_tt {\
				border: 1px solid #aaa;\
				width: 90px;\
				line-height: 100%;\
			}\
		');
		
		var keyword = document.getElementsByTagName('h1')[0].firstChild.nodeValue;//取得h1标签内容
		var key_wd = encodeURIComponent(keyword);
		var s_div = document.createElement("div");
		s_div.className = "s_bar";
		s_div.innerHTML = '\
			<a href="javascript:void(0)" class="s_tt">Search it \
				<font color="red"><b>!</b>\
				</font></a>\
			<span class="s_lin">\
				<a href="http://www.baidu.com/s?ie=utf-8&wd=' + key_wd + ' "target="_blank">百度一下</a>\
				<a href="http://www.google.com/search?&q=' + key_wd + ' "target="_blank">Google</a>\
				<a href="http://www.gougou.com/search?id=92452&search=' + key_wd + '"target="_blank">迅雷下载</a>\
				<a href="http://book.gougou.com/search?restype=3&id=92452&search=' + key_wd + ' "target="_blank">迅雷书籍</a>\
				<a href="http://www.verycd.com/search/folders/' + key_wd + ' "target="_blank">VeryCD</a>\
				<a href="http://zh.wikipedia.org/w/index.php?search=' + key_wd + ' "target="_blank">维基百科</a>\
				<a href="http://books.google.com/books?q=' + key_wd + ' "target="_blank">谷歌书籍</a>\
				<a href="http://video.google.cn/videosearch?q=' + key_wd + '&www_google_domain=www.google.cn&emb=0#" target="_blank">谷歌视频</a>\
			</span>\
			<span class="s_lin2">\
			</span>\
		';
		$('#mainpic').appendChild(s_div);
		otherEngines(keyword);
	}
};

// 添加其他搜索引擎
function otherEngines(keyword){
	var engines = GM_getValue("otherEngines", "").split(/\n/);
	for (i=0,j=engines.length; i<j; i++) {
		var engine = engines[i].split('|');
		if (engine.length > 1) {
			if (engine[1].indexOf('{gb:word}') >= 0){
				replace2GB(keyword, engines[i], engine[0]);
			}else{
				var searchlinks = '<a href="'+ engines[i].replace(engine[0] + '|', '').replace(/{word}/ig, encodeURIComponent(keyword)) +'" target="_blank" >'+ engine[0].replace(/{word}|{gb:word}/ig, keyword.replace('<', '&lt;').replace('>', '&gt;')) +'</a>';
				$('.s_lin2')[0].innerHTML += searchlinks;
			}
		}
	}
};


// 将其他搜索引擎中的搜索关键字替换成 GB2312 编码格式。编码通过查询 baidu 获得
// 感谢 Googlekingkong 的作者，这是他想出的方法
function replace2GB(keyword, enginesi, engine0){
    GM_xmlhttpRequest({
        method: 'GET',
        url: 'http://www.baidu.com/s?ie=utf-8&wd=' + encodeURIComponent(keyword),
        overrideMimeType: 'text/xml; charset=gb2312',
        onload: function(resp){
            if (resp.status < 200 || resp.status > 300) {
                return;
            };
			var keywordGB = String(resp.responseText.match(/word=[^'"&]+['"&]/i)).replace(/word=|['"&]/ig,'');
			var searchlinks = '<a href="'+ enginesi.replace(engine0 + '|', '').replace(/{gb:word}/ig, keywordGB) +'" target="_blank" >'+ engine0.replace(/{word}|{gb:word}/ig, keyword.replace('<', '&lt;').replace('>', '&gt;')) +'</a>';
			$('.s_lin2')[0].innerHTML += searchlinks;
        },
        onerror: function(){
            return;
        }
    });
};

/* ************************ 图片识别处理 ************************ */

// 检测、显示图片函数
function show_pic(){
	var a_links = document.links;
	_pic_ = /^http\S*\.(?:jpg|jpeg|jpe|jfif|bmp|png|gif|tif|tiff|ico)/i;
	switch ( parseInt(GM_getValue("choice", 1)) ){
	case 0:
		break;
	case 1:
		if (Douban || location.href == 'http://userscripts.org/scripts/show/49911') {
		}else{
			break;
		};
	case 2:
		for (var i=0,n=a_links.length; i<n; i++){
			checkIMG(a_links[i]);
		};
		break;
	case 3:// 点击时才检测图片
		for (var i=0,n=a_links.length; i<n; i++){
			a_links[i].addEventListener("mousedown", function(e){
				(e.button == 1) && checkIMG(this)
			}, false);
		};
		break;
	}
};

//检测图片
function checkIMG(link){
	var href = link.href;
	var inner = link.innerHTML;
	if ( _pic_.test(href) && !/<img\s/i.test(inner) ){
		link.addEventListener("mousedown", function(e){
			(e.button == 1) && toggle(this.childNodes[0]) && toggle(this.childNodes[1])// 图片\链接切换
		}, false);
		link.innerHTML = '<img style="max-width:520px;" alt="图片载入ing..." title="点击鼠标中键可切换链接/图片 by豆瓣助手" src="' + href + '" /><span style="display:none;">' + inner + '</span>';
	}
};

/* ************************ 小组、评论、论坛增强处理 ************************ */

// 添加增强工具条
function exGroup(){
	var ct = GM_getValue("count", true), jv = GM_getValue("just_view", true), re = GM_getValue("requote", true);
	var _topic = $('.topic-reply')[0];// 小组回复区
	var _comments = $('#comments');// 书影音评论回复区
	var _table = _comments && _comments.getElementsByTagName('table')[0];
	if ( (ct || jv ||re) && (_topic || _comments) ){
		var replys = (_topic && _topic.getElementsByTagName('li')) || (_table && _comments.getElementsByTagName('table'))|| _comments.getElementsByClassName('wrap');
		var start = parseInt(QueryString('start'))+ 1; //楼层起点

		//工具条CSS & HTML
		GM_addStyle(GM_getValue("auto_hide", false)?'.ctrl_tool{display:none;} li:hover .ctrl_tool{display:block;}':'');
		var re_s = re?'<a name="db_re" href="javascript:void(0)" title="回复该用户发言" >回</a>\
					<a name="db_qt" href="javascript:void(0)" title="引用该用户发言" >引</a>':'';
		var re_l = re?'&gt;<a name="db_re" href="javascript:void(0)" title="回复该用户发言" >回复</a>&nbsp;&nbsp;\
					&gt;<a name="db_qt" href="javascript:void(0)" title="引用该用户发言" >引用</a>&nbsp;&nbsp;':'';
		var jv_s = jv?'<a name="db_jv" href="javascript:void(0)" title="只看该用户所有发言" >只</a>\
					<a name="db_hl" href="javascript:void(0)" title="高亮该用户所有发言，再次点击取消高亮" >亮</a>\
					<a name="db_ig" href="javascript:void(0)" title="忽略该用户所有发言" >略</a>\
					<a name="db_bk" href="javascript:void(0)" title="复原所有发言" >原</a>':'';
		var jv_l = jv?'&gt;<a name="db_jv" href="javascript:void(0)" title="只看该用户所有发言" >只看</a>&nbsp;&nbsp;\
					&gt;<a name="db_hl" href="javascript:void(0)" title="高亮该用户所有发言，再次点击取消高亮" >高亮</a>&nbsp;&nbsp;\
					&gt;<a name="db_ig" href="javascript:void(0)" title="忽略该用户所有发言" >忽略</a>&nbsp;&nbsp;\
					&gt;<a name="db_bk" href="javascript:void(0)" title="复原所有发言" >复原</a>&nbsp;&nbsp;':'';
		var clibtn = GM_getValue("tidybar", false) ? '&gt;'+re_s+jv_s+'&nbsp;&nbsp;' : re_l+jv_l;

		// 对书影音评论进行页面重构
		if (_comments && !_table){
			_comments.innerHTML = _comments.innerHTML
			.replace(/<h2>/, '</li><div class="ctool"></div></div><h2>')
			.replace(/<div/, '</li><div class="ctool"></div></div><div')
			.replace(/^<span class="wrap">/, '<div class="dbhp"><span class=\'wrap\'>')
			.replace(/<\/h3><\/span>/g, '</h3> </span><li>')
			.replace(/<span class="wrap">/g, '</li><div class="ctool"></div></div><div class="dbhp"><span class=\'wrap\'>');
		};
		// 重构条目论坛
		if (_table){
			_comments.innerHTML = _comments.innerHTML
			.replace(/<\/h4><\/span>/g, '</h4></span><p>')
			.replace(/<\/td><\/tr>/g, '</p></td></tr>')
		}; 
		//逐楼添加工具条
		for (var i=0,l=replys.length; i<l; i++){
			var rehead = replys[i].getElementsByTagName('h4')[0] || replys[i].getElementsByTagName('span')[0];
			if (ct){//数楼
				rehead.firstChild.insertData(0,parseInt(i) + start + '楼 ');
			};
			var ban = replys[i].getElementsByClassName('group_banned')[0] || replys[i].getElementsByTagName('td')[1] ||  _comments.getElementsByClassName('ctool')[i];
			if (clibtn && ban){
				var _span = document.createElement("span");
				_span.className="gact fright ctrl_tool";
				_span.innerHTML = clibtn;
				ban.appendChild(_span)
			};	
			if (re){//快速回复
				document.getElementsByName('db_re')[i].addEventListener('click', requote, false);
				document.getElementsByName('db_qt')[i].addEventListener('click', requote, false);
			};
			if (jv){//只看高亮等
				document.getElementsByName('db_jv')[i].addEventListener('click', just_view, false);
				document.getElementsByName('db_hl')[i].addEventListener('click', just_view, false);
				document.getElementsByName('db_ig')[i].addEventListener('click', just_view, false);
				document.getElementsByName('db_bk')[i].addEventListener('click', just_view, false);
			};
		};

		
		//楼主工具条
		if (jv && $('.topic-opt')[0]){
			var toptool = '\
			<span class="fleft" id="louzhu">\
			&gt;<a href="javascript:void(0)" id="db_jv" title="只看楼主发言" >只看</a>&nbsp;&nbsp;\
			&gt;<a href="javascript:void(0)" id="db_hl" title="高亮楼主所有发言，再次点击取消高亮" >高亮</a>&nbsp;&nbsp;\
			&gt;<a href="javascript:void(0)" id="db_ig" title="忽略楼主所有发言" >忽略</a>&nbsp;&nbsp;\
			&gt;<a href="javascript:void(0)" id="db_bk" title="复原所有发言" >复原</a>&nbsp;&nbsp;\
			&gt;<a href="javascript:void(0)" id="livemod" title="开启直播模式，刷新及翻页后自动只看楼主" >直播模式</a>&nbsp;&nbsp;\
			</span> ';
			$('.topic-opt')[0].innerHTML += toptool;
			$('#db_jv').addEventListener('click', just_view, false);
			$('#db_hl').addEventListener('click', just_view, false);
			$('#db_ig').addEventListener('click', just_view, false);
			$('#db_bk').addEventListener('click', just_view, false);
			$('#livemod').addEventListener('click', function(){location.href = location.href.replace(location.search,'') + '?jv=' + this.parentNode.parentNode.parentNode.getElementsByTagName('a')[0].firstChild.nodeValue;}, false);
		};
		islivemod();// 检测是否直播模式
		
		//置顶小组导航条
		$('.paginator')[0] && ($('.aside')[0].getElementsByTagName('p')[0].innerHTML += ('<div class="paginator">' + $('.paginator')[0].innerHTML + '</div>'));
		
		if (re){// 添加快速回复框
			var ck_value = getCookie('ck');
			var re_f = document.createElement("div");
			re_f.id = 're_f';
			re_f.style.cssText = "position:fixed;top:25%;border:1px solid #ccc;display:none;";
			var action = /group/.test(location.href)?'add_comment':'?post=ok#last';
			re_f.innerHTML = '\
				<form name="comment_form" method="post" action="'+ action +'">\
					<div style="display: none;"><input name="ck" value='+ ck_value +' type="hidden"></div>\
					<textarea id="re_text" name="rv_comment" rows="20" style="font-size:12px;width:310px;border:0px;border-bottom:1px solid #ccc;"></textarea><br>\
					<input value="加上去" type="submit">\
					<input value="取消" type="button" onClick="document.getElementById(\'re_f\').style.display=\'none\'">\
					<input value="清空" type="button" onClick="document.getElementById(\'re_text\').value=\'\';document.getElementById(\'re_text\').focus();">\
					<a class="fright gact" href="javascript:;" title="快捷键：\n打开为Shift+Enter\n退出为Esc（会清空内容）\n提交为Ctrl+Enter。\n在输入框内除Ctrl+Enter以及Esc外，其他快捷键无效。\n发言失败时，请自行判断是否已经登录并有权发言。" onClick="document.getElementById(\'re_text\').value+=this.title;document.getElementById(\'re_text\').focus();">使用说明</a>\
				</form>';
			$('.aside')[0].appendChild(re_f);
			 //加载 Shift + Enter 开关回复框快捷键
			addHotKey('shift+Enter',function(){
				var re_text = $('#re_text');
				toggle($('#re_f'));
				re_text.focus();
			});
			$('#re_f').addEventListener('keydown', function(e){
				if (e.keyCode == '27'){
					toggle($('#re_f'));
					$('#re_text').value = '';
				}
			}, false); 
		}
	}
};

// 只看\高亮\忽略\复原 操作
function just_view(urlmsg){
	var yn = (typeof(urlmsg) == 'string')?true:false;
 	var todo = yn?'db_jv':this.name || this.id;
	var parent_3 = this.parentNode ? this.parentNode.parentNode.parentNode : '';// 加三元选择符是为了修正“直播模式”的BUG
	var hasImg = parent_3.className=="dbhp" ? false : true;
	var _comments = $('#comments');
	var clickname = yn ? urlmsg : 
				(parent_3.getElementsByTagName('a')[0].firstChild.nodeValue || parent_3.getElementsByTagName('a')[1].firstChild.nodeValue);
	var replys = hasImg ? 
				(_comments ? _comments.getElementsByTagName('table') : document.getElementsByTagName('ul')[0].getElementsByTagName('li'))
				: _comments.getElementsByClassName('dbhp');
	var aNum = hasImg?1:0;
	for (var i=0,j=replys.length; i<j; i++){
		var reply = replys[i];
		var isit = (reply.getElementsByTagName('a')[aNum].firstChild.nodeValue == clickname)?true:false;
		if (todo == 'db_jv'){
			reply.style.display = isit?'':'none';
		}else if(todo == 'db_hl' && isit){
			reply.style.background = (reply.style.background)?'':GM_getValue("hlcolor", "#eeffee");
		}else if(todo == 'db_ig' && isit){
			reply.style.display = 'none';
		}else if(todo == 'db_bk'){
			reply.style.display = '';
			reply.style.background = '';
		}
	}
};

// 直播模式
function islivemod(){
	var name = QueryString('jv');
	if (name !== 0){
		just_view(decodeURIComponent(name));
		var live = $('#livemod');
		if (live){
			live.firstChild.nodeValue = '关闭直播';
			live.title = '已开启直播模式，点击取消直播; 点击“复原”按钮可临时查看全部帖子';
			live.style.background = '#fffe15';
			live.href = location.href.replace(location.search,'');
		};
		if ($('.paginator')[0]){
			var next = $('.paginator')[0].getElementsByTagName('a');
			for (var i=0,j=next.length; i<j; i++){
				next[i].href += '&jv='+name;
			}
		}
	}
};

// 引用回复函数
// 感谢 NullPointer ，该功能参照了他的 Reply buttons for new Douban 中的格式
function requote(){
	var re_f = $('#re_f');
	var re_text = $('#re_text');
	var reply_doc = this.parentNode.parentNode.parentNode;
	var aNum = (reply_doc.tagName == 'TR')?1:0;
	var rn = (re_text.value == '')?'':'\n';
	if (this.name == 'db_re'){
		var alltext = rn + '@' + reply_doc.getElementsByTagName('a')[aNum].firstChild.nodeValue + '\n';
	}else if(this.name == 'db_qt'){
		var _h4 = reply_doc.getElementsByTagName('h4')[0];
		var rehead = _h4?reply_doc.getElementsByTagName('h4')[0].textContent.replace(/\s+/g,' ')
					:reply_doc.getElementsByTagName('h3')[0].textContent.replace(/\s+/g,' ');
		var redoc = _h4?reply_doc.getElementsByTagName('p')[0].textContent.replace(/\n\s*\n/g, '\n')
					:reply_doc.getElementsByTagName('li')[0].textContent.replace(/\n\s*\n/g, '\n').replace(/^\s{7}/g, '');
		if (redoc.search(/(-{50,})[\s\S]+\1/g)>-1){
			if (confirm("是否删去引文中的引文？")){redoc = redoc.replace(/(-{50,})[\s\S]+\1/g,'').replace(/\n\s*\n/g, '\n');}
		};
		var len = redoc.length;
		var diylen = GM_getValue('diylen', 500);
		if (len > diylen){
			if (confirm("引文太长，是否省略一部分？")){redoc = redoc.substr(0,diylen)+ '......\n(以上引文省略'+ (len-diylen) +'字)';}
		};
		var sepr = '----------------------------------------------------------';
		var alltext  =  rn+sepr+'\n'+rehead+'\n'+redoc+'\n'+sepr+'\n';
	};
	re_text.value += alltext;
	re_f.style.display='';
	re_text.focus();
};  


/* ************************ 其他杂项功能 ************************ */

// Ctrl + Enter 回复快捷键
function ctrlenter(){
	var form = document.forms;
	for (var i=0,j=form.length; i<j; i++) {
		form[i].addEventListener('keydown', function(e){
			if ( e.ctrlKey && e.keyCode == "13") {
				this.submit();
			}
		}, false);
	}
};

// 输入框高亮函数
function hl_input() {
	if (GM_getValue('hl_input', true)) {
		GM_addStyle('input:focus, select:focus, textarea:focus {-moz-outline: 2px solid -moz-rgba(255,153,0,0.5);-moz-outline-radius: 3px;}');
	}
};

//浮动定位工具
function settle(){
	if (GM_getValue('settler', true)){
		var settler = document.createElement("div");
		settler.className = 'gact';
		settler.style.cssText = "position:fixed;bottom:0;border:1px solid #ccc;z-index:10;";
		settler.innerHTML = '\
			<a href="javascript:;" title="置顶，快捷键为：↑" onclick="scrollTo(0,0);">&nbsp;Top↑&nbsp;</a>\
			<a href="javascript:;" title="置底，快捷键为：↓" onclick="scrollTo(0,99999);">&nbsp;Btm↓&nbsp;</a>\
			<a href="javascript:;" title="上一页，快捷键为：←" id="prev">&nbsp;Prev←&nbsp;</a>\
			<a href="javascript:;" title="下一页，快捷键为：→" id="next">&nbsp;Next→&nbsp;</a>';
		$('.aside')[0].appendChild(settler);
		addHotKey(GM_getValue('hk_top', '↑'),function(){scrollTo(0,0)});
		addHotKey(GM_getValue('hk_btm', '↓'),function(){scrollTo(0,99999)});
		addHotKey(GM_getValue('hk_pre', '←'),function(){gotopage('.prev')});
		addHotKey(GM_getValue('hk_nxt', '→'),function(){gotopage('.next')});
		$('#prev').addEventListener('click', function(){gotopage('.prev')}, false); 
		$('#next').addEventListener('click', function(){gotopage('.next')}, false); 
	}
};

//翻页函数
function gotopage(to){
	var h = '',going = $(to)[0];
	(going && (h=going.firstChild.href) && (location.href = h))||alert('呃……翻不动了');
};

//娱乐功能 Konami Code
function openDouban(){
	var k=[];
	document.addEventListener('keydown', function(e){
		k.push(e.keyCode);
		if(k.toString().indexOf("38,38,40,40,37,39,37,39")>=0){
		   GM_openInTab('http://www.douban.com/');
		   k=[];
		}
	}, false); 
};
