var sPop = null;
var postSubmited = false;
var smdiv = new Array();

var userAgent = navigator.userAgent.toLowerCase();
var is_webtv = userAgent.indexOf('webtv') != -1;
var is_kon = userAgent.indexOf('konqueror') != -1;
var is_mac = userAgent.indexOf('mac') != -1;
var is_saf = userAgent.indexOf('applewebkit') != -1 || navigator.vendor == 'Apple Computer, Inc.';
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko' && !is_saf) && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ns = userAgent.indexOf('compatible') == -1 && userAgent.indexOf('mozilla') != -1 && !is_opera && !is_webtv && !is_saf;
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera && !is_saf && !is_webtv) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);

function ctlent(event, clickactive) {
	if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && $('postsubmit')) {
		if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit', 'editsubmit', 'pmsubmit']) && !validate($('postform'))) {
			return;
		}
		postSubmited = true;
		if(!isUndefined(clickactive) && clickactive) {
			$('postsubmit').click();
			$('postsubmit').disabled = true;
		} else {
			$('postsubmit').disabled = true;
			$('postform').submit();
		}
	}
}

function storeCaret(textEl){
	if(textEl.createTextRange){
		textEl.caretPos = document.selection.createRange().duplicate();
	}
}

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 != checkall && (!prefix || (prefix && e.name.match(prefix)))) {
			e.checked = form.elements[checkall].checked;
		}
	}
}

function arraypop(a) {
	if(typeof a != 'object' || !a.length) {
		return null;
	} else {
		var response = a[a.length - 1];
		a.length--;
		return response;
	}
}

function arraypush(a, value) {
	a[a.length] = value;
	return a.length;
}


function findtags(parentobj, tag) {
	if(!isUndefined(parentobj.getElementsByTagName)) {
		return parentobj.getElementsByTagName(tag);
	} else if(parentobj.all && parentobj.all.tags) {
		return parentobj.all.tags(tag);
	} else {
		return null;
	}
}

function copycode(obj) {
	if(is_ie && obj.style.display != 'none') {
		var rng = document.body.createTextRange();
		rng.moveToElementText(obj);
		rng.scrollIntoView();
		rng.select();
		rng.execCommand("Copy");
		rng.collapse(false);
	}
}

function attachimg(obj, action, text) {
	if(action == 'load') {
		if(obj.width > screen.width * 0.7) {
			obj.resized = true;
			obj.width = screen.width * 0.7;
			obj.alt = text;
		}
		obj.onload = null;
	} else if(action == 'mouseover') {
		if(obj.resized) {
			obj.style.cursor = 'pointer';
		}
	} else if(action == 'click') {
		if(!obj.resized) {
			return false;
		} else {
			window.open(text);
		}
	}
}

function attachimginfo(obj, infoobj, show, event) {
	var left_offset = obj.offsetLeft;
	var top_offset = obj.offsetTop;
	var width_offset = obj.offsetWidth;
	var height_offset = obj.offsetHeight;
	while ((obj = obj.offsetParent) != null) {
		left_offset += obj.offsetLeft;
		top_offset += obj.offsetTop;
	}
	if(show) {
		$(infoobj).style.position = 'absolute';
		$(infoobj).style.left = left_offset + 3;
		$(infoobj).style.top = height_offset < 40 ? top_offset + height_offset : top_offset + 3;
		$(infoobj).style.display = '';
	} else {
		if(is_ie) {
			$(infoobj).style.display = 'none';
			return;
		} else {
			var mousex = document.body.scrollLeft + event.clientX;
			var mousey = document.body.scrollTop + event.clientY;
			if(mousex < left_offset || mousex > left_offset + width_offset || mousey < top_offset || mousey > top_offset + height_offset) {
				$(infoobj).style.display = 'none';
			}
		}
	}
}

function setcopy(text, alertmsg){
	if(is_ie) {
		clipboardData.setData('Text', text);
		alert(alertmsg);
	} else {
		prompt('Please press "Ctrl+C" to copy this text', text);
	}
}

function toggle_collapse(objname, unfolded) {
	if(isUndefined(unfolded)) {
		var unfolded = 1;
	}
	var obj = $(objname);
	var oldstatus = obj.style.display;
	var collapsed = getcookie('discuz_collapse');
	var cookie_start = collapsed ? collapsed.indexOf(objname) : -1;
	var cookie_end = cookie_start + objname.length + 1;

	obj.style.display = oldstatus == 'none' ? '' : 'none';
	collapsed = cookie_start != -1 && ((unfolded && oldstatus == 'none') || (!unfolded && oldstatus == '')) ?
			collapsed.substring(0, cookie_start) + collapsed.substring(cookie_end, collapsed.length) : (
			cookie_start == -1 && ((unfolded && oldstatus == '') || (!unfolded && oldstatus == 'none')) ?
			collapsed + objname + ' ' : collapsed);

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

	if(img = $(objname + '_img')) {
		var img_regexp = new RegExp((oldstatus == 'none' ? '_yes' : '_no') + '\\.gif$');
		var img_re = oldstatus == 'none' ? '_no.gif' : '_yes.gif';
		img.src = img.src.replace(img_regexp, img_re);
	}
	if(symbol = $(objname + '_symbol')) {
		symbol.innerHTML = symbol.innerHTML == '+' ? '-' : '+';
	}
}

