// $Id: global.js 1994 2007-05-28 01:31:22Z youyouxia $
var uagent = navigator.userAgent.toLowerCase();
var isOpera = (uagent.indexOf('opera') != -1 || typeof(window.opera) != 'undefined');
var isSafari = (uagent.indexOf('applewebkit') != -1 || navigator.vendor == 'Apple Computer, Inc.');
var isWebtv = (uagent.indexOf('webtv') != -1);
var isIE = (uagent.indexOf('msie') != -1 && !isOpera && !isSafari && !isWebtv);
var isGecko = (navigator.product == 'Gecko' && !isSafari);
var isMoz = isGecko;
var isKonqueror = (uagent.indexOf('konqueror') != -1);
var isNs = (uagent.indexOf('compatible') == -1 && uagent.indexOf('mozilla') != -1 && !isOpera && !isWebtv && !isSafari);
var isMac = (uagent.indexOf('mac') != -1);
var uaVers = parseInt(navigator.appVersion);

if (typeof Array.prototype.push === 'undefined')
{
	Array.prototype.push = function()
	{
		var i, len = this.length, n = arguments.length;
		for (i = 0; i < n; i++) this[len + i] = arguments[i];
		return this.length;
	}
}

function appendSid(uri)
{
	if (uri.indexOf('s=') < 0 && typeof(sessionid) != 'undefined' && sessionid)
		uri += ((uri.indexOf('?') > -1) ? '&' : '?') + 's=' + sessionid;
	return uri;
}

function $()
{
	var elements = [];
	var len = arguments.length;
	if (len == 1) elements = my_getbyid(arguments[0]);
	else for (var i = 0; i < len; i++) elements.push(my_getbyid(arguments[i]));
	return elements;
}

function my_getbyid(el)
{
	if (typeof el == 'string') el = document.getElementById(el);
	return el;
}

function insertAfter(newElm, targetElm)
{
	if(!(newElm = $(newElm))) return;
	if(!(targetElm = $(targetElm))) return;
	var parent = newElm.parentNode;
	if (parent.lastChild == targetElm) parent.appendChild(newElm);
	else parent.insertBefore(newElm, targetElm.nextSibling);
}

var addEvent = function(o, t, f)
{
	var d = 'addEventListener', n = 'on' + t, rO = o, clean = (t != 'unload');
	if (o[d]) o[d](t, f, false);
	else if (o.attachEvent) o.attachEvent(n, f);
	else
	{
		clean = false;
		if (!o._evts) o._evts = {};
		if (!o._evts[t])
		{
			o._evts[t] = o[n] ? { b: o[n] } : {};
			o[n] = new Function('e', 'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) { o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null; } return r');
			if (t != 'unload') clean = true;
		}
		if (!f._i) f._i = addEvent._i++;
		o._evts[t][f._i] = f;
	}
	if (clean) addEvent(window, 'unload', function(){removeEvent(rO, t, f);});
};
addEvent._i = 1;

var removeEvent = function(o, t, f)
{
	var d = 'removeEventListener';
	if (o[d]) o[d](t, f, false);
	else if (o.detachEvent) o.detachEvent('on' + t, f);
	else if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
};

