/*

	[Discuz!] (C)2001-2007 Comsenz Inc.

	This is NOT a freeware, use is subject to license terms



	$RCSfile: common.js,v $

	$Revision: 1.103 $

	$Date: 2007/07/30 09:16:52 $

*/



var lang = new Array();

var userAgent = navigator.userAgent.toLowerCase();

var is_opera = userAgent.indexOf('opera') != -1 && opera.version();

var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);

var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);



function $(id) {

	return document.getElementById(id);

}







function checkall(form, prefix, checkall) {

	var checkall = checkall ? checkall : 'chkall';

	for(var i = 0; i < form.elements.length; i++) {

		var e = form.elements[i];

		if(e.name && e.name != checkall && (!prefix || (prefix && e.name.match(prefix)))) {

			e.checked = form.elements[checkall].checked;

		}

	}

}



function doane(event) {

	e = event ? event : window.event;

	if(is_ie) {

		e.returnValue = false;

		e.cancelBubble = true;

	} else if(e) {

		e.stopPropagation();

		e.preventDefault();

	}

}



function fetchCheckbox(cbn) {

	return $(cbn) && $(cbn).checked == true ? 1 : 0;

}



function getcookie(name) {

	var cookie_start = document.cookie.indexOf(name);

	var cookie_end = document.cookie.indexOf(";", cookie_start);

	return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));

}