function imgzoom(o) {
	if(event.ctrlKey) {
		var zoom = parseInt(o.style.zoom, 10) || 100;
		zoom -= event.wheelDelta / 12;
		if(zoom > 0) {
			o.style.zoom = zoom + '%';
		}
		return false;
	} else {
		return true;
	}
}

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 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 AddText(txt) {
	obj = $('postform').message;
	selection = document.selection;
	checkFocus();
	if(!isUndefined(obj.selectionStart)) {
		var opn = obj.selectionStart + 0;
		obj.value = obj.value.substr(0, obj.selectionStart) + txt + obj.value.substr(obj.selectionEnd);
	} else if(selection && selection.createRange) {
		var sel = selection.createRange();
		sel.text = txt;
		sel.moveStart('character', -strlen(txt));
	} else {
		obj.value += txt;
	}
}

function insertAtCaret(textEl, text){
	if(textEl.createTextRange && textEl.caretPos){
		var caretPos = textEl.caretPos;
		caretPos.text += caretPos.text.charAt(caretPos.text.length - 2)	== ' ' ? text +	' ' : text;
	} else if(textEl) {
		textEl.value +=	text;
	} else {
		textEl.value = text;
	}
}

function checkFocus() {
	var obj = typeof wysiwyg == 'undefined' || !wysiwyg ? $('postform').message : editwin;
	if(!obj.hasfocus) {
		obj.focus();
	}
}

function setCaretAtEnd() {
	var obj = typeof wysiwyg == 'undefined' || !wysiwyg ? $('postform').message : editwin;
	if(typeof wysiwyg != 'undefined' && wysiwyg) {
		if(is_moz || is_opera) {

		} else {
			var sel = editdoc.selection.createRange();
			sel.moveStart('character', strlen(getEditorContents()));
			sel.select();
		}
	} else {
		if(obj.createTextRange)  {
			var sel = obj.createTextRange();
			sel.moveStart('character', strlen(obj.value));
			sel.collapse();
			sel.select();
		}
	}
}

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

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 insertSmiley(smilieid) {
	checkFocus();
	var src = $('smilie_' + smilieid).src;
	var code = $('smilie_' + smilieid).pop;
	if(typeof wysiwyg != 'undefined' && wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
		if(is_moz) {
			applyFormat('InsertImage', false, src);
			var smilies = findtags(editdoc.body, 'img');
			for(var i = 0; i < smilies.length; i++) {
				if(smilies[i].src == src && smilies[i].getAttribute('smilieid') < 1) {
					smilies[i].setAttribute('smilieid', smilieid);
					smilies[i].setAttribute('border', "0");
				}
			}
		} else {
			insertText('<img src="' + src + '" border="0" smilieid="' + smilieid + '" alt="" /> ', false);
		}
	} else {
		code += ' ';
		AddText(code);
	}
}

function smileyMenu(ctrl) {
	ctrl.style.cursor = 'pointer';
	if(ctrl.alt) {
		ctrl.pop = ctrl.alt;
		ctrl.alt = '';
	}
	if(ctrl.title) {
		ctrl.lw = ctrl.title;
		ctrl.title = '';
	}
	if(!smdiv[ctrl.id]) {
		smdiv[ctrl.id] = document.createElement('div');
		smdiv[ctrl.id].id = ctrl.id + '_menu';
		smdiv[ctrl.id].style.display = 'none';
		smdiv[ctrl.id].className = 'popupmenu_popup';
		document.body.appendChild(smdiv[ctrl.id]);
	}
	smdiv[ctrl.id].innerHTML = '<table style="width: 60px;height: 60px;text-align: center;vertical-align: middle;" class="altbg2"><tr><td><img src="' + ctrl.src + '" border="0" width="' + ctrl.lw + '" /></td></tr></table>';
	showMenu(ctrl.id, 0, 0, 1, 0);
}

function announcement() {
	$('announcement').innerHTML = '<marquee style="margin: 0px 8px" direction="left" scrollamount="2" scrolldelay="1" onMouseOver="this.stop();" onMouseOut="this.start();">' +
		$('announcement').innerHTML + '</marquee>';
	$('announcement').style.display = 'block';
}

function $(id) {
	return document.getElementById(id);
}

function in_array(needle, haystack) {
	if(typeof needle == 'string') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}

