/*-----------------------------------------------------------
 
	Original Author:  Wesley Weixing Chen
	Create Time:      Oct 19th, 2006.
	My Website:       http://www.pcpaly.com.cn/
	All Rights Reserved (c) scar_ax@hotmail.com
 
------------------------------------------------------------*/

var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = (userAgent.indexOf('opera') != -1);
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_ie     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf));
var is_moz    = ((navigator.product == 'Gecko') && (!is_saf));
var is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_saf));
var is_mac    = (userAgent.indexOf('mac') != -1);

function findPrefix() {
	if (document.cookie) {
		var str = document.cookie.split('Theme=')[0];
		var beginPos = Math.max(str.lastIndexOf(';') + 1);
		return str.substr(beginPos).replace(/^\s+|\s+$/g, '');
	}
	return "";
}

function getBasePath() {
	var path = location.href.replace(/^https?:\/\/[^\/]+(\/.*)$/gi, "$1");
	path = path.substring(0, path.lastIndexOf("/"));
	path = path.replace(/\/(?:behind|plugin|archive)$/i, '');
	if (path == '/') {
		return '';
	}
	return path;
}

var appPrefix = findPrefix();
var base_path = getBasePath();
var theme = getCookie("Theme");

// --------------------------------------

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
}

String.prototype.trimNullRow = function() {
	var str = this.replace(/^([\t 　\r\n]*<br[^>]*>)*/gi, '');
	str = str.replace(/([\t 　\r\n]*<br[^>]*>[[\t 　\r\n]*)*$/gi, '');
	return str;
}

String.prototype.htmlEncode = function() {
	var str = this.replace(/&/g, '&amp;');
	str = str.replace(/</g, '&lt;');
	str = str.replace(/>/g, '&gt;');
	str = str.replace(/(?:\t| |\v|\r)*\n/g, '<br />\n');
	str = str.replace(/  /g, '&nbsp; ');
	str = str.replace(/\t/g, '&nbsp; &nbsp; ');
	str = str.replace(/\x22/g, '&quot;');
	str = str.replace(/\x27/g, '&#39;');
	return str;
}

String.prototype.htmlDecode = function() {
	var str = this.replace(/&amp;/gi, '&');
	str = str.replace(/&nbsp;/gi, ' ');
	str = str.replace(/&quot;/gi, '"');
	str = str.replace(/&#39;/g, "'");
	str = str.replace(/&lt;/gi, '<');
	str = str.replace(/&gt;/gi, '>');
	str = str.replace(/<br[^>]*>(?:(\r\n)|\r|\n)?/gi, '\n');
	return str;
}

String.prototype.textEncode = function() {
	var str = this.replace(/&amp;/gi, '&');
	str = str.replace(/</g, '&lt;');
	str = str.replace(/>/g, '&gt;');
	return str;
}

String.prototype.textDecode = function() {
	var str = this.replace(/&amp;/gi, '&');
	str = str.replace(/&lt;/gi, '<');
	str = str.replace(/&gt;/gi, '>');
	return str;
}

String.prototype.chnFormat = function() {
	var s = this.replace(/\r/g, '');
	s = s.replace(/[\v\t　 ]*\n[\v\t　 ]*/g, '\n');
	s = s.replace(/(\n+)/g, '$1　　');
	s = s.replace(/[\n]{2,}/g, '\n\n');
	s = s.replace(/\n/g, '\r\n');
	s = '　　' + s;
	s = s.replace(/(　　(!|！))/g, '');
	s = s.replace(/　　(\[uploadimage)/gi, '$1');
	return s;
}

Array.prototype.push = function(element) {
	this[this.length] = element;
	return this;
}

Array.prototype.pop = function(element) {
	var newArray = [];
	for (var i = 0; i < this.length; i++) {
		if (this[i] != element) {
			newArray[newArray.length] = this[i];
		}
	}
	return newArray;
}

function colorToRgb(v) {
	if (!v) return '';
	function hex(d) {
		return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
	};
	if (typeof v == "number") {
		var r = v & 0xFF;
		var g = (v >> 8) & 0xFF;
		var b = (v >> 16) & 0xFF;
		return "#" + hex(r) + hex(g) + hex(b);
	}
	if (v.substr(0, 3) == "rgb") {
		var re = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/;
		if (v.match(re)) {
			var r = parseInt(RegExp.$1);
			var g = parseInt(RegExp.$2);
			var b = parseInt(RegExp.$3);
			return "#" + hex(r) + hex(g) + hex(b);
		}
		return null;
	}
	if (v.substr(0, 1) == "#") {
		return v;
	}
	return null;
}

// --------------------------------------

function $(id) {
	return document.getElementById(id);
}

function w(str) {
	document.write(str);
}

function findSpecialChar(str) {
	var chars = "!@#$%^&*()+=|\/?<>,.:;'\"`[]{}";
	for (var i=0; i<chars.length; i++)
	{
		if ( str.indexOf(chars.substring(i, i+1)) != -1 )
		{
			return true;
		}
	}
	return false;
}

function byteLen(str) {
	var bytes = 0;
	for (i = 0; i < str.length; bytes += (str.charCodeAt(i++) < 255 ? 1 : 2));
	return bytes;
}

function getForm(f) {
	switch (typeof f) {
		default:
		case null:
		case '':
		case 'undefined':
			return document.forms[0];
		case 'string':
		case 'number':
			return document.forms[f];
		case 'object':
			return f;
	}	
}

function checkAll(box) {
	var f = box.form;
	var value = box.checked;
	for (var i = 0; i < f.elements.length; i++) {
		var el = f.elements[i];
		if (el.type.toLowerCase() == 'checkbox' && el.id != "confirm") {
			el.checked = value;
		}
	}
}

function submitOnce(f) {
	for (var i = 0; i < f.elements.length; i++) {
		var el = f.elements[i];
		var type = el.type.toLowerCase();
		if (el.tagName == 'button' || type == 'submit' || type == 'button' || type == 'reset') {
			el.disabled = true;
		}
	}
}

function msgbox(msg, focusCtl) {
	alert(msg);
	if (focusCtl != null) {
		focusCtl.focus();
	}
	return false;
}

function bindFailInfo(msg, tooltiper) {
	tooltiper.innerHTML = msg;
	tooltiper.style.color = 'red';
	return false;
}

function bindSuccessInfo(tooltiper) {
	tooltiper.innerHTML = '√';
	tooltiper.style.color = 'green';
	tooltiper.style.font = '12px 宋体';
	return true;
}

// --------------------------------------

function createChild(parent, tagName, id) {
	var el = document.createElement(tagName);
	if (typeof id != 'undefined') {
		el.id = id;
	}
	parent.appendChild(el);
	return el;
}

function createOption(select, text, value) {
	var opt = document.createElement("option");
	opt.text = text;
	opt.value = value;
	select.options.add(opt);
	return opt;
}

function getOffset(el) {
	var point = { x: el.offsetLeft, y: el.offsetTop };
	//Recursion
	if (el.offsetParent) {
		var parentPoint = getOffset(el.offsetParent);
		point.x += parentPoint.x;
		point.y += parentPoint.y;
	}
	return point;
}

function getScrollOffset() {
	var point;
	if (document.body.scrollTop != 0) {
		point = { x : document.body.scrollLeft, y : document.body.scrollTop };
	} else {
		point = { x : document.documentElement.scrollLeft, y : document.documentElement.scrollTop };
	}
	return point;
}

// --------------------------------------

function setCookie(name, value, expires)
{
	if (typeof expires == 'undefined') {
		document.cookie = appPrefix + name + "=" + escape(value);
	} else {
		var date = new Date();
		date.setTime(date.getTime() + (expires * 86400000));
		document.cookie = appPrefix + name + '=' + escape(value) + '; expires=' + date.toGMTString();
	}
}

function getCookie(name)
{
	var search = appPrefix + name + "=";
	if(document.cookie.length > 0)  {
		offset = document.cookie.indexOf(search);
		if(offset == -1)  {
			return '';
		}
		offset += search.length;
		end = document.cookie.indexOf(";", offset);
		if(end == -1) end = document.cookie.length;
		return unescape(document.cookie.substring(offset, end));
	}
}

// --------------------------------------

function addEvent(el, listener, func) {
	if (is_ie) {
		el.attachEvent('on' + listener, func);
	} else {
		el.addEventListener(listener, func, true);
	}
}

function addEvents(el, listeners, func) {
	for (var i = 0; i < listeners.length; addEvent(el, listeners[i++], func));
}

function removeEvent(el, listener, func) {
	if (is_ie) {
		el.detachEvent("on" + listener, func);
	} else {
		el.removeEventListener(listener, func, true);
	}
}

function removeEvents(el, listeners, func) {
	for (var i = 0; i < listeners.length; removeEvent(el, listeners[i++], func));
}

function stopEvent(e) {
	if (is_ie) {
		e.cancelBubble = true;
		e.returnValue = false;
	} else {
		e.preventDefault();
		e.stopPropagation();
	}
}

function removeClass(el, className) {
	if (el && el.className) {
		var cls = el.className.split(" ");
		var arr = new Array();
		for (var i = cls.length; i > 0;) {
			if (cls[--i] != className) {
				arr[arr.length] = cls[i];
			}
		}
		el.className = arr.join(" ");
	}
}

function addClass(el, className) {
	removeClass(el, className);
	el.className += " " + className;
}

function hasClass(el, className) {
	if (el && el.className) {
		var cls = el.className.split(" ");
		for (var i = cls.length; i > 0;) {
			if (cls[--i] == className) {
				return true;
			}
		}
	}
	return false;
};

// --------------------------------------

var tooltip;
document.write("<div id='js_tooltip' style='position:absolute; z-index:1000; visibility:hidden'></div>");
function popLayer(e) {
	var el = e.srcElement ? e.srcElement : e.target;
	if (!el) {
		return;
	}
	if (el.alt != null && el.alt != '') {
		el.tooltip = el.alt;
		el.alt = '';
	}
	if (el.title != null && el.title != '') {
		el.tooltip = el.title;
		el.title = '';
	}
	if (el.tooltip != tooltip) {
		tooltip = el.tooltip;
		var container = $('js_tooltip');
		if (tooltip == null || tooltip == '') {
			container.style.display = 'none';
			container.style.width = "0px";
			container.style.visibility = 'hidden';
		} else {
			container.style.display = '';
			container.style.width = "auto";
			container.innerHTML = tooltip.replace(/\n/g, '<br>');
			if (container.clientWidth > 280) {
				container.style.width = "280px";
			}
			var mouse = { x : e.clientX, y : e.clientY };
			var scrollOffset = getScrollOffset();
			var size = { w : container.clientWidth, h : container.clientHeight };
			var adjustLeft  = mouse.x + 12 + size.w > document.body.clientWidth ?  - size.w - 12 : 12;
			var adjustRight = mouse.y + 12 + size.h > document.body.clientHeight ? - size.h - 12 : 12;
			container.style.left = (mouse.x + scrollOffset.x + adjustLeft) + 'px';
			container.style.top  = (mouse.y + scrollOffset.y + adjustRight) + 'px';
			container.style.visibility = 'visible';
		}
	}
}
document.onmouseover = function(e) {
	if (typeof popLayer == "function") {
		popLayer(is_ie ? event : e);
	}
}

// --------------------------------------

function callMask(content, hideCloseButton)
{
	if (is_ie) {
		var selects = document.getElementsByTagName('SELECT');
		for (var i = 0; i < selects.length; i++) {
			selects[i].style.visibility = 'hidden';
		}
	}
	var mask = $('__mask');
	if (mask) {
		mask.style.display = '';
		mask.getElementByTagName('td')[0].innerHTML = message;
	} else {
		mask = document.createElement('div');
		mask.id = '__mask';
		mask.style.width = document.body.offsetWidth;
		mask.style.height = (document.body.offsetHeight + 30) + "px";
		mask.style.position = 'absolute';
		mask.style.top = '0px';
		mask.style.left = '0px';
		mask.style.background = 'gray';
		mask.style.filter = 'alpha(opacity=80)';
		mask.style.opacity = '0.80';
		document.body.appendChild(mask);
		var table = document.createElement('table');
		table.style.position = 'absolute';
		table.style.border = '1px black solid';
		table.style.background = 'white';
		mask.appendChild(table);
		var tbody = document.createElement('tbody');
		table.appendChild(tbody);
		var tr1 = document.createElement('tr');
		tbody.appendChild(tr1);
		var td1 = document.createElement('td');
		td1.style.verticalAlign = 'top';
		td1.style.padding = '16px';
		td1.innerHTML = content;
		tr1.appendChild(td1);
		if (typeof hideCloseButton == 'undefined' || !hideCloseButton) {
			var tr2 = document.createElement('tr');
			tbody.appendChild(tr2);
			var td2 = document.createElement('td');
			td2.style.padding = '12px 80px 6px 80px';
			td2.align = 'center';
			td2.style.verticalAlign = 'bottom';
			td2.innerHTML = "<input type='button' value='确定' onclick='javascript:shutMask();' style='background:#eeeeee; width:66px; height:19px; border:1px #111111 solid' onmouseover=\"this.style.background='#ffffaa'\" onmouseout=\"this.style.background='#eeeeee'\" />";
			tr2.appendChild(td2);
		}
		if (table.offsetWidth > document.body.offsetWidth * 3 / 4) {
			table.style.tableLayout = 'fixed';
			table.style.width = document.body.offsetWidth * 3 / 4;
		}
		table.style.left = ((document.body.offsetWidth - table.offsetWidth) * 6 / 13) + 'px';
		table.style.top = ((document.body.offsetHeight - table.offsetHeight) * 4 / 9) + 'px';
	}
}
function shutMask() {
	if (is_ie) {
		var selects = document.getElementsByTagName('SELECT');
		for (var i = 0; i < selects.length; i++) {
			selects[i].style.visibility = 'visible';
		}
	}
	var mask = $('__mask');
	if (mask) {
		mask.style.display = 'none';
	}
}

// --------------------------------------

function forumJump(droplist) {
	var value = droplist.options[droplist.selectedIndex].value;
	if (value != '')
	{
		if (/^[^\.]+\.aspx.*$/.test(value)) {
			location.href = value;
		} else {
			var arr = value.split(':');
			if (arr.length > 1) {
				location.href = 'index.aspx?cid=' + arr[0];
			} else {
				var urlExtension = droplist.getAttribute('urlextension');
				if (urlExtension == '' || urlExtension == 'undefined') {
					location.href = 'forum.aspx?fid=' + value;
				} else {
					location.href = 'forum-' + value + '-1.' + urlExtension;
				}
			}
		}
	}
}

function managerDropListChanged(droplist, extensionOfRewritePath) {
	if (droplist.options[droplist.selectedIndex].value != '') {
		if (extensionOfRewritePath != '') {
			window.open('user-' + droplist.options[droplist.selectedIndex].value + '.' + extensionOfRewritePath);
		} else {
			window.open('user_profile.aspx?name=' + escape(droplist.options[droplist.selectedIndex].value));
		}
		droplist.selectedIndex = 0;
	}
}
function showManagers(managers, extensionOfRewritePath) {
	if (managers == '') {
		return;
	}
	var droplistMode = (byteLen(managers) > 28);
	var arr = managers.split(',');
	var result = '';
	for (var i = 0; i< arr.length; i++) {
		var name = arr[i].trim();
		if (droplistMode) {
			result += ("<option value='" + name + "'>" + name + "</option>");
		} else {
			if (i != 0) result += ", ";
			if (extensionOfRewritePath != '') {
				result += ("<a href='user-" + escape(name) + "." + extensionOfRewritePath + "' target='_blank'>" + name + "</a>");
			} else {
				result += ("<a href='user_profile.aspx?name=" + escape(name) + "' target='_blank'>" + name + "</a>");
			}
		}
	}
	if (droplistMode) {
		result  = "<option value=''>-- 版主 --  </option>" + result;
		result  = "<select onmousewheel='return false' onchange=\"javascript:managerDropListChanged(this, '" + extensionOfRewritePath + "');\" style='width: 100px'>" + result;
		result += "</select>";
	}
	w(result);
}

var collapse_cookie = "Collapsibility";	//do NOT modify its value.
function switchCollapse(img, targetId, saveMemory) {
	var target = $(targetId);
	var targetIdInCookie = targetId.replace(/_content$/gi, '');
	var cookieValue = '';
	var arr = [];
	var found = false;
	if (document.cookie == '') {
		saveMemory = false;
	}
	if (saveMemory) {
		cookieValue = getCookie(collapse_cookie);
		if (cookieValue != '') {
			arr = cookieValue.split(',');
			for (var i = 0; i < arr.length; i++) {
				if (targetIdInCookie == arr[i]) {
					found = true;
					break;
				}
			}
		}
	}
	if (img.src.indexOf('expanded') != -1) {
		img.src = img.src.replace('expanded', 'collapsed');
		target.style.display = 'none';
		if (saveMemory && !found) {
			setCookie(collapse_cookie, arr.push(targetIdInCookie).join(','), 1);
		}
	} else {
		img.src = img.src.replace('collapsed', 'expanded');
		target.style.display = '';
		if (saveMemory && found) {
			setCookie(collapse_cookie, arr.pop(targetIdInCookie).join(','), 1);
		}
	}
}

function tabKey(ta, e) {
	var ev = is_ie ? window.event : e;
	if ((ev.keyCode ? ev.keyCode : ev.charCode) == 9) {
		if (ta.selectionStart) {
			var start = parseInt(ta.selectionStart);
			ta.value = ta.value.substr(0, start) + "	" + ta.value.substr(start);
			ta.selectionStart = start + 1;
			ta.selectionEnd = start + 1;
		} else if (document.selection && document.selection.createRange) {
			var range = document.selection.createRange();
			range.text = "	" + range.text;
			range.moveStart('character', 0);
			range.moveEnd('character', 0);
			range.collapse(true);
			range.select();
		} else if (is_moz && !ta.selectionStart) {
			ta.value += "	";
		}
		stopEvent(ev);
	}
}

function fixSize(image) {
	var size = { w : parseInt(image.clientWidth), h : parseInt(image.clientHeight) };
	var parent = image.parentNode;
	while (parent.parentNode && parent.tagName != "TD") {
		parent = parent.parentNode;
	}
	var maxSize = Math.min(parseInt(parent.clientWidth) - 20, 600);
	if (size.w > maxSize) {
		var newWidth = maxSize - 16;
		image.style.width = newWidth + "px";
		image.style.height = size.h * newWidth / size.w + "px";
		//image.title = "按住CTRL同时滚动鼠标滚轮可调节该图片大小";
		addEvent(image, "mousewheel", function(e) {
			zoomSize(image, is_ie ? window.event : e);
		});
	}
}

function fixAvatar(avatar) {
	if (avatar.clientWidth > 140) {
		avatar.style.width = "140px"; 
	}
	if (avatar.clientHeight > 160) {
		avatar.style.height = "160px";
	}
}

function zoomSize(image, ev) {
	if (ev.ctrlKey) {
		var zoom = parseInt(image.style.zoom, 10) || 100;
		zoom -= event.wheelDelta / 12;
		if(zoom > 0) {
			image.style.zoom = zoom + '%';
		}
		stopEvent(ev);
	}
}