function thumbImg(obj) {

	var zw = obj.width;

	var zh = obj.height;

	if(is_ie && zw == 0 && zh == 0) {

		var matches;

		re = /width=(["']?)(\d+)(\1)/i;

		matches = re.exec(obj.outerHTML);

		zw = matches[2];

		re = /height=(["']?)(\d+)(\1)/i;

		matches = re.exec(obj.outerHTML);

		zh = matches[2];

	}

	obj.resized = true;

	obj.style.width = zw + 'px';

	obj.style.height = 'auto';

	if(obj.offsetHeight > zh) {

		obj.style.height = zh + 'px';

		obj.style.width = 'auto';

	}

	if(is_ie) {

		var imgid = 'img_' + Math.random();

		obj.id = imgid;

		setTimeout('try {if ($(\''+imgid+'\').offsetHeight > '+zh+') {$(\''+imgid+'\').style.height = \''+zh+'px\';$(\''+imgid+'\').style.width = \'auto\';}} catch(e){}', 1000);

	}

	obj.onload = null;

}



function imgzoom(obj) {}



function in_array(needle, haystack) {

	if(typeof needle == 'string' || typeof needle == 'number') {

		for(var i in haystack) {

			if(haystack[i] == needle) {

					return true;

			}

		}

	}

	return false;

}



function setcopy(text, alertmsg){

	if(is_ie) {

		clipboardData.setData('Text', text);

		alert(alertmsg);

	} else if(prompt('Press Ctrl+C Copy to Clipboard', text)) {

		alert(alertmsg);

	}

}



function isUndefined(variable) {

	return typeof variable == 'undefined' ? true : false;

}



function mb_strlen(str) {

	var len = 0;

	for(var i = 0; i < str.length; i++) {

		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;

	}

	return len;

}



function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {

	var expires = new Date();

	expires.setTime(expires.getTime() + seconds);

	document.cookie = escape(cookieName) + '=' + escape(cookieValue)

		+ (expires ? '; expires=' + expires.toGMTString() : '')

		+ (path ? '; path=' + path : '/')

		+ (domain ? '; domain=' + domain : '')

		+ (secure ? '; secure' : '');

}



function strlen(str) {

	return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;

}



function updatestring(str1, str2, clear) {

	str2 = '_' + str2 + '_';

	return clear ? str1.replace(str2, '') : (str1.indexOf(str2) == -1 ? str1 + str2 : str1);

}



function toggle_collapse(objname, noimg) {

	var obj = $(objname);

	obj.style.display = obj.style.display == '' ? 'none' : '';

	if(!noimg) {

		var img = $(objname + '_img');

		img.src = img.src.indexOf('_yes.gif') == -1 ? img.src.replace(/_no\.gif/, '_yes\.gif') : img.src.replace(/_yes\.gif/, '_no\.gif');

	}

	var collapsed = getcookie('discuz_collapse');

	collapsed =  updatestring(collapsed, objname, !obj.style.display);

	setcookie('discuz_collapse', collapsed, (collapsed ? 86400 * 30 : -(86400 * 30 * 1000)));

}



function trim(str) {

	return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');

}



function _attachEvent(obj, evt, func) {

	if(obj.addEventListener) {

		obj.addEventListener(evt, func, false);

	} else if(obj.attachEvent) {

		obj.attachEvent("on" + evt, func);

	}

}



var jsmenu = new Array();

var ctrlobjclassName;

jsmenu['active'] = new Array();

jsmenu['timer'] = new Array();

jsmenu['iframe'] = new Array();



function initCtrl(ctrlobj, click, duration, timeout, layer) {

	if(ctrlobj && !ctrlobj.initialized) {

		ctrlobj.initialized = true;

		ctrlobj.unselectable = true;



		ctrlobj.outfunc = typeof ctrlobj.onmouseout == 'function' ? ctrlobj.onmouseout : null;

		ctrlobj.onmouseout = function() {

			if(this.outfunc) this.outfunc();

			if(duration < 3) jsmenu['timer'][ctrlobj.id] = setTimeout('hideMenu(' + layer + ')', timeout);

		}



		ctrlobj.overfunc = typeof ctrlobj.onmouseover == 'function' ? ctrlobj.onmouseover : null;

		ctrlobj.onmouseover = function(e) {

			doane(e);

			if(this.overfunc) this.overfunc();

			if(click) {

				clearTimeout(jsmenu['timer'][this.id]);

			} else {

				for(var id in jsmenu['timer']) {

					if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);

				}

			}

		}

	}

}



function initMenu(ctrlid, menuobj, duration, timeout, layer, drag) {

	if(menuobj && !menuobj.initialized) {

		menuobj.initialized = true;

		menuobj.ctrlkey = ctrlid;

		menuobj.onclick = ebygum;

		menuobj.style.position = 'absolute';

		if(duration < 3) {

			if(duration > 1) {

				menuobj.onmouseover = function() {

					clearTimeout(jsmenu['timer'][ctrlid]);

				}

			}

			if(duration != 1) {

				menuobj.onmouseout = function() {

					jsmenu['timer'][ctrlid] = setTimeout('hideMenu(' + layer + ')', timeout);

				}

			}

		}

		menuobj.style.zIndex = 50;

		if(is_ie) {

			menuobj.style.filter += "progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";

		}

		if(drag) {

			menuobj.onmousedown = function(event) {try{menudrag(menuobj, event, 1);}catch(e){}};

			menuobj.onmousemove = function(event) {try{menudrag(menuobj, event, 2);}catch(e){}};

			menuobj.onmouseup = function(event) {try{menudrag(menuobj, event, 3);}catch(e){}};

		}

	}

}



var menudragstart = new Array();

function menudrag(menuobj, e, op) {

	if(op == 1) {

		if(in_array(is_ie ? event.srcElement.tagName : e.target.tagName, ['TEXTAREA', 'INPUT', 'BUTTON', 'SELECT'])) {

			return;

		}

		menudragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];

		menudragstart[2] = parseInt(menuobj.style.left);

		menudragstart[3] = parseInt(menuobj.style.top);

		doane(e);

	} else if(op == 2 && menudragstart[0]) {

		var menudragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];

		menuobj.style.left = (menudragstart[2] + menudragnow[0] - menudragstart[0]) + 'px';

		menuobj.style.top = (menudragstart[3] + menudragnow[1] - menudragstart[1]) + 'px';

		doane(e);

	} else if(op == 3) {

		menudragstart = [];

		doane(e);

	}

}



function showMenu(ctrlid, click, offset, duration, timeout, layer, showid, maxh, drag) {

	var ctrlobj = $(ctrlid);

	if(!ctrlobj) return;

	if(isUndefined(click)) click = false;

	if(isUndefined(offset)) offset = 0;

	if(isUndefined(duration)) duration = 2;

	if(isUndefined(timeout)) timeout = 500;

	if(isUndefined(layer)) layer = 0;

	if(isUndefined(showid)) showid = ctrlid;

	var showobj = $(showid);

	var menuobj = $(showid + '_menu');

	if(!showobj|| !menuobj) return;

	if(isUndefined(maxh)) maxh = 400;

	if(isUndefined(drag)) drag = false;



	if(click && jsmenu['active'][layer] == menuobj) {

		hideMenu(layer);

		return;

	} else {

		hideMenu(layer);

	}



	var len = jsmenu['timer'].length;

	if(len > 0) {

		for(var i=0; i<len; i++) {

			if(jsmenu['timer'][i]) clearTimeout(jsmenu['timer'][i]);

		}

	}



	initCtrl(ctrlobj, click, duration, timeout, layer);

	ctrlobjclassName = ctrlobj.className;

	ctrlobj.className += ' hover';

	initMenu(ctrlid, menuobj, duration, timeout, layer, drag);



	menuobj.style.display = '';

	if(!is_opera) {

		menuobj.style.clip = 'rect(auto, auto, auto, auto)';

	}



	setMenuPosition(showid, offset);



	if(is_ie && is_ie < 7) {

		if(!jsmenu['iframe'][layer]) {

			var iframe = document.createElement('iframe');

			iframe.style.display = 'none';

			iframe.style.position = 'absolute';

			iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';

			$('append_parent') ? $('append_parent').appendChild(iframe) : menuobj.parentNode.appendChild(iframe);

			jsmenu['iframe'][layer] = iframe;

		}

		jsmenu['iframe'][layer].style.top = menuobj.style.top;

		jsmenu['iframe'][layer].style.left = menuobj.style.left;

		jsmenu['iframe'][layer].style.width = menuobj.w;

		jsmenu['iframe'][layer].style.height = menuobj.h;

		jsmenu['iframe'][layer].style.display = 'block';

	}



	if(maxh && menuobj.scrollHeight > maxh) {

		menuobj.style.height = maxh + 'px';

		if(is_opera) {

			menuobj.style.overflow = 'auto';

		} else {

			menuobj.style.overflowY = 'auto';

		}

	}



	if(!duration) {

		setTimeout('hideMenu(' + layer + ')', timeout);

	}



	jsmenu['active'][layer] = menuobj;

}



function setMenuPosition(showid, offset) {

	var showobj = $(showid);

	var menuobj = $(showid + '_menu');

	if(isUndefined(offset)) offset = 0;

	if(showobj) {

		showobj.pos = fetchOffset(showobj);

		showobj.X = showobj.pos['left'];

		showobj.Y = showobj.pos['top'];

		showobj.w = showobj.offsetWidth;

		showobj.h = showobj.offsetHeight;

		menuobj.w = menuobj.offsetWidth;

		menuobj.h = menuobj.offsetHeight;

		if(offset < 3) {

			menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + 'px';

			menuobj.style.top = offset == 1 ? showobj.Y + 'px' : (offset == 2 || ((showobj.Y + showobj.h + menuobj.h > document.documentElement.scrollTop + document.documentElement.clientHeight) && (showobj.Y - menuobj.h >= 0)) ? (showobj.Y - menuobj.h) + 'px' : showobj.Y + showobj.h + 'px');

		} else if(offset == 3) {

			menuobj.style.left = (document.body.clientWidth - menuobj.clientWidth) / 2 + document.body.scrollLeft + 'px';

			menuobj.style.top = (document.body.clientHeight - menuobj.clientHeight) / 2 + document.body.scrollTop + 'px';

		}

		if(menuobj.style.clip && !is_opera) {

			menuobj.style.clip = 'rect(auto, auto, auto, auto)';

		}

	}

}



function hideMenu(layer) {

	if(isUndefined(layer)) layer = 0;

	if(jsmenu['active'][layer]) {

		try {

			$(jsmenu['active'][layer].ctrlkey).className = ctrlobjclassName;

		} catch(e) {}

		clearTimeout(jsmenu['timer'][jsmenu['active'][layer].ctrlkey]);

		jsmenu['active'][layer].style.display = 'none';

		if(is_ie && is_ie < 7 && jsmenu['iframe'][layer]) {

			jsmenu['iframe'][layer].style.display = 'none';

		}

		jsmenu['active'][layer] = null;

	}

}



function fetchOffset(obj) {

	var left_offset = obj.offsetLeft;

	var top_offset = obj.offsetTop;

	while((obj = obj.offsetParent) != null) {

		left_offset += obj.offsetLeft;

		top_offset += obj.offsetTop;

	}

	return { 'left' : left_offset, 'top' : top_offset };

}



function ebygum(eventobj) {

	if(!eventobj || is_ie) {

		window.event.cancelBubble = true;

		return window.event;

	} else {

		if(eventobj.target.type == 'submit') {

			eventobj.target.form.submit();

		}

		eventobj.stopPropagation();

		return eventobj;

	}

}



function menuoption_onclick_function(e) {

	this.clickfunc();

	hideMenu();

}



function menuoption_onclick_link(e) {

	choose(e, this);

}



function menuoption_onmouseover(e) {

	this.className = 'popupmenu_highlight';

}



function menuoption_onmouseout(e) {

	this.className = 'popupmenu_option';

}



function choose(e, obj) {

	var links = obj.getElementsByTagName('a');

	if(links[0]) {

		if(is_ie) {

			links[0].click();

			window.event.cancelBubble = true;

		} else {

			if(e.shiftKey) {

				window.open(links[0].href);

				e.stopPropagation();

				e.preventDefault();

			} else {

				window.location = links[0].href;

				e.stopPropagation();

				e.preventDefault();

			}

		}

		hideMenu();

	}

}



function smiletypescroll(direct) {

	if(direct == 0) {

		$('smileytypes').scrollTop -= 28;

	} else {

		$('smileytypes').scrollTop += 28;

	}

}



var Ajaxs = new Array();

var AjaxStacks = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

var attackevasive = isUndefined(attackevasive) ? 0 : attackevasive;

function Ajax(recvType, waitId) {



	for(var stackId = 0; stackId < AjaxStacks.length && AjaxStacks[stackId] != 0; stackId++);

	AjaxStacks[stackId] = 1;



	var aj = new Object();



	aj.loading = 'Loading...';//public

	aj.recvType = recvType ? recvType : 'XML';//public

	aj.waitId = waitId ? $(waitId) : null;//public



	aj.resultHandle = null;//private

	aj.sendString = '';//private

	aj.targetUrl = '';//private

	aj.stackId = 0;

	aj.stackId = stackId;



	aj.setLoading = function(loading) {

		if(typeof loading !== 'undefined' && loading !== null) aj.loading = loading;

	}



	aj.setRecvType = function(recvtype) {

		aj.recvType = recvtype;

	}



	aj.setWaitId = function(waitid) {

		aj.waitId = typeof waitid == 'object' ? waitid : $(waitid);

	}



	aj.createXMLHttpRequest = function() {

		var request = false;

		if(window.XMLHttpRequest) {

			request = new XMLHttpRequest();

			if(request.overrideMimeType) {

				request.overrideMimeType('text/xml');

			}

		} else if(window.ActiveXObject) {

			var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];

			for(var i=0; i<versions.length; i++) {

				try {

					request = new ActiveXObject(versions[i]);

					if(request) {

						return request;

					}

				} catch(e) {}

			}

		}

		return request;

	}



	aj.XMLHttpRequest = aj.createXMLHttpRequest();

	aj.showLoading = function() {

		if(aj.waitId && (aj.XMLHttpRequest.readyState != 4 || aj.XMLHttpRequest.status != 200)) {

			changedisplay(aj.waitId, '');

			aj.waitId.innerHTML = '<span><img src="' + IMGDIR + '/loading.gif"> ' + aj.loading + '</span>';

		}

	}



	aj.processHandle = function() {

		if(aj.XMLHttpRequest.readyState == 4 && aj.XMLHttpRequest.status == 200) {

			for(k in Ajaxs) {

				if(Ajaxs[k] == aj.targetUrl) {

					Ajaxs[k] = null;

				}

			}

			if(aj.waitId) changedisplay(aj.waitId, 'none');

			if(aj.recvType == 'HTML') {

				aj.resultHandle(aj.XMLHttpRequest.responseText, aj);

			} else if(aj.recvType == 'XML') {

				aj.resultHandle(aj.XMLHttpRequest.responseXML.lastChild.firstChild.nodeValue, aj);

			}

			AjaxStacks[aj.stackId] = 0;

		}

	}



	aj.get = function(targetUrl, resultHandle) {



		setTimeout(function(){aj.showLoading()}, 500);

		if(in_array(targetUrl, Ajaxs)) {

			return false;

		} else {

			Ajaxs.push(targetUrl);

		}

		aj.targetUrl = targetUrl;

		aj.XMLHttpRequest.onreadystatechange = aj.processHandle;

		aj.resultHandle = resultHandle;

		var delay = attackevasive & 1 ? (aj.stackId + 1) * 1001 : 100;

		if(window.XMLHttpRequest) {

			setTimeout(function(){

			aj.XMLHttpRequest.open('GET', aj.targetUrl);

			aj.XMLHttpRequest.send(null);}, delay);

		} else {

			setTimeout(function(){

			aj.XMLHttpRequest.open("GET", targetUrl, true);

			aj.XMLHttpRequest.send();}, delay);

		}



	}

	aj.post = function(targetUrl, sendString, resultHandle) {

		setTimeout(function(){aj.showLoading()}, 500);

		if(in_array(targetUrl, Ajaxs)) {

			return false;

		} else {

			Ajaxs.push(targetUrl);

		}

		aj.targetUrl = targetUrl;

		aj.sendString = sendString;

		aj.XMLHttpRequest.onreadystatechange = aj.processHandle;

		aj.resultHandle = resultHandle;

		aj.XMLHttpRequest.open('POST', targetUrl);

		aj.XMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		aj.XMLHttpRequest.send(aj.sendString);

	}

	return aj;

}



