document.domain = location.hostname.match(/([^.]*.[^.]*$)/g)[0];

var isIE = /microsoft/i.test(navigator.appName);
var isIE7 = /7\./.test(navigator.appVersion);
var isFX = /netscape/i.test(navigator.appName);

function byId(sId){
	return document.getElementById(sId);
}//byId
function byName(sName){
	return document.getElementsByName(sName);
}//byName
function byTagName(parent, tagName){
	if(parent){
		return parent.getElementsByTagName(tagName);
	}else{
		return document.getElementsByTagName(tagName);
	}
}//byTagName

function eventWithinElement(el){
	var e = eventWithinElement.caller.arguments[0];
	//alert(el.id+ "=="+eventWithinElement.caller);
	var currentEl = e.relatedTarget;
	var hasFound = false;
	try{
		while ((currentEl) && (currentEl.tagName != "BODY")) {
			if(currentEl === el){
				hasFound = true;
				break;
			}
			else{
				currentEl = currentEl.parentNode;
			}
		}
	}
	catch(e){
	}
	return hasFound;
}//eventWithinElement

$(function (){
	$(document.body).click(function (){
		show();
	});
	//纸条:['mbaNavCollege', 'menuNavCollege'],['mbaNavInbox', 'menuNavInbox']
	var lstMenuDivId = [['mbSearchUser', 'menuSearchUser'],['mbaNavFriend', 'menuNavFriend'],['mbaNavSkin', 'menuNavSkin']];
	function SimpleMenu(sThis, sMenu){
		var _this = byId(sThis);
		var _menu = byId(sMenu);
		if(_menu){
			_this.onmouseover = function(event){
				event = event ? event : window.event;
				var doc = _this.ownerDocument,
					top = 0,
					left = 0;
				if(_this.getBoundingClientRect){
					box = _this.getBoundingClientRect();
					top += box.top + Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop);
					left += box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
				}else{
					top = this.offsetTop;
					left = this.offsetLeft;
				}
				_menu.style.top = top + 15 + 'px';	//15:_this.style.height
				_menu.style.left = left + 'px';
				show(_menu);
				if(sThis == 'mbaNavSkin'){
					addSkin();
				}
			}

			if(window.navigator.userAgent.indexOf("MSIE") >= 1){
			_menu.onmouseleave = function(){
						_menu.className = 'hidden';
				}
			}else{
				_menu.onmouseout = function(event){
					if(!eventWithinElement(this))
						_menu.className = 'hidden';
				}
			}
		}
	}
	function show(obj){
		for(var i = 0; i < lstMenuDivId.length; i++){
			if(obj && obj.id == lstMenuDivId[i][1]){
				obj.className = 'jLayer jMenu';
			}else if(byId(lstMenuDivId[i][1])){
				byId(lstMenuDivId[i][1]).className = 'hidden';
			}
		}
	}
	for(var i = 0; i < lstMenuDivId.length; i++){
		SimpleMenu(lstMenuDivId[i][0], lstMenuDivId[i][1]);
	}
});

/**
 * no permission
 * alert no permission information
 * @author anakin(sunyu@zhanzuo.net)
 */