function saveData(data, del) {
	if(!data && isUndefined(del)) {
		return;
	}
	if(typeof wysiwyg != 'undefined' && typeof editorid != 'undefined' && typeof bbinsert != 'undefined' && bbinsert && $(editorid + '_mode') && $(editorid + '_mode').value == 1) {
		data = html2bbcode(data);
	}
	if(is_ie) {
		try {
			var oXMLDoc = textobj.XMLDocument;
			var root = oXMLDoc.firstChild;
			if(root.childNodes.length > 0) {
				root.removeChild(root.firstChild);
			}
			var node = oXMLDoc.createNode(1, 'POST', '');
			var oTimeNow = new Date();
			oTimeNow.setHours(oTimeNow.getHours() + 24);
			textobj.expires = oTimeNow.toUTCString();
			node.setAttribute('message', data);
			oXMLDoc.documentElement.appendChild(node);
			textobj.save('Discuz!');
		} catch(e) {}
	} else if(window.sessionStorage) {
		try {
			sessionStorage.setItem('Discuz!', data);
		} catch(e) {}
	}
}

function loadData() {
	var message = '';
	if(is_ie) {
		try {
			textobj.load('Discuz!');
			var oXMLDoc = textobj.XMLDocument;
			var nodes = oXMLDoc.documentElement.childNodes;
			message = nodes.item(nodes.length - 1).getAttribute('message');
		} catch(e) {}
	} else if(window.sessionStorage) {
		try {
			message = sessionStorage.getItem('Discuz!');
		} catch(e) {}
	}

	if(in_array((message = trim(message)), ['', 'null', 'false', null, false])) {
		alert(lang['post_autosave_none']);
		return;
	}
	if((typeof wysiwyg == 'undefined' || !wysiwyg ? textobj.value : editdoc.body.innerHTML) == '' || confirm(lang['post_autosave_confirm'])) {
		if(typeof wysiwyg == 'undefined' || !wysiwyg) {
			textobj.value = message;
		} else {
			editdoc.body.innerHTML = bbcode2html(message);
		}
	}
}

function deleteData() {
	if(is_ie) {
		saveData('', 'delete');
	} else if(window.sessionStorage) {
		try {
			sessionStorage.removeItem('Discuz!');
		} catch(e) {}
	}
}

function updateseccode(width, height) {
	$('seccodeimage').innerHTML = '<img id="seccode" onclick="updateseccode(' + width + ', '+ height + ')" width="' + width + '" height="' + height + '" src="seccode.php?update=' + Math.random() + '" class="absmiddle" alt="" />';
}

function signature(obj) {
	if(obj.style.maxHeightIE != '') {
		var height = (obj.scrollHeight > parseInt(obj.style.maxHeightIE)) ? obj.style.maxHeightIE : obj.scrollHeight;
		if(obj.innerHTML.indexOf('<IMG ') == -1) {
			obj.style.maxHeightIE = '';
		}
		return height;
	}
}

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

function fetchCheckbox(cbn) {
	return $(cbn) && $(cbn).checked == true ? 1 : 0;
}

function parseurl(str, mode) {
	str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, mode == 'html' ? '$1<img src="$2" border="0">' : '$1[img]$2[/img]');
	str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
	str = str.replace(/([^\w>=\]:"']|^)(([\-\.\w]+@[\.\-\w]+(\.\w+)+))/ig, mode == 'html' ? '$1<a href="mailto:$2">$2</a>' : '$1[email]$2[/email]');
	return str;
}

function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}

function addbookmark(url, site){
	if(is_ie) {
		window.external.addFavorite(url, site);
	} else {
		alert('Please press "Ctrl+D" to add bookmark');
	}
}

function doane(event) {
	e = event ? event : window.event ;
	if(is_ie) {
		e.returnValue = false;
		e.cancelBubble = true;
	} else {
		e.stopPropagation();
		e.preventDefault();
	}
}
var jsmenu = new Array();
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);
		}

		if(click && duration) {
			ctrlobj.clickfunc = typeof ctrlobj.onclick == 'function' ? ctrlobj.onclick : null;
			ctrlobj.onclick = function (e) {
				doane(e);
				if(jsmenu['active'][layer] == null || jsmenu['active'][layer].ctrlkey != this.id) {
					if(this.clickfunc) this.clickfunc();
					else showMenu(this.id, true);
				} else {
					hideMenu(layer);
				}
			}
		}

		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) {
	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 && !is_mac) {
			menuobj.style.filter += "progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";
		}
		initMenuContents(menuobj);
	}
}