function newfunction(func){

	var args = new Array();

	for(var i=1; i<arguments.length; i++) args.push(arguments[i]);

	return function(event){

		doane(event);

		window[func].apply(window, args);

		return false;

	}

}



function changedisplay(obj, display) {

	if(display == 'auto') {

		obj.style.display = obj.style.display == '' ? 'none' : '';

	} else {

		obj.style.display = display;

	}

	return false;

}



var evalscripts = new Array();

function evalscript(s) {

	if(s.indexOf('<script') == -1) return s;

	var p = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/ig;

	var arr = new Array();

	while(arr = p.exec(s)) {

		appendscript(arr[1], '', arr[2], arr[3]);

	}

	s = s.replace(p, '');

	p = /<script(.*?)>([^\x00]+?)<\/script>/ig;

	while(arr = p.exec(s)) {

		appendscript('', arr[2], arr[1].indexOf('reload=') != -1);

	}

	return s;

}



function appendscript(src, text, reload, charset) {

	var id = hash(src + text);

	if(!reload && in_array(id, evalscripts)) return;

	if(reload && $(id)) {

		$(id).parentNode.removeChild($(id));

	}



	evalscripts.push(id);

	var scriptNode = document.createElement("script");

	scriptNode.type = "text/javascript";

	scriptNode.id = id;

	scriptNode.charset = charset;

	try {

		if(src) {

			scriptNode.src = src;

		} else if(text){

			scriptNode.text = text;

		}

		$('append_parent').appendChild(scriptNode);

	} catch(e) {}

}