function noPermission(){
	_alert("您没有权限进行此操作！");
	return;
}
function showAlert(msg){
	if(msg)
		_alert(msg);
}
//未审批用户的提示
function unauditedUser(){
	_confirm('', '<span style="font-size:12px;"><em>你的姓名尚未通过审批.故不能使用此功能</em><br />'
			+ '只有使用真实姓名，朋友们才能找到你！</span>', 
			function(){window.location.href = '/settings/user_config_baseinfo.php';}, 
			'修改姓名');
}
/**
* poke
* @param string action maybe:send,rand,reply,del
* @param int toUserId
* @param int pokeId
* @return string
* @author anakin(sunyu@zhanzuo.net)
*/
function Poke(action,toUserId,pokeId, isUserHomePage){
	var isSuccess = false;
	$ajax("/poke/poke_ajax.php", "action=" + action + "&to_uid=" + toUserId + "&poke_id=" + pokeId, function(json){
			//try{
				json = eval('(' + json + ')');
				switch(json.status){
					case 0:		//第一次使用电
						_confirm("要电ta吗？","Biu！Biu！<br />一次电，一声Hi，一个朋友，一份缘<br />ta下次占座的时候会被你电到！",function(){Poke('send', toUserId)},"电ta");
						break;
					case -1:	//连续电
						if(json.message)
							_alert(json.message, null, null, "关闭");
						break;
					case 1:		//放电成功
						if(action != "del"){
							if(isUserHomePage){
								_alert(json.message, "电击感言", null, "关闭");
							}
							else{
								var gotoHomePage = function(){
									window.open("/user_homepage.php?user_id=" + toUserId+"&tj=ts");
									//window.location = "/user_homepage.php?user_id=" + toUserId;
								}
								_confirm("电击感言", json["message"], gotoHomePage, "去ta座位", null, "关闭");
							}
						}
						if(pokeId)
							$("#poke_" + pokeId).remove();
						//向上顶一条
						if(json.poke_id > -1){
							var li_poke = '<li class="clearfix" id="poke_' + json['poke_id'] + '"><p>'
								+ '<a href="/user_homepage.php?user_id=' + json['from_user_id'] + '" target="_blank">'
								+ json['from_user_name'] + '</a> 电你啦！</p><span>'
								+ '<a onClick="Poke(\'reply\',' + json['from_user_id'] + ', ' + json['poke_id'] + ');" href="javascript:void(0);">'
								+ '回电</a> | <a onClick="Poke(\'del\',' + byId("user_id").value + ',' + json['poke_id'] + ');"'
								+ 'href="javascript:void(0);">忽略</a></span></li>';
								
								/*var dl_poke = '<dl id="poke_' + json.poke_id + '"><dt>'
										+ '<span style="font:9px Verdana;">BiuBiu~</span>　'
										+ '<a href="/user_homepage.php?user_id=' + json.from_user_id + '">'
										+ json.from_user_name + '</a> 电你啦！'
										+ '<a onclick="javascript:Poke(\'del\',' + byId("user_id").value + ',' + json.poke_id + ')" href="javascript:void(0);" class="del" >删除</a>'
										+ '</dt><dd><a onClick="Poke(\'reply\',' + json.from_user_id + ', ' + json.poke_id + ');" '
										+ 'href="javascript:void(0);">回电</a> | <a onClick="javascript:Poke(\'del\',' 
										+ byId("user_id").value + ',' + json.poke_id + ');" href="javascript:void(0);">忽略</a></dd></dl>';
										*/
							$("#ul_poke").append(li_poke);

						}
						break;
				}
			//}	
			//catch(e){
			//	_alert("电操作失败，请稍后重试！");
			//}
		}
	);
}

//未审批用户的提示
function unauditedUser(){
	_confirm('', '<span style="font-size:12px;"><em>你的姓名尚未通过审批.故不能使用此功能</em><br />'
			+ '只有使用真实姓名，朋友们才能找到你！</span>', 
			function(){window.location.href = '/settings/user_config_baseinfo.php';}, 
			'修改姓名');
}
/*****************************************************************/
// Web IM call funcitons