function cancelEvent(e, c)
{
	e.returnValue = false;
	if (e.preventDefault) e.preventDefault();
	if (c)
	{
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
};

function domReady(f, a)
{
	var n = 0;
	var t = setInterval(function()
	{
		var c = true;
		n++;
		if (document.getElementsByTagName && (document.getElementsByTagName('body')[0] != null || document.body != null))
		{
			c = false;
			if (typeof a == 'object')
			{
				for (var i in a)
				{
					if ((a[i] == 'id' && $(i) == null) || (a[i] == 'tag' && document.getElementsByTagName(i).length < 1))
					{
						c = true;
						break;
					}
				}
			}
			if(!c)
			{
				try { f(); }
				catch(e) { alert('Error: ' + e.description); }
				clearInterval(t);
			}
		}
		if (n >= 60) clearInterval(t);
	}, 250);
};

function getStyle(el, prop)
{
	if(!(el = $(el))) return;
	if (el.currentStyle) return el.currentStyle[prop];
	else if (document.defaultView.getComputedStyle) return document.defaultView.getComputedStyle(el, '')[prop];
	return null;
}

function addClass(el, name, old)
{
	if(!(el = $(el))) return;
	if (!el.className) return (el.className = name);
	var value, pattern = new RegExp('(^|\s)' + old + '(\s|$)');
	if (old && (value = el.className.match(pattern)))
		el.className = el.className.replace(value[1] + old + value[2], value[1] + name + value[2]);
	else el.className += ' ' + name;
}

function inArray(value, array)
{
	var i;
	for (i in array) if (array[i] == value) return i;
	return false;
};

function urlencode(text)
{
	text = escape(text.toString()).replace(/\+/g, '%2B');
	var matches = text.match(/(%([0-9A-F]{2}))/gi);
	if (matches)
	{
		for (var matchid = 0; matchid < matches.length; matchid++)
		{
			var code = matches[matchid].substring(1,3);
			if (parseInt(code, 16) >= 128) text = text.replace(matches[matchid], '%u00' + code);
		}
	}
	text = text.replace('%25', '%u0025');
	return text;
}

function sprintf()
{
	var ret = arguments[0];
	if(ret)
	{
		var reg = /%(-)?(\d+)?\.?(\d+)?(\w)/g;
		var i = 0, l = 0, arr;
		while(arr = reg.exec(ret))
		{
			if (++i > arguments.length) return null;
			var tmp = '';
			if (arr[4] == 'f')
				if (arr[3])	tmp = arguments[i].toFixed(arr[3]);
			else tmp = arguments[i].toString();
			if ((l = Number(arr[2]) - tmp.length) > 0)
			{
				tmp = arr[1] ? tmp + new Array(l + 1).join('   ') : new Array(l + 1).join('   ') + tmp;
			}
			ret = ret.replace(arr[0], tmp);
		}
		return ret;
	}
	return null;
}

var httpRequest = {
pool: [],

get: function ()
{
	var len = this.pool.length, i;
	for (i = 0; i < len; i ++)
		if (this.pool[i].readyState == 0 || this.pool[i].readyState == 4)
			return this.pool[i];
	var obj = this.pool[len] = this.create();
	return obj;
},

create: function ()
{
	var i, obj;
	if ('undefined' != typeof(XMLHttpRequest)) obj = new XMLHttpRequest();
	else if ('undefined' != typeof(ActiveXObject))
	{
		var msxmls = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP.2.6', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
		for (i = 0; i < 7; i++)
		{
			try {obj = new ActiveXObject(msxmls[i]);}
			catch (e) {}
		}
	}
	else alert('Could not create XMLHttpRequest object.');
	return obj;
}};

var enableCache = true, jsCache = [];
function getHtml(uri, e)
{
	var isCallback = (typeof(el) == 'function'), fromType = typeof(uri);
	var useCache = (enableCache && fromType == 'string');
	if (!isCallback && (e = $(e)))
	{
		if (useCache && jsCache[uri])
		{
			e.innerHTML = jsCache[uri];
			return;
		}
		else e.innerHTML = '<blink class="redtxt">Loading...<\/blink>';
	}
	else if (useCache && jsCache[uri]) e(jsCache[uri]);

	var x = httpRequest.get(), postData = null;
	x.onreadystatechange = function()
	{
		if (x.readyState != 4) return;
		if ((isSafari && 'undefined' == typeof(x.status)) || inArray(x.status, ['0', '200', '304']))
		{
			var text = x.responseText;
			if (isCallback) e(text);
			else e.innerHTML = text;
			if (useCache && fromType == 'string') jsCache[uri] = text;
		}
		else alert('Error! HTTP request return the following status message: ' + x.statusText);
	};

	if (fromType != 'string')
	{
		if (!uri.tagName || uri.tagName.toLowerCase() != 'form') return;
		var posturi = appendSid(uri.getAttribute('action'));
		x.open('POST', posturi, true);
		postData = parseForm(uri);
		x.setRequestHeader('Method', 'POST ' + posturi + ' HTTP/1.1');
		x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}
	else x.open('GET', appendSid(uri), true);
	x.send(postData);
}

function parseForm(form)
{
	var formValues = [], formElements = element.elements, len = formElements.length;
	for (var i = 0; i < len; ++i)
	{
		var child = formElements[i];
		if (child.disabled || (child.type && ((child.type == 'radio' || child.type == 'checkbox') && child.checked == false))) continue;
		var name = child.name;
		if (name)
		{
			var n = name.length - 2;
			if (child.type.indexOf('select') > -1)
			{
				var clen = child.length;
				for (var j = 0; j < clen; ++j)
				{
					var option = child.options[j];
					if (option.selected) formValues.push(name + '=' + urlencode(option.value));
				}
			}
			else formValues.push(name + '=' + urlencode(child.value));
		}
	}

	return formValues.join('&');
}

function setCookie(name, value, expires)
{
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) expires = expires * 86400000;
	var expires_date = new Date(today.getTime() + expires);
	document.cookie = ((cookie_id) ? cookie_id : '') +
		name + '=' + urlencode(value) +
		((expires) ? ';expires=' + expires_date.toGMTString() : '') +
		((cookie_path) ? ';path=' + cookie_path : '') +
		((cookie_domain) ? ';domain=' + cookie_domain : '');
		//+ ((cookie_secure) ? ';secure' : '');
}