function initMenuContents(menuobj) {
	if(menuobj.title == 'menu') {
		menuobj.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity=85,finishOpacity=100,style=0)";
		menuobj.style.opacity = 0.85;
		menuobj.title = '';
	} else {
		var tds = findtags(menuobj, 'td');
		for(var i = 0; i < tds.length; i++) {
			if(tds[i].className == 'popupmenu_option' || tds[i].className == 'editor_colornormal') {
				if(is_ie && !is_mac) {
					tds[i].style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity=85,finishOpacity=100,style=0)";
				}
				tds[i].style.opacity = 0.85;
				if(tds[i].title && tds[i].title == 'nohighlight') {
					tds[i].title = '';
				} else {
					tds[i].ctrlkey = this.ctrlkey;
					if(tds[i].className != 'editor_colornormal') {
						tds[i].onmouseover = menuoption_onmouseover;
						tds[i].onmouseout = menuoption_onmouseout;
					}
					if(typeof tds[i].onclick == 'function') {
						tds[i].clickfunc = tds[i].onclick;
						tds[i].onclick = menuoption_onclick_function;
					} else {
						tds[i].onclick = menuoption_onclick_link;
					}
					if(!is_saf && !is_kon)	{
						try {
							links = findtags(tds[i], 'a');
							for(var j = 0; j < links.length; j++) {
								if(isUndefined(links[j].onclick)) {
									links[j].onclick = ebygum;
								}
							}
						}
						catch(e) {}
					}
				}
			}
		}
	}
}

function showMenu(ctrlid, click, offset, duration, timeout, layer, showid, maxh) {
	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;

	hideMenu(layer);

	for(var id in jsmenu['timer']) {
		if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);
	}

	initCtrl(ctrlobj, click, duration, timeout, layer);
	initMenu(ctrlid, menuobj, duration, timeout, layer);

	menuobj.style.display = '';
	if(!is_opera) {
		menuobj.style.clip = 'rect(auto, auto, auto, auto)';
	}

	var showobj_pos = fetchOffset(showobj);
	var showobj_x = showobj_pos['left']+showobj.offsetWidth;
	var showobj_y = showobj_pos['top'];
	var showobj_w = showobj.offsetWidth;
	var showobj_h = showobj.offsetHeight;
	var menuobj_w = menuobj.offsetWidth;
	var menuobj_h = menuobj.offsetHeight;

	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.body.scrollTop + document.body.clientHeight) && (showobj_y - menuobj_h >= 0)) ? (showobj_y - menuobj_h) + 'px' : showobj_y + showobj_h + 'px');

	if(menuobj.style.clip && !is_opera) {
		menuobj.style.clip = 'rect(auto, auto, auto, auto)';
	}

	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)';
			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_ie || is_opera) {
			menuobj.style.width = menuobj.scrollWidth + 18;
		}
		if(is_opera) {
			menuobj.style.overflow = 'auto';
		} else {
			menuobj.style.overflowY = 'auto';
		}
	}

	if(!duration) {
		setTimeout('hideMenu(' + layer + ')', timeout);
	}

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