function stripscript(s) {

	return s.replace(/<script.*?>.*?<\/script>/ig, '');

}



function ajaxupdateevents(obj, tagName) {

	tagName = tagName ? tagName : 'A';

	var objs = obj.getElementsByTagName(tagName);

	for(k in objs) {

		var o = objs[k];

		ajaxupdateevent(o);

	}

}



function ajaxupdateevent(o) {

	if(typeof o == 'object' && o.getAttribute) {

		if(o.getAttribute('ajaxtarget')) {

			if(!o.id) o.id = Math.random();

			var ajaxevent = o.getAttribute('ajaxevent') ? o.getAttribute('ajaxevent') : 'click';

			var ajaxurl = o.getAttribute('ajaxurl') ? o.getAttribute('ajaxurl') : o.href;

			_attachEvent(o, ajaxevent, newfunction('ajaxget', ajaxurl, o.getAttribute('ajaxtarget'), o.getAttribute('ajaxwaitid'), o.getAttribute('ajaxloading'), o.getAttribute('ajaxdisplay')));

			if(o.getAttribute('ajaxfunc')) {

				o.getAttribute('ajaxfunc').match(/(\w+)\((.+?)\)/);

				_attachEvent(o, ajaxevent, newfunction(RegExp.$1, RegExp.$2));

			}

		}

	}

}