function getCookie(name)
{
	name = cookie_id + name;
	var start = document.cookie.indexOf(name + '=');
	var len = name.length;
	if (start == -1 || (!start && name != document.cookie.substring(0, len))) return null;
	len += start + 1;
	end = document.cookie.indexOf(';', len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

function toggle(id)
{
	if (!id) return;
	if (el = $(id))
	{
		if (getStyle(el, 'display') == 'none' || getStyle(el, 'visibility') == 'hidden')
			showElement(el);
		else hideElement(el);
	}
}

function showElement(el, dtype, vtype)
{
	if (!(el = $(el))) return;
	el.style.display = (!dtype) ? 'block' : dtype;
	el.style.visibility = (!vtype) ? 'visible' : vtype;
}

function hideElement(el)
{
	showElement(el, 'none', 'hidden');
}

function showHide(id1, id2)
{
	if (id1) toggle(id1);
	if (id2) toggle(id2);
}

function getPosition(e)
{
	if(!(e = $(e))) return;
	var top = e.offsetTop, left = e.offsetLeft, width = e.offsetWidth, height = e.offsetHeight;
	while (e = e.offsetParent)
	{
		if (e.style.position == 'absolute' || e.style.position == 'relative' || (e.style.overflow != 'visible' && e.style.overflow != '')) break;
		top += e.offsetTop;
		left += e.offsetLeft;
	}
	return {top: top, left: left, width: width, height: height};
}

var dBody = null;
function getBody()
{
	if (!dBody) dBody = (document.compatMode && document.compatMode.indexOf('CSS') > -1) ? document.documentElement : document.body;
	return dBody;
}
function getScrollX() {return window.pageXOffset || window.scrollX || getBody().scrollLeft || 0;}
function getScrollY() {return window.pageYOffset || window.scrollY || getBody().scrollTop || 0;}
function getMouseX(evt) {return evt.pageX || evt.clientX + getScrollX() - document.documentElement.clientLeft - document.body.clientLeft || 0;}
function getMouseY(evt) {return evt.pageY || evt.clientY + getScrollY() - document.documentElement.clientTop - document.body.clientTop || 0;}
function getBodyWidth() {return self.innerWidth || getBody().clientWidth || 0;}
function getBodyHeight() {return self.innerHeight || getBody().clientHeight || 0;}

var toggleview = toggle;
var my_hide_div = hideElement;
var my_show_div = showElement;
var set_cookie = setCookie;
var get_cookie = getCookie;

function PopUp(url, name, width, height, center, resize, scroll, posleft, postop,del)
{
	var showx = '', showy = '';
	var X,Y;
	if(typeof del == 'underfined')
	{
		if (!confirm( lang_g['g_delt']))
		{
			return false;
		}
	}
	if (posleft != 0) X = posleft;
	if (postop  != 0) Y = postop;
	if (!scroll) scroll = 1;
	if (!resize) resize = 1;
	if ((parseInt (navigator.appVersion) >= 4 ) && center)
	{
		X = (screen.width  - width ) / 2;
		Y = (screen.height - height) / 2;
	}
	if (X > 0) showx = ',left='+X;
	if (Y > 0) showy = ',top='+Y;
	if (scroll != 0) scroll = 1;
	var Win = window.open( url, name, 'width='+width+',height='+height+ showx + showy + ',resizable='+resize+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no');
}

function CheckAll(fmobj)
{
	var len = fmobj.elements.length;
	for (var i = 0; i < len; i++)
	{
		var e = fmobj.elements[i];
		if (e.name != 'allbox' && e.type == 'checkbox' && !e.disabled)
			e.checked = fmobj.allbox.checked;
	}
}

function highlightAll(str)
{
    if (isIE)
    {
        var rng = document.body.createTextRange();
        rng.moveToElementText(str);
        rng.scrollIntoView();
        rng.select();
        rng.execCommand("Copy");
        rng.collapse(false);
		setTimeout("window.status=''", 1800);
    }
}

function redirlocate(object)
{
	if (object.options[object.selectedIndex].value != '')
		window.location.href = appendSid(object.options[object.selectedIndex].value);
}

function turnAjax()
{
	var closeajax = getCookie('closeajax');
	var tabAjax = $('isajax');
	if (isOpera == true && uaVers < 8.5)
	{
		alert(lang_g['g_error']);
		return false;
	}
	if (!closeajax && typeof closeajax != 'null')
	{
		setCookie('closeajax',"1");
		tabAjax.innerHTML = "<input type='button' value=' "+lang_g['g_open']+" ' class='button' onclick='turnAjax()' />";
		return;
	}
	else
	{
		if (closeajax == '1')
		{
			setCookie('closeajax',"0");
			tabAjax.innerHTML = "<input type='button' value=' "+lang_g['g_close']+" ' class='button' onclick='turnAjax()' />";
			return;
		}
		setCookie('closeajax',"1");
		tabAjax.innerHTML = "<input type='button' value=' "+lang_g['g_open']+" ' class='button' onclick='turnAjax()' />";
		return;
	}
}

function changeMod(Mode)
{
	if (Mode == 2) return false;
	else if (Mode == 0) setCookie('mxeditor', 'bbcode');
	else setCookie('mxeditor', 'wysiwyg');
	var div_mxeditor = $('mxeditorinfo');
	div_mxeditor.innerHTML = lang_g['g_edv'];
}

function SelectTag()
{
	var target = $('selectall').checked;
	if (target == true) SelectAll();
	else NoneAll();
}

function SelectAll()
{
	var rows = document.modform.getElementsByTagName('tr');
	var unique_id, checkbox, marked_row = [];
	var len = rows.length;
	for (var i = 0; i < len; i++)
	{
        checkbox = rows[i].getElementsByTagName('input')[0];
        if (checkbox && checkbox.type == 'checkbox')
        {
            unique_id = checkbox.name + checkbox.value;
            if (checkbox.disabled == false)
            {
                checkbox.checked = true;
                if (typeof(marked_row[unique_id]) == 'undefined' || !marked_row[unique_id])
                {
                    rows[i].className += ' marked';
                    marked_row[unique_id] = true;
                }
            }
	    }
	}
}

function NoneAll()
{
	var rows = document.modform.getElementsByTagName('tr');
    var unique_id, checkbox, marked_row = [];
	var len = rows.length;
	for (var i = 0; i < len; i++)
	{
        checkbox = rows[i].getElementsByTagName( 'input' )[0];
        if (checkbox && checkbox.type == 'checkbox')
        {
            unique_id = checkbox.name + checkbox.value;
            checkbox.checked = false;
            rows[i].className = rows[i].className.replace(' marked', '');
            marked_row[unique_id] = false;
        }
	}

	return true;
}

function check_e_client(imgurl)
{
	var stat = 'ok', lang = '';
	if ($("email").value != $("emailconfirm").value)
	{
		stat = 'error';
		lang = lang_g['g_check_email'];
	}
	$("isok_email_firm").innerHTML = '<span style="color:red;position:absolute;"><img src="./images/' + imgurl + '/note_' + stat + '.gif" /> ' + lang + '</span>';
}

function check_p_client(imgurl)
{
	var password = $('password').value;
	var stat = 'ok', lang = '';
	if (password == '' || password != $('passwordconfirm').value)
	{
		stat = 'error';
		lang = lang_g['g_check_password'];
	}
	$("isok_password").innerHTML = '<span style="color:red;position:absolute;"><img src="./images/' + imgurl + '/note_' + stat + '.gif" /> ' + lang + '</span>';
}

function calculate_byte(str)
{
	if (typeof(wMode) != 'undefined' && wMode)
	{
		str = str.replace(/<img( ||.*?)smilietext=(\'|\"|)(.*?)(\'|\"|>| )(.*?)>/gi, "$3");
		str = str.replace(/<img( ||.*?)src=(\'|\"|)(.*?)(\'|\"|>| )(.*?)>/gi, "[img]$3[/img]");
		str = str.replace(/<[\/\!]*?[^<>]*?>/g, '');
		str = str.replace(/&amp;/g, '1');
		str = str.replace(/&lt;/g, '1');
		str = str.replace(/&gt;/g, '1');
	}
	return str.length;
}

function multi_page_jump(url_bit, totalposts, perpage)
{
	var pages = 1, curpage = 1, show_page = 1;
	if (totalposts % perpage == 0) pages = totalposts / perpage;
	else pages = Math.ceil(totalposts / perpage);
	var msg = lang_g['g_intm'] + pages;
	if (current_page > 0) curpage = (current_page / perpage) - 1;
	if (curpage < pages) show_page = curpage + 1;
	else show_page = curpage - 1;
	var start, userPage = window.prompt(msg, show_page);
	if (userPage > 0)
	{
		if (userPage < 1) userPage = 1;
		if (userPage > pages) userPage = pages;
		if (userPage == 1) start = 0;
		else start = (userPage - 1) * perpage;
		window.location.href = appendSid(url_bit) + '&pp=' + start;
	}
}