function hideMenu(layer) {
	if(isUndefined(layer)) layer = 0;
	if(jsmenu['active'][layer]) {
		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 = findtags(obj, '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();
	}
}

var ttpCtrlExist = true;
try
{
	var ttpCtrl = new ActiveXObject("TTPlayer.OCX.1");
}catch(e){
	ttpCtrlExist = false;
}

if (ttpCtrlExist)
{
	document.write('<object id="Player" classid="CLSID:89AE5F82-410A-4040-9387-68D1144EFD03" width="0" height="0"></object>');
}

var xmlhttp_request = false;
function getXMLRequester( )
{
  try{
    if( window.ActiveXObject ){
      for( var i = 5; i; i-- ){
        try{
          if( i == 2 ){
            xmlhttp_request = new ActiveXObject( "Microsoft.XMLHTTP" );
          }else{
            xmlhttp_request = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" ); 
            xmlhttp_request.setRequestHeader("Content-Type","text/xml");
            xmlhttp_request.setRequestHeader("Content-Type","gb2312");
          }
          break;
        }catch(e){ xmlhttp_request = false;}
      }
    }else if( window.XMLHttpRequest ){
    	      xmlhttp_request = new XMLHttpRequest();
            if (xmlhttp_request.overrideMimeType)
            { xmlhttp_request.overrideMimeType('text/xml'); }
          }
  }catch(e){ xmlhttp_request = false;}
  return xmlhttp_request;
} 

var OnlineHostUrl="http://"+window.location.host;
function setEnjoy(subjectid, val)
{
  url=OnlineHostUrl+"/subject/vote.php?sid="+subjectid+"&enjoy="+val;
  xmlhttp_request=getXMLRequester();
  xmlhttp_request.onreadystatechange = doChangeCnt;
  xmlhttp_request.open('GET', url, true); 
  xmlhttp_request.send(null);
}

function doChangeCnt()
{
  if (xmlhttp_request.readyState == 4){
    if (xmlhttp_request.status == 200) {
    	var val = xmlhttp_request.responseText;
    	var valarr = val.split(' ');
    	var sid      = valarr[0];
    	var retval   = valarr[1];
    	var enjoy    = valarr[2];
    	var notenjoy = valarr[3];
      if (retval == 0){
        alert("抱歉！\n未检测到您的登录状态，请先登录！");
        //window.location="/login_sig.php?Suc_referer=/subject/main.php?sid="+sid;
        loginWindow(event,sid);
      }else if (retval == 1){
        alert("抱歉！\n未找到此音乐派，可能该音乐派已被删除或关闭！\n请选择其它主题！");
      }else if (retval == 2){
        alert("抱歉！\n投票操作未能成功，请您稍后重试！");
      }else if (retval == 3){
        alert("抱歉！\n您已经对这个音乐派投过票了，谢谢您的参与！");
      }else if (retval == 10){
          alert("恭喜！\n投票成功，谢谢您的参与！");
          document.getElementById('enjoynum').innerHTML = enjoy;
          document.getElementById('notenjoynum').innerHTML = notenjoy;
          document.getElementById('enjoynum1').innerHTML = enjoy;
          document.getElementById('notenjoynum1').innerHTML = notenjoy;
      }
    }
  }
}

function setFavorite(subjectid)
{
  url=OnlineHostUrl+"/subject/favorite.php?sid="+subjectid;
  xmlhttp_request=getXMLRequester();
  xmlhttp_request.onreadystatechange = doChangeFavorite;
  xmlhttp_request.open('GET', url, true); 
  xmlhttp_request.send(null);
}

function doChangeFavorite()
{
  if (xmlhttp_request.readyState == 4){
    if (xmlhttp_request.status == 200) {
    	var val = xmlhttp_request.responseText;
    	var valarr = val.split(' ');
    	var sid      = valarr[0];
    	var retval   = valarr[1];
      if (retval == 0){
        alert("抱歉！\n未检测到您的登录状态，请先登录！");
        loginWindow(event,sid);
      }else if (retval == 1){
        alert("抱歉！\n未找到此音乐派，可能该音乐派已被删除或关闭！\n请选择其它主题！");
      }else if (retval == 2){
        alert("抱歉！\n收藏操作未能成功，请您稍后重试！");
      }else if (retval == 3){
        alert("您已经收藏过这个音乐派了！");
      }else if (retval == 10){
        alert("恭喜！\n收藏成功！");
        window.location="/user_paifav.php";
      }
    }
  }
}

function setNormalEnjoy(subjectid, val)
{
  url=OnlineHostUrl+"/subject/vote.php?sid="+subjectid+"&enjoy="+val;
  xmlhttp_request=getXMLRequester();
  xmlhttp_request.onreadystatechange = doChangeNormalCnt;
  xmlhttp_request.open('GET', url, true); 
  xmlhttp_request.send(null);
}

function doChangeNormalCnt()
{
  if (xmlhttp_request.readyState == 4){
    if (xmlhttp_request.status == 200) {
    	var val = xmlhttp_request.responseText;
    	var valarr = val.split(' ');
    	var sid      = valarr[0];
    	var retval   = valarr[1];
    	var enjoy    = valarr[2];
    	var notenjoy = valarr[3];
      if (retval == 0){
        alert("抱歉！\n未检测到您的登录状态，请先登录！");
        //window.location="/login_sig.php?Suc_referer=/subject/main.php?sid="+sid;
        loginWindow(event,sid);
      }else if (retval == 1){
        alert("抱歉！\n未找到此音乐派，可能该音乐派已被删除或关闭！\n请选择其它主题！");
      }else if (retval == 2){
        alert("抱歉！\n投票操作未能成功，请您稍后重试！");
      }else if (retval == 3){
        alert("抱歉！\n您已经对这个音乐派投过票了，谢谢您的参与！");
      }else if (retval == 10){
        alert("恭喜！\n投票成功，谢谢您的参与！");
        document.getElementById('enjoy'+sid).innerHTML = enjoy;
        document.getElementById('notenjoy'+sid).innerHTML = notenjoy;
      }
    }
  }
}

var __sto = setTimeout;
window.setTimeout = function(callback,timeout,param)
{
    var args = Array.prototype.slice.call(arguments,2);
    var _cb = function()
    {
        callback.apply(null,args);
    }
    __sto(_cb,timeout);
}

function playAllSongs(subjectid,lmode)
{
	if (lmode == 2){
    url=OnlineHostUrl+"/subject/allsongs.php?sid="+subjectid;
    xmlhttp_request=getXMLRequester();
    xmlhttp_request.onreadystatechange = doGetAllSongs;
    xmlhttp_request.open('GET', url, true); 
    xmlhttp_request.send(null);
	}else{
		allOpenTTPlayer();
		window.setTimeout(allzjplay,3000,null);
	}
}

function doGetAllSongs()
{
  if (xmlhttp_request.readyState == 4){
    if (xmlhttp_request.status == 200) {
    	var val = xmlhttp_request.responseText;
      if (val == 0){
        alert("抱歉！\n参数错误，未能找到该音乐派，请重试！");
        window.location="/login_sig.php?Suc_referer=/subject/main.php?sid="+sid;
      }else if (val == 1){
        alert("抱歉！\n查询失败，请您稍后重试！");
      }else if (val == 2){
        alert("抱歉！\n未能找到该音乐派，请重试！");
      }else{
      	var sform = document.createElement('form');
      	sform.id     = "AllSongs";
      	sform.name   = "AllSongs";
      	sform.action = "/player/index.php";
      	sform.method = "post";
      	sform.target = "_blank";
      	var valarr = val.split("^@^");
      	for(i = 0; i < valarr.length; i++){
      	  if (trim(valarr[i]) != ""){
      	    var input = document.createElement("input");
      	    input.id    = "checkmp3[]";
      	    input.name  = "checkmp3[]";
      	    input.type  = "hidden";
      	    input.value = URLDecode(valarr[i]);
      	    sform.appendChild(input);
      	  }
      	}
        document.body.appendChild(sform);
      	sform.submit();
      }
    }
  }
}

function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}
var lastform = 0;
function allOpenTTPlayer()
{
  for(var j = document.forms.length - 1; j >= 0; j--){
    var vobj = document.forms[j];
    if (vobj.name.indexOf("item") == 0){
    	lastform = j;
	    for(var i = 0;i<vobj.elements.length;i++){
	    	if(vobj.elements[i].checked && i == vobj.elements.length - 1){
	        var vpars = vobj.elements[i].value.split("|");
					AddSoundToReady_TTplayer(vpars[2],vpars[1],vpars[0]);
		    }
	    }break;
    }
	}
}