/*

 *@ url: 需求請求的 url

 *@ id : 顯示的 id

 *@ waitid: 等待的 id，默認為顯示的 id，如果 waitid 為空字符串，則不顯示 loading...， 如果為 null，則在 showid 區域顯示

 *@ linkid: 是哪個鏈接觸發的該 ajax 請求，該對象的屬性(如 ajaxdisplay)保存了一些 ajax 請求過程需要的數據。

*/

function ajaxget(url, showid, waitid, loading, display, recall) {

	waitid = typeof waitid == 'undefined' || waitid === null ? showid : waitid;

	var x = new Ajax();

	x.setLoading(loading);

	x.setWaitId(waitid);

	x.display = typeof display == 'undefined' || display == null ? '' : display;

	x.showId = $(showid);

	if(x.showId) x.showId.orgdisplay = typeof x.showId.orgdisplay === 'undefined' ? x.showId.style.display : x.showId.orgdisplay;



	if(url.substr(strlen(url) - 1) == '#') {

		url = url.substr(0, strlen(url) - 1);

		x.autogoto = 1;

	}



	var url = url + '&inajax=1&ajaxtarget=' + showid;

	x.get(url, function(s, x) {

		evaled = false;

		if(s.indexOf('ajaxerror') != -1) {

			evalscript(s);

			evaled = true;

		}

		if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {

			if(x.showId) {

				changedisplay(x.showId, x.showId.orgdisplay);

				changedisplay(x.showId, x.display);

				x.showId.orgdisplay = x.showId.style.display;

				ajaxinnerhtml(x.showId, s);

				ajaxupdateevents(x.showId);

				if(x.autogoto) scroll(0, x.showId.offsetTop);

			}

		}

		if(!evaled)evalscript(s);

		ajaxerror = null;

		if(recall) {eval(recall);}

	});

}