function eyouim_initIM(id, user){
	var imWindow = window.open('http://im.zhanzuo.com/webim.php','_blank','height=600,width=360,top=50,left=50,toolbar=no,locationbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
//	var imWindow = window.open('/webim.php','_blank','height=600,width=360,top=50,left=50,toolbar=no,locationbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
	eyouim_toggleLabel(true);
	setCookie('imWindow', id);
}
function eyouim_syncLabel(){
	try{
		if(getCookieByName('imWindow')){
			eyouim_toggleLabel(true);
		}else{
			eyouim_toggleLabel(false);
		}
	}catch(e){}
	/*
	try{
		if (parent.gMainWindow){
			eyouim_toggleLabel(true);
		}else{
			eyouim_toggleLabel(false);
		}
	}catch (e){}
	*/
}
function eyouim_logoff(){
	try{
		if(getCookieByName('imWindow')){
			delCookie('imWindow');
		}
		//parent.logOff(true);
		//parent.setTimeout("location = '/logout.php'", 500);
		window.setTimeout("location = '/logout.php'", 500);
	}catch (e){
		//parent.setTimeout("location = '/logout.php'", 500);
		window.setTimeout("location = '/logout.php'", 500);
	}
}
function eyouim_closeIM(id){
	if(getCookieByName('imWindow') && getCookieByName('imWindow') == id){
		delCookie('imWindow');
	}
	/*
	try{
		parent.logOff(true);
	}
	catch (e){}
	*/
}
function eyouim_toggleLabel(bToggle){
	var toggleElement = byId("toggle-im");
	if (bToggle){
		toggleElement.innerHTML = "关闭";
		toggleElement.opened = true;
	}
	else{
		toggleElement.innerHTML = "打开";
		toggleElement.opened = false;
	}
}
function eyouim_toggleIM(id, user){
	/*
	if (self == parent){
		var redirect =  confirm("在线聊天即将开启，页面会随之刷新，请在点击“确定”前保存你尚未提交的内容");
		if (redirect){
			window.location = "http://" + location.hostname + "/index.php?url=" + 
				location.href.replace(new RegExp("^http://" + location.hostname, "ig"), "");
		}
	}
	else{*/
		var toggleElement = byId("toggle-im");
		if (toggleElement.opened){
			eyouim_closeIM(id);
			eyouim_toggleLabel(false);
		}else{
			if(getCookieByName('imWindow') && getCookieByName('imWindow') == id){
				window._alert? window._alert('你IM已经开启'):alert('你IM已经开启');
				return;
			}
			eyouim_initIM(id, user);
			eyouim_toggleLabel(true);
		}
//	}
}
function redirect(){
	if (self != parent)	{
		parent.location = self.location;
	}
}
/***********************************************************************/

function setCookie(name, value, time, path, domain, secure){
	document.cookie = name + "=" + value+ //escape(value) +
		( (time) ? ";expires=" + time : "") +
		( (path) ? ";path=" + path : ";path=/") +		//可选项，Cookie在服务器端的有效路径,在这里默认为:'/'根目录下
		( (domain) ? ";domain=" + domain : ";domain="+document.domain) +	//可选项，该Cookie的有效域名,在这里默认为:document.domain
		( (secure) ? ";secure" : "");	//可选项， 指明Cookie 是否仅通过安全的 HTTPS 连接传送，0或false或空时为假

/*
	if(time){
		document.cookie = name + "=" + value + "; expires=" + time;
	}else{
		document.cookie = name + "=" + value;
	}*/
}
/* 通过name读取对应的cookie值 */
function getCookieByName(name){
	var cookieValue = "";
	var search = name + "=";
	if(document.cookie.length > 0){
		offset = document.cookie.indexOf(search);
		if (offset != -1){
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) end = document.cookie.length;
			cookieValue = unescape(document.cookie.substring(offset, end))
		}
	}
	return cookieValue;
}
function delCookie(name){//为了删除指定名称的cookie，可以将其过期时间设定为一个过去的时间
	if(getCookieByName(name)){
		var date = new Date();
		date.setTime(date.getTime() - 1);
		setCookie(name, '', date.toGMTString());
		//document.cookie = name + "=a; expires=" + date.toGMTString();
	}
}

window.setTimeout(function(){eyouim_syncLabel()}, 3000);