function oneOpenTTPlayer(vobj)
{
	for(var i = 0;i<vobj.elements.length;i++){
	 	if(vobj.elements[i].checked && i == vobj.elements.length - 1){
	    var vpars = vobj.elements[i].value.split("|");
			AddSoundToReady_TTplayer(vpars[2],vpars[1],vpars[0]);
	  }
	}
}

function allzjplay(fobj)
{
	try
	{
		var extraInfo = Player.clientPlayer;
		if(extraInfo)
		{
			extraInfo.beginAddSongs();
			if (fobj == null){
			  for(var j = 0; j < document.forms.length; j++){
			    var vobj = document.forms[j];
			    //if (j == 0 || j == 1) continue;
			    if (vobj.name.indexOf("item") == 0){
			    for(var i = 0;i<vobj.elements.length;i++){
			    	if(vobj.elements[i].checked){
 			        var vpars = vobj.elements[i].value.split("|");
 			        //alert(vpars[2]+" "+vpars[0]+" "+vpars[1]);
 			        if (j == lastform && i == vobj.elements.length - 1) break;
			     		extraInfo.AddSong(vpars[2],vpars[1],vpars[0]);
				    }
			    }
			    }
		    }
		  }
			extraInfo.endAddSongs(false, true, true);
		}
	}catch (e){
		alert("非常抱歉\\n只有最新版本千千静听才能支持直接试听功能，请下载最新版本");
	}
}

function onezjplay(fStr)
{
	try
	{
		var extraInfo = Player.clientPlayer;
		if(extraInfo)
		{
			extraInfo.beginAddSongs();
			var fobj = document.forms[fStr];
		  for(var i = 0;i<fobj.elements.length;i++){
		  	if(fobj.elements[i].checked){
		      var vpars = fobj.elements[i].value.split("|");
		      if (fobj.elements.length>5 && i == fobj.elements.length - 1) break;
				  extraInfo.AddSong(vpars[2],vpars[1],vpars[0]);
			  }
		  }
			extraInfo.endAddSongs(false, true, true);
		}
	}catch (e){
		alert("非常抱歉\\n只有最新版本千千静听才能支持直接试听功能，请下载最新版本");
	}
}

var commonSearch = "请输入您要搜索的标签";
function clearSearch(scha)
{
    if(scha.value == commonSearch){
        scha.value = "";
        scha.style.color = "#000";
    }
}

function resetSearch(scha)
{
    if(!scha.value){
        scha.value = commonSearch;
        scha.style.color = "#999";
    }
}

var isIe=(document.all)?true:false; 

function mousePosition(ev) 
{ 
	if(ev == null){
	  return {x:0, y:0};
	}
	if(ev.pageX || ev.pageY){ 
	  return {x:ev.pageX, y:ev.pageY}; 
	} 
	return { 
	 x:ev.clientX + parent.document.body.scrollLeft - parent.document.body.clientLeft,y:ev.clientY + parent.document.body.scrollTop - parent.document.body.clientTop 
	}; 
} 