var ajaxpostHandle = 0;

function ajaxpost(formid, showid, waitid) {

	showloading();

	var waitid = typeof waitid == 'undefined' || waitid === null ? showid : (waitid !== '' ? waitid : '');



	if(ajaxpostHandle != 0) {

		return false;

	}

	var ajaxframeid = 'ajaxframe';

	var ajaxframe = $(ajaxframeid);

	if(ajaxframe == null) {

		if (is_ie && !is_opera) {

			ajaxframe = document.createElement("<iframe name='" + ajaxframeid + "' id='" + ajaxframeid + "'></iframe>");

		} else {

			ajaxframe = document.createElement("iframe");

			ajaxframe.name = ajaxframeid;

			ajaxframe.id = ajaxframeid;

		}

		//ajaxframe.id = ajaxframeid;

		ajaxframe.style.display = 'none';

		$('append_parent').appendChild(ajaxframe);



	}

	$(formid).target = ajaxframeid;

	ajaxpostHandle = [showid, ajaxframeid, formid, $(formid).target];

	if(ajaxframe.attachEvent) {

		ajaxframe.detachEvent ('onload', ajaxpost_load);

		ajaxframe.attachEvent('onload', ajaxpost_load);

	} else {

		document.removeEventListener('load', ajaxpost_load, true);

		ajaxframe.addEventListener('load', ajaxpost_load, false);

	}

	$(formid).submit();

	return false;

	//$(waitid).innerHTML = 'Loading...';

}



function ajaxpost_load() {

	showloading('none');

	if(is_ie) {

		var s = $(ajaxpostHandle[1]).contentWindow.document.XMLDocument.text;

	} else {

		var s = $(ajaxpostHandle[1]).contentWindow.document.documentElement.firstChild.nodeValue;

	}

	evaled = false;

	if(s.indexOf('ajaxerror') != -1) {

		evalscript(s);

		evaled = true;

	}

	if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {

		ajaxinnerhtml($(ajaxpostHandle[0]), s);

		if(!evaled)evalscript(s);

		setMenuPosition($(ajaxpostHandle[0]).ctrlid, 0);

		setTimeout("hideMenu()", 3000);

	}

	ajaxerror = null;

	if($(ajaxpostHandle[2])) {

		$(ajaxpostHandle[2]).target = ajaxpostHandle[3];

		//$(ajaxpostHandle[2]).removeChild($(ajaxpostHandle[1]));

	}

	ajaxpostHandle = 0;

}