//<link href="http://img.zhanzuo.ccc/s/peach_css/skin/orange.css?v=200809161418" rel="stylesheet" media="screen" type="text/css" />
function addSkin(){
	var lstSkinName = ['pink','blackred','red','orange','olive','blue','green','purple'];
	for(var i = 0; i < lstSkinName.length; i++){
		var oSkinLink = byId('skin_'+lstSkinName[i]);
		if(!oSkinLink){
			var oLink = document.createElement('link');
			oLink.id = 'skin_'+lstSkinName[i];
			oLink.setAttribute('rel', 'stylesheet');
			oLink.setAttribute('media', 'disable');
			oLink.setAttribute('type', 'text/css');
			oLink.setAttribute('rel', 'stylesheet');
			var oLink2008 = byId('skin_2008');
			var linkHref = oLink2008.href;
			var index1 = oLink2008.href.lastIndexOf('/');
			var str1 = linkHref.substring(0, index1);
			var str2 = linkHref.substring(index1);
			var lst = str2.split('?');
			var cssName = '/' + lstSkinName[i] + '.css';
			var newHref = str1 + cssName + '?' +lst[1];
			oLink.href = newHref;
			document.getElementsByTagName('head')[0].appendChild(oLink);
		}
	}

}//
function changeSkin(theme){
	if(theme == '黑板'){
		theme = 'classic';
	}
	var oLink2008 = byId('skin_2008');
	var linkHref = oLink2008.href;
	var index1 = oLink2008.href.lastIndexOf('/');
	var str1 = linkHref.substring(0, index1);
	var str2 = linkHref.substring(index1);
	var lst = str2.split('?');
	var cssName = '/' + theme + '.css';
	var newHref = str1 + cssName + '?' +lst[1];
	

	try{
		if(typeof $ajax != 'undefined'){
			$ajax('/settings/ajax_change_theme.php?theme='+theme, null,function(sOK){
					if(sOK == 'ok'){
						oLink2008.href = newHref;
					}
				}
			);
		}else if(typeof $.ajax != 'undefined'){
			$.ajax(
				{type: 'get',
					url: '/settings/ajax_change_theme.php?theme='+theme,
					data: null,
					success: function(sOK){
						if(sOK == 'ok'){
							oLink2008.href = newHref;
						}
					}
				}
			);
		}
		
	}catch(e){ }
	
}//changeSkin

//for kakawang
function man_stat_url(stat, mantype, childtype, a_user, t_user){
	try{
		if(typeof $ajax != 'undefined'){
			$ajax('urlstat/user_action_stat.php?stat='+stat+'&mantype='+mantype+'&childtype='+childtype+'&a_user='+a_user+'&t_user='+t_user, null,function(json){}
			);
		}else if(typeof $.ajax != 'undefined'){
			$.ajax(
				{type: 'get',
					url: 'urlstat/user_action_stat.php?stat='+stat+'&mantype='+mantype+'&childtype='+childtype+'&a_user='+a_user+'&t_user='+t_user,
					data: null,
					success: function(json){}
				}
			);
		}
	}catch(e){ }
}//changeSkin

function cancelFont()
{
	try{
		if(typeof $ajax != 'undefined'){
			$ajax('/settings/user_config_font.php?action=undo', null,function(json){window.location.href = window.location.href;}
			);
		}else if(typeof $.ajax != 'undefined'){
			$.ajax(
				{type: 'get',
					url: '/settings/user_config_font.php?action=undo',
					data: null,
					success: function(json){window.location.href = window.location.href;}
				}
			);
		}
	}catch(e){ }
}
function changeFont()
{
	try{
		if(typeof $ajax != 'undefined'){
			$ajax('/settings/user_config_font.php?action=do', null,function(json){window.location.href = '/settings/user_config_font.php';}
			);
		}else if(typeof $.ajax != 'undefined'){
			$.ajax(
				{type: 'get',
					url: '/settings/user_config_font.php?action=do',
					data: null,
					success: function(json){window.location.href = '/settings/user_config_font.php';}
				}
			);
		}
	}catch(e){ }
}