//弹出方法 
function showMessageBox(wTitle,content,pos,wWidth) 
{ 
	 closeWindow(); 
	 var bWidth=parseInt(parent.document.documentElement.scrollWidth); 
	 var bHeight=parseInt(parent.document.documentElement.scrollHeight); 
	 var back=parent.document.createElement("div"); 
	 back.id="back"; 
	 var styleStr="top:0px;left:0px;position:absolute;background:#F4F4F4;width:"+bWidth+"px;height:"+bHeight+"px;"; 
	 styleStr+=(isIe)?"filter:alpha(opacity=0);":"opacity:0;"; 
	 back.style.cssText=styleStr; 
	 parent.document.body.appendChild(back); 

	 var mesW=parent.document.createElement("div"); 
	 mesW.id="mesWindow"; 
	 mesW.className="mesWindow"; 
	 mesW.innerHTML="<table cellpadding=2 bgcolor=#BCD4FF cellspacing=0 border=0 width=100%><tr><td height=20 class=bold_14_0000>"+wTitle+"</td><td style='width:1px;'><img src='/images/users/btclose.gif' onclick='closeWindow();' alt='关闭窗口' style='CURSOR: hand'></td></tr></table><table cellpadding=0 cellspacing=0 border=0 width=100%><tr><td height='80' valign='middle' id='mesWindowContent'>"+content+"</td></tr></table>"; 
	 
	 //styleStr="left:32%;top:30%;position:absolute;width:"+wWidth+"px;height:100px;";
	 var vleft = parent.document.documentElement.scrollLeft+(parent.document.documentElement.clientWidth-mesW.offsetWidth)/3.1;
	 var vtop = parent.document.documentElement.scrollTop+(parent.document.documentElement.clientHeight-mesW.offsetHeight)/2.5
	 styleStr="left:"+vleft+";top:"+vtop+";position:absolute;width:"+wWidth+"px;height:100px;"; 
	 mesW.style.cssText=styleStr;
	 parent.document.body.appendChild(mesW);
	 //parent.window.scrollTo(vleft,vtop);
	 showBackground(back,50);
} 

//让背景渐渐变暗 
 function showBackground(obj,endInt) 
{ 
	 if(isIe) 
	 { 
		obj.filters.alpha.opacity+=10; 
		if(obj.filters.alpha.opacity<endInt) 
		{ 
			setTimeout(function(){showBackground(obj,endInt)},5); 
		} 
	}else{ 
		var al=parseFloat(obj.style.opacity);al+=0.1; 
		obj.style.opacity=al; 
		if(al<(endInt/100)) 
		{
			setTimeout(function(){showBackground(obj,endInt)},5);
		} 
	} 
} 

//关闭窗口 
function closeWindow() 
{ 
	 if(document.getElementById('back')!=null) 
	 { 
		 document.getElementById('back').parentNode.removeChild(document.getElementById('back')); 
	 } 
	 if(document.getElementById('mesWindow')!=null) 
	 { 
		 document.getElementById('mesWindow').parentNode.removeChild(document.getElementById('mesWindow')); 
	 } 
}

function loginMessageBox(ev,sid) 
{ 
    var objPos = mousePosition(ev);
    messContent = "<table width=\"100%\" height=\"31\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
    messContent += "<form method=\"post\" name=\"login\" target='_self' action='/inc/logging_common_post.php'>";
    messContent += "<tr valign=middle>";
    messContent += "<td width=\"6%\">&nbsp;</td>"
    messContent += "<td width=\"13%\" align=\"left\" valign=\"middle\" class=\"zt_font01\" style=\"color:#000000\">用户名:</td>";
    messContent += "<td width=\"21%\" align=\"left\"><input name=\"username\" type=\"text\" size=\"10\" style=\"height:18\" onKeyDown=\"ctlSubmit(event);\"></td>";
    messContent += "<td width=\"13%\" align=\"center\" valign=\"middle\" class=\"zt_font01\" style=\"color:#000000\">密码:</td>";
    messContent += "<td width=\"23%\" align=\"left\"><input name=\"password\" type=\"password\" size=\"10\" style=\"height:18\" onKeyDown=\"ctlSubmit(event);\"></td>";
    messContent += "<td width=\"20%\" align=\"center\"><span class=\"zt_font01\"><a href=\"#\" onclick=\"CheckAndSubmit();\"><font color=\"blue\">登录</font></a></span><input type=\"hidden\" name=\"cookietime\" value=\"315360000\"><input type=\"hidden\" name=\"submitlogin\" value=\"1\"><input type=\"hidden\" name=\"Suc_referer\" value=\"/subject/main.php?sid="+sid+"\"></td>";
    messContent += "</tr>";
		messContent += "</form>";
		messContent += "</table>";
    showMessageBox('&nbsp;千千音乐在线&nbsp;->&nbsp;登录',messContent,objPos,380);
}

function loginWindow(ev, sid)
{
	  loginMessageBox(ev,sid);
}