function ajaxmenu(e, ctrlid, timeout, func, cache, duration, ismenu, divclass, optionclass) {

	showloading();

	if(jsmenu['active'][0] && jsmenu['active'][0].ctrlkey == ctrlid) {

		hideMenu();

		doane(e);

		return;

	} else if(is_ie && is_ie < 7 && document.readyState.toLowerCase() != 'complete') {

		return;

	}

	if(isUndefined(timeout)) timeout = 3000;

	if(isUndefined(func)) func = '';

	if(isUndefined(cache)) cache = 1;

	if(isUndefined(divclass)) divclass = 'popupmenu_popup';

	if(isUndefined(optionclass)) optionclass = 'popupmenu_option';

	if(isUndefined(ismenu)) ismenu = 1;

	if(isUndefined(duration)) duration = timeout > 0 ? 0 : 3;

	var div = $(ctrlid + '_menu');

	if(cache && div) {

		showMenu(ctrlid, e.type == 'click', 0, duration, timeout, 0, ctrlid, 400, 1);

		if(func) setTimeout(func + '(' + ctrlid + ')', timeout);

		doane(e);

	} else {

		if(!div) {

			div = document.createElement('div');

			div.ctrlid = ctrlid;

			div.id = ctrlid + '_menu';

			div.style.display = 'none';

			div.className = divclass;

			$('append_parent').appendChild(div);

		}



		var x = new Ajax();

		var href = !isUndefined($(ctrlid).href) ? $(ctrlid).href : $(ctrlid).attributes['href'].value;

		x.div = div;

		x.etype = e.type;

		x.optionclass = optionclass;

		x.duration = duration;

		x.timeout = timeout;

		x.get(href + '&inajax=1&ajaxmenuid='+ctrlid+'_menu', function(s) {

			evaled = false;

			if(s.indexOf('ajaxerror') != -1) {

				evalscript(s);

				evaled = true;

				if(!cache && duration != 3 && x.div.id) setTimeout('$("append_parent").removeChild($(\'' + x.div.id + '\'))', timeout);

			}

			if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {

				if(x.div) x.div.innerHTML = '<div class="' + x.optionclass + '">' + s + '</div>';

				showMenu(ctrlid, x.etype == 'click', 0, x.duration, x.timeout, 0, ctrlid, 400, 1);

				if(func) setTimeout(func + '("' + ctrlid + '")', x.timeout);

				//if(!cache && duration != 3 && x.div.id) setTimeout('document.body.removeChild($(\'' + x.div.id + '\'))', timeout);

			}

			if(!evaled) evalscript(s);

			ajaxerror = null;

			showloading('none');

		});

		doane(e);

	}

}



//得到一個定長的hash值， 依賴於 stringxor()

function hash(string, length) {

	var length = length ? length : 32;

	var start = 0;

	var i = 0;

	var result = '';

	filllen = length - string.length % length;

	for(i = 0; i < filllen; i++){

		string += "0";

	}

	while(start < string.length) {

		result = stringxor(result, string.substr(start, length));

		start += length;

	}

	return result;

}



function stringxor(s1, s2) {

	var s = '';

	var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

	var max = Math.max(s1.length, s2.length);

	for(var i=0; i<max; i++) {

		var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);

		s += hash.charAt(k % 52);

	}

	return s;

}



function showloading(display, waiting) {

	var display = display ? display : 'block';

	var waiting = waiting ? waiting : 'Loading...';

	$('ajaxwaitid').innerHTML = waiting;

	$('ajaxwaitid').style.display = display;

}



function ajaxinnerhtml(showid, s) {

	if(showid.tagName != 'TBODY') {

		showid.innerHTML = s;

	} else {

		while(showid.firstChild) {

			showid.firstChild.parentNode.removeChild(showid.firstChild);

		}

		var div1 = document.createElement('DIV');

		div1.id = showid.id+'_div';

		div1.innerHTML = '<table><tbody id="'+showid.id+'_tbody">'+s+'</tbody></table>';

		$('append_parent').appendChild(div1);

		var trs = div1.getElementsByTagName('TR');

		var l = trs.length;

		for(var i=0; i<l; i++) {

			showid.appendChild(trs[0]);

		}

		var inputs = div1.getElementsByTagName('INPUT');

		var l = inputs.length;

		for(var i=0; i<l; i++) {

			showid.appendChild(inputs[0]);

		}

		div1.parentNode.removeChild(div1);

	}

}