//********************互动快讯***********************
//获得新快讯内容
function getNews(){
//	try{
		if(typeof $ajax != 'undefined'){
			$ajax('/message/msg_news_flash_ajax.php?t=get', '', function(sHTML){
					if(sHTML || sHTML == ''){
						var oBoxReminds = byId('box_reminds');
						if(oBoxReminds){
							oBoxReminds.innerHTML = sHTML;
							oBoxReminds.style.display = sHTML ? '' : 'none';
						}
					}
				}
			)
		}else if(typeof $.ajax != 'undefined'){
			$.ajax(
				{type: 'get',
					url: '/message/msg_news_flash_ajax.php?t=get',
					data: null,
					success: function(sHTML){
						var oBoxReminds = byId('box_reminds');
						if(sHTML || sHTML == ''){
							if(oBoxReminds){
								oBoxReminds.innerHTML = sHTML;
								oBoxReminds.style.display = sHTML ? '' : 'none';
							}
						}
					}
				}
			);
		}
//	}catch(e){}
}

var sWindowTitle = document.title.innerHTML ? document.title.innerHTML : document.title;
var isNotified = false;	//是否正在提醒有新快讯
//停止Title提醒
function stopNotify_news(){
	if(isNotified){
		isNotified = false;
		document.title = sWindowTitle;
	}
}
//开始Title提醒
function startNotify_news(){
	if(!isNotified){
		isNotified = true;
		var switchTitle = function(sWindowTitle){
			if(isNotified){
				var sMsgTitle = '【新互动快讯】', sEmptyTitle = '【　　　　　】';
				if(document.title.indexOf(sMsgTitle) != -1){
					document.title = sEmptyTitle + sWindowTitle;
				}else{
					document.title = sMsgTitle + sWindowTitle;
				}
				window.setTimeout(function(){switchTitle(sWindowTitle)}, 1000);
			}
		}
		switchTitle(sWindowTitle);
		window.setTimeout(function(){stopNotify_news();}, 30000);
	}
}