function AddSoundToReady_TTplayer(url,title,artist) {
	try
	{
		var extraInfo = Player.clientPlayer;
		if(extraInfo)
		{
			extraInfo.beginAddSongs();
			extraInfo.AddSong(url,title,artist);
			extraInfo.endAddSongs(false, true, false);
		}
	}catch (e){
		alert("非常抱歉\\n只有最新版本千千静听才能支持直接试听功能，请下载最新版本");
	}
}

function AddSoundToPlay_TTplayer(url,title,artist) {
	try
	{
		var extraInfo = Player.clientPlayer;
		if(extraInfo)
		{
			extraInfo.beginAddSongs();
			extraInfo.AddSong(url,title,artist);
			extraInfo.endAddSongs(false, true, true);
		}
	}catch (e){
		alert("非常抱歉\\n只有最新版本千千静听才能支持直接试听功能，请下载最新版本");
	}
}

function multiplay(mVar,lmode)
{
  if (mVar.indexOf("item") != 0){
    playAllSongs(mVar,lmode);
  }else{
    if (lmode == 1){
    	if (document.forms[mVar].elements.length > 5){
    		oneOpenTTPlayer(document.forms[mVar]);
    		window.setTimeout(onezjplay,3000,mVar);
    	}else{
      	onezjplay(mVar);
      }
    }else if (lmode == 2){
      play_song(document.forms[mVar]);
    }else{
      play_song(document.forms[mVar]);
    }
  }
}

function suggestWindow(ev,tacontent,url,mvar) 
{
    var objPos = mousePosition(ev);
    var ta = tacontent.split("|");
    messContent = "<table width=\"100%\" height=\"41\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
    messContent += "<form method=\"post\" name=\"suggestw\" target=\"_target\" accept-charset=\"GBK\" action='/player/index.php'>";
    messContent += "<tr valign=top>";
    messContent += "<td width=\"6%\" height=\"23\">&nbsp;</td>"
    messContent += "<td width=\"93%\" align=\"left\" valign=\"middle\" class='zt_font11'><a href=\"#\" onclick=\"javascript:var lmode=suggestw.listmode.checked;closeWindow();saveListenMode(lmode?1:0);if('"+tacontent+"'!=''){AddSoundToPlay_TTplayer('"+url+"','"+ta[1]+"','"+ta[0]+"');}else{multiplay('"+mvar+"',1);}\">用千千静听客户端播放</a><font color=red>（推荐使用，试听体验更流畅）</font></td>";
    messContent += "</tr>";
    messContent += "<tr valign=middle>";
    messContent += "<td width=\"6%\" height=\"23\">&nbsp;</td>"
    messContent += "<td width=\"93%\" align=\"left\" valign=\"middle\" class='zt_font11'><a href=\"#\" onclick=\"javascript:var lmode=suggestw.listmode.checked;closeWindow();saveListenMode(lmode?2:0);if('"+tacontent+"'!=''){mkplay('"+tacontent+"');}else{multiplay('"+mvar+"',2);}\">WEB播放</a><font color=#0066CC>（原有网页方式）</font></td>";
    messContent += "</tr>";
    messContent += "<tr valign=middle>";
    messContent += "<td width=\"6%\">&nbsp;</td>"
    messContent += "<td width=\"93%\" align=\"left\" valign=\"middle\"><input type=\"Checkbox\" name=\"listmode\" id=\"listmode\" value=\"\" checked>&nbsp;记住我的选择</td>";
    messContent += "</tr>";
		messContent += "</form>";
		messContent += "</table>";
    showMessageBox('&nbsp;千千音乐在线&nbsp;->&nbsp;提示信息',messContent,objPos,380);
}

function CheckAndSubmit()
{
     if (document.login.username.value == "")
     {
         alert("错误\n请输入用户名！");
         document.login.username.focus();
         return (false);
     }

     if (document.login.password.value == "")
     {
         alert("错误\n请输入密码！");
         document.login.password.focus();
         return (false);
     }
	   document.login.submit();
}

function searchArtist(artistname)
{
  if (trim(artistname) != ""){
    url=OnlineHostUrl+"/quan/dosearch.php?qword="+URLEncode(artistname);
    xmlhttp_request=getXMLRequester();
    xmlhttp_request.onreadystatechange = doSearchArtist;
    xmlhttp_request.open('GET', url, true); 
    xmlhttp_request.send(null);
  }else{
    alert("页面异常，请与系统管理员联系！");
  }
}

function doSearchArtist()
{
  if (xmlhttp_request.readyState == 4){
    if (xmlhttp_request.status == 200) {
    	var val = xmlhttp_request.responseText;
      if (val == "0"){
        alert("抱歉，您查询的圈子不存在！");
      }else{
        window.open("/quan/quans.php?aid="+val);
      }
    }
  }
}