var hiddenobj = new Array();

var pmwinposition = new Array();

function pmwin(action, param) {

	var objs = document.getElementsByTagName("OBJECT");

	if(action == 'open') {

		for(i = 0;i < objs.length; i ++) {

			if(objs[i].style.visibility != 'hidden') {

				objs[i].setAttribute("oldvisibility", objs[i].style.visibility);

				objs[i].style.visibility = 'hidden';

			}

		}

		var clientWidth = document.body.clientWidth;

		var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;

		var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;

		var pmwidth = 800;

		var pmheight = clientHeight * 0.9;

		if(!$('pmlayer')) {

			div = document.createElement('div');div.id = 'pmlayer';

			div.style.width = pmwidth + 'px';

			div.style.height = pmheight + 'px';

			div.style.left = ((clientWidth - pmwidth) / 2) + 'px';

			div.style.position = 'absolute';

			div.style.zIndex = '999';

			$('append_parent').appendChild(div);

			$('pmlayer').innerHTML = '<div style="width: 800px; background: #666666; margin: 5px auto; text-align: left">' +

				'<div style="width: 800px; height: ' + pmheight + 'px; padding: 1px; background: #FFFFFF; border: 1px solid #7597B8; position: relative; left: -6px; top: -3px">' +

				'<div onmouseover="pmwindrag(this)" style="cursor: move; position: relative; left: 0px; top: 0px; width: 800px; height: 30px; margin-bottom: -30px;"></div>' +

				'<a href="###" onclick="pmwin(\'close\')"><img style="position: absolute; right: 20px; top: 15px" src="' + IMGDIR +'/close.gif" title="關閉" /></a>' +

				'<div id="pmwinmask" style="margin-top: 30px; position: absolute; width: 100%; height: 100%; display: none"></div><iframe id="pmframe" name="pmframe" style="width:' + pmwidth + 'px;height:100%" allowTransparency="true" frameborder="0"></iframe></div></div>';

		}

		$('pmlayer').style.display = '';

		$('pmlayer').style.top = ((clientHeight - pmheight) / 2 + scrollTop) + 'px';

		if(!param) {

			pmframe.location = 'pm.php';

		} else {

			pmframe.location = 'pm.php?' + param;

		}

	} else if(action == 'close') {

		for(i = 0;i < objs.length; i ++) {

			if(objs[i].attributes['oldvisibility']) {

				objs[i].style.visibility = objs[i].attributes['oldvisibility'].nodeValue;

				objs[i].removeAttribute('oldvisibility');

			}

		}

		hiddenobj = new Array();

		$('pmlayer').style.display = 'none';

	}

}



var pmwindragstart = new Array();

function pmwindrag(obj) {

	obj.onmousedown = function(e) {

		if(is_ie) {

			document.body.onselectstart = function() {

				return false;

			}

		}

		pmwindragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];

		pmwindragstart[2] = parseInt($('pmlayer').style.left);

		pmwindragstart[3] = parseInt($('pmlayer').style.top);

		$('pmwinmask').style.display = '';

		doane(e);

	}

	_attachEvent(document.body, 'mousemove', function(e) {

		if(pmwindragstart[0]) {

			var pmwindragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];

			with($('pmlayer')) {

				style.left = (pmwindragstart[2] + pmwindragnow[0] - pmwindragstart[0]) + 'px';

				style.top = (pmwindragstart[3] + pmwindragnow[1] - pmwindragstart[1]) + 'px';

			}

			doane(e);

		}

	});

	obj.onmouseup = function(e) {

		if(is_ie) {

			document.body.onselectstart = function() {

				return true;

			}

		}

		pmwindragstart = [];

		$('pmwinmask').style.display = 'none';

		doane(e);

	}

	obj.onmouseover = null;

}



function pmchecknew() {

	ajaxget('pm.php?checknewpm=' + Math.random(), 'pmnotice', 'ajaxwaitid');

}



var discuz_uid = isUndefined(discuz_uid) ? 0 : discuz_uid;

if(discuz_uid && !getcookie('checkpm') && typeof IN_ADMINCP == 'undefined') {

	if(document.attachEvent) {

		window.attachEvent('onload', pmchecknew);

	} else {

		window.addEventListener('load', pmchecknew, false);

	}

}