//是否有新快讯
function isHaveNews(){
//	try{
		if(typeof $ajax != 'undefined'){
			$ajax('/message/msg_news_flash_ajax.php?t=is', '', function(isHave){
					if(isHave == '1' || isHave == '0' || isHave == '2'){
						setCookie('isHave',isHave);
						if(getCookieByName('isHave') == '1' || getCookieByName('isHave') == '2'){
							if(window.location.pathname.indexOf('message.php') != -1){
								getNews();
							}
							if(getCookieByName('isHave') == '1')
								startNotify_news();
						}
					}
				}
			);
		}else if(typeof $.ajax != 'undefined'){
			$.ajax(
				{type: 'get',
					url: '/message/msg_news_flash_ajax.php?t=is',
					data: null,
					success: function(isHave){
						if(isHave == '1' || isHave == '2' || isHave == '0'){
							setCookie('isHave',isHave);
							if(getCookieByName('isHave') == '1' || getCookieByName('isHave') == '2'){
								if(window.location.pathname.indexOf('message.php') != -1){
									getNews();
								}
								if(getCookieByName('isHave') == '1')
									startNotify_news();
							}
						}
					}
				}
			);
		}
//	}catch(e){}
}//
//检查快讯
function checkNow(){
//	try{
	var oBoxReminds= byId('box_reminds');
	if(oBoxReminds && oBoxReminds.innerHTML == '')
		oBoxReminds.style.display = 'none';
	else if(oBoxReminds){
		oBoxReminds.style.display = '';
	}
	var arrPageIDs_new = [];
	var iMaxPageID_new = 0;
	if(getCookieByName('pageIDs'))
		arrPageIDs_new = getCookieByName('pageIDs').split(',');
	
	for(var i = 0; i < arrPageIDs_new.length; i++){
		iMaxPageID_new = Math.max(arrPageIDs_new[i],iMaxPageID_new);
	}
	var iMyPageID_new = ++iMaxPageID_new;
	arrPageIDs_new.push(iMyPageID_new);
	setCookie('pageIDs', arrPageIDs_new.join());
	
//设置时间间隔
	var iLongTime_new = 5*60*1000, iShortTime_new = 1*60*1000;
	var oTimerObj_new;

	

	//检查工作
	var checkWork = function(sType){
		var oNowDate = new Date();
		var iNowTime = oNowDate.getTime();	//当前时间
		var sMeURL = window.location.href;	//我的URL
		var iWorkTime = getCookieByName('worktime');	//上次工作时间
		
		var timeDifference = Math.abs(iNowTime - iWorkTime);
		if(getCookieByName('workPageID') && parseInt(getCookieByName('workPageID')) == iMyPageID_new){
			setCookie('worktime', iNowTime);
//			document.title += ' i am work';
			isHaveNews();
		}else if(!getCookieByName('workPageID') || timeDifference > (iLongTime_new+iShortTime_new)){
			setCookie('workPageID', iMyPageID_new);
			setCookie('worktime', iNowTime);
//			document.title += ' --i am work';
			isHaveNews();
		}else{
//			document.title += ' have work' ;
			if(sType != 'long'){
				myTimerFunc('long');
			}
			if(getCookieByName('isHave') == '1' || getCookieByName('isHave') == '2'){
				if(window.location.pathname.indexOf('message.php') != -1){
					getNews();
				}
			}
		}
	}

		//timer 定时器
		var myTimerFunc = function(sType){
			if(sType == 'short' && window.location.pathname.indexOf('message.php') != -1){
				isHaveNews();
				if(getCookieByName('isHave') == '0')
					getNews();
			}
			window.clearInterval(oTimerObj_new);
			oTimerObj_new = window.setInterval(function(){checkWork(sType);}, sType=='short' ? iShortTime_new: iLongTime_new);
		}

		window.onload = function(){
			setCookie('workPageID', iMyPageID_new);
			myTimerFunc('short');
		}
		window.onunload = function(){
			window.clearInterval(oTimerObj_new);
			delCookie('isHave');
			if(parseInt(getCookieByName('workPageID')) == iMyPageID_new){
				delCookie('workPageID');
			}
			
			
			if(getCookieByName('pageIDs')){
				arrPageIDs_new = getCookieByName('pageIDs').split(',');
				for(var j = 0; j < arrPageIDs_new.length; j++){
					if(arrPageIDs_new[j] == iMyPageID_new){
						arrPageIDs_new.splice(j, 1);
					}
				}
				setCookie('pageIDs', arrPageIDs_new.join());
			}
		}

		document.onfocus = function(){
			if(parseInt(getCookieByName('workPageID')) != iMyPageID_new){
				setCookie('workPageID', iMyPageID_new);
				myTimerFunc('short');
			}
		}
		window.onfocus = function(){
			if(parseInt(getCookieByName('workPageID')) != iMyPageID_new){
				setCookie('workPageID', iMyPageID_new);
				myTimerFunc('short');
			}
		}
		
		document.onblur = function(){
			if(parseInt(getCookieByName('workPageID')) == iMyPageID_new){
				delCookie('workPageID');
			}
			myTimerFunc('long');
		}
		
	//}catch(e){}
}
checkNow();
//***************************************************
//跨域设置session
function setcrossdomaincookie(sessionid){
	if(sessionid){
		var frm = document.createElement("iframe");
		frm.setAttribute("name", "setcookie");
		frm.setAttribute("width", 0);
		frm.setAttribute("height", 0);
		frm.setAttribute("border", 0);
		frm.setAttribute("src", "http://www.buchaqian.com/mall_crossdomain.php?sid="+sessionid);
		document.body.appendChild(frm);
	}
}
