// JavaScript Document


function singleonlineping(){
//		alert(uid+'|'+username);
	if(uid&&username){
	timerunds=parseInt(new Date().valueOf());
	jQuery.getJSON(serverurl,{"act":"onlineping",'uid':uid,'names':username,'times':timerunds},function(Data){
//alert(Data);
	});
	}
	u=setTimeout("singleonlineping()",10000);
}
singleonlineping();
//username='sunstear';
lasttime=0;
lastmem=0;
showlasttime=new Array();
showlastmem=new Array();
lastsend=0;
talkche=new Array();
waituserlist=new Array();
emurl="http"+"://ww"+"w.oyowow.com/public/biaoqing/";

function singlegetzj(){

	if(uid&&username){
	timerunds=parseInt(new Date().valueOf());
	jQuery.getJSON(serverurl,{"act":"getonline",'type':'zj','times':timerunds},function(Data){
		singleonlinedeal(Data);
	});
	}
	u=setTimeout("singlegetzj()",10000);
}

function singlegetroom(){

}

function getstranger(){
//alert('执行函数');
timerunds=parseInt(new Date().valueOf());
	jQuery.getJSON(serverurl,{"act":"getstranger",'uid':uid,'times':timerunds},function(Data){
//	alert('得到数据');
		if(Data=='kong'){
			alert('当前无其他人');
		}else{
			getstrangerdo(Data);
		}
		
	});
}

function getstrangerdo(theid){
//alert('hello!');
	 addstrengeri(theid);
	 
}

function singlegetonline(){
	if(uid&&username){
	timerunds=parseInt(new Date().valueOf());
	jQuery.getJSON(serverurl,{"act":"getonline",'times':timerunds},function(Data){
//	alert(Data);
		singleonlinedeal(Data);
	});
	}
	u=setTimeout("singlegetonline()",10000);
}
singlegetonline();
thecookieche=new Array();

function singleonlinedeal(dealdata){
	olddata=thecookieche;
	tbadd=arrayUtil.regroupArray(olddata,dealdata);
	tbrem=arrayUtil.regroupArray(dealdata,olddata);
	addonline(tbadd);
	delonline(tbrem);
	thecookieche=dealdata;
}

function delonline(Data){
	jQuery.each(Data, function(i,item){
		var arrs=item.split('@');
		//将记录从好友列表中删除
		friendslist[arrs[0]]=0;
		jQuery("#friend_list_"+arrs[0]).remove();
	});
}

function addonline(Data){
	jQuery.each(Data, function(i,item){
		var arrs=item.split('@');
		//将记录添加到好友列表
		friendslist[arrs[0]]=1;
	list="<li id=friend_list_"+arrs[0]+" title="+arrs[1]+" onclick=talkwin(this)>"+arrs[1]+"</li>";
		jQuery("#friends_team_list").append(list);
		
		jQuery('#'+"friend_list_"+arrs[0]).hover(
		  function () {
			jQuery(this).addClass("bjse2");
		  },
		  function () {
			jQuery(this).removeClass("bjse2");
		  }
		); 
		
	});
}


//刷新得到信息
function getnew(uid){
	if(uid&&username){
	timerunds=parseInt(new Date().valueOf());
	jQuery.getJSON(serverurl,{"act":"getnew",'uid':uid,'times':timerunds},function(Data){
		addtocookie(Data);
//		alert(friendslist['5']);
//		alert(oylist['5']);//偶有列表
	});
	}
u=setTimeout("getnew(uid)",5000);
}
getnew(uid);

//处理缓存数据
function showtowin(){
	jQuery.each(waituserlist,function(i,item){
		if(talkche[item].length>0){
			talkdealwith(item);
		}
	});
}

function talkdealwith(theid){
	if(talkche[theid]){
		if(isonshow(theid)){
			singleaddtowin(theid,'friend');
		}else{
			messageclew(theid);
		}
	}
}
//添加到聊天窗口


function singleaddtowin(theid,thetype){
	jQueryzoonn=jQueryshowwin.css('z-index');
		if(jQueryzoonn<index){
			index++;
			zoonn=index*1;
			showid=jQueryshowwin.attr('id');
			jQueryshowwin.css('z-index',zoonn);
		}
	jQueryshowwimsmall="#"+'friend'+"_window_"+theid;
	showlasttime[theid]=showlasttime[theid]?showlasttime[theid]:0;	
	showlastmem[theid]=showlastmem[theid]?showlastmem[theid]:0;
	jQuery.each(talkche[theid],function(i,item){	
		if(item.timestamp>showlasttime[theid]){
			showlasttime[theid]=item.timestamp;
			showlastmem[theid]=item.ai;
			
				jQuerythetime=stamptotime(item.timestamp);
				jQuerycontent=item.content.replace(/\[face(100|\d{1,2})\]/g,"<img src="+emurl+"R$1.gif>");
			jQuery(jQueryshowwimsmall+" [id=said]").append(item.fromname+':'+jQuerythetime+"<br>");
			jQuery(jQueryshowwimsmall+" [id=said]").append(jQuerycontent+"<br>");
			jQuery("#"+jQueryshowwimsmall+" [id=said]").scrollTop(jQuery("#"+showid+" [id=said]").scrollTop()+32);
		}else if(item.timestamp ==showlasttime[theid]){
			if(item.ai>showlastmem[theid]){
				showlasttime[theid]=item.timestamp;
				showlastmem[theid]=item.ai;
				
					jQuerythetime=stamptotime(item.timestamp);
					jQuerycontent=item.content.replace(/\[face(100|\d{1,2})\]/g,"<img src="+emurl+"R$1.gif>");
					
				jQuery(jQueryshowwimsmall+" [id=said]").append(item.fromname+':'+jQuerythetime+"<br>");
				jQuery(jQueryshowwimsmall+" [id=said]").append(jQuerycontent+"<br>");
				jQuery("#"+jQueryshowwimsmall+" [id=said]").scrollTop(jQuery("#"+showid+" [id=said]").scrollTop()+32);
				}
			}
	});	
	talkche[theid]=Array();
}



//闪烁效果

shan=new Array();
function shanshuo(theid){
	jQueryshanshuodiv=jQuery("#"+'friend'+"_list_"+theid);
	jQueryshanshuodiv.toggleClass('flicker');
	theids='shan'+theid;
	shan[theids]=setTimeout("shanshuo('"+theid+"')",500);
}

newtitle="你有新消息!";
tishilis=new Array();
tishiset=0;
function nts(){
	//判断新消息
	if(tishilis.length>0){
		newmessagetishi();
		clearTimeout(tishiset);
		tishiset=setTimeout("nts()",500);
	}else{
		clearTimeout(tishiset);
		tishiset=0;
		document.title=oldtitle;
		jQuery('#newtishi').hide();
	}
}

function tishi(theid){
	if(arrayUtil.indexOfArray(theid,tishilis)>0){
		}else{
		tishilis.push(theid);
		}
		nts();	
	}


function newmessagetishi(){
		thentitle=document.title;
		if(thentitle==oldtitle){
			document.title=newtitle;
			}else{
			document.title=oldtitle;
		}
		jQuery('#tsphoto').show();
		jQuery('#newtishi').toggle();
	}

function clearshanshuo(theid){
	theind=arrayUtil.indexOfArray(theid,tishilis);
	tishilis.splice(theind-1,1);
	jQueryshanshuodiv=jQuery("#"+'friend'+"_list_"+theid);
	jQueryshanshuodiv.removeClass('flicker');
	theid='shan'+theid;
	jQuery('#tsphoto').hide();
	jQuery('#newtishi').hide();
	clearTimeout(shan[theid]);
	shan[theid]=0;
}


function isonlist(theid){
	if(friendslist[theid]||oylist[theid]){
		return true;
	}else{
		return false;
	}
}
//消息提示
function messageclew(theid){
	if(isonlist(theid)){
		shantheid='shan'+theid;
		if(shan[shantheid]){			
			}else{
//				alert(theid+'asdf');
				tishi(theid);
				shanshuo(theid);
				PlaySound('消息1');
			}
	//		alert('有新信息');
	}else{
		addstrengerp(theid);
	}
}

function addstrengerp(theid){
		list="<li id=friend_list_"+theid+" title="+theid+" onclick=talkwin(this)>"+'陌生人'+"</li>";
		jQuery("#ouyu_team_list").append(list);
		jQuery('#'+"friend_list_"+theid).hover(
		  function () {
			jQuery(this).addClass("bjse2");
		  },
		  function () {
			jQuery(this).removeClass("bjse2");
		  }
		); 
		oylist[theid]=1;
}

function addstrengeri(theid){
//alert(theid);
if(oylist[theid]){
//alert('得到用户已存在');
}else{
	arrs=theid[0].split('@');
	list="<li id=friend_list_"+arrs[0]+" title="+arrs[1]+" onclick=talkwin(this)>"+'陌生人'+"</li>";
	jQuery("#ouyu_team_list").append(list);
	obj=jQuery('#'+"friend_list_"+arrs[0]);
	jQuery('#'+"friend_list_"+arrs[0]).hover(
		  function () {
			jQuery(this).addClass("bjse2");
		  },
		  function () {
			jQuery(this).removeClass("bjse2");
		  }
		); 
	oylist[theid]=1;
	talkwin(obj);
	}
}

//发送新信息
function mssend(){
	timerunds=parseInt(new Date().valueOf());
	toids=showid.split('_');
	toid=toids[2];
	cont=jQuery("#"+showid+" [id=write] [id=textfield]").val();
	jQuery.get(serverurl,{"act":"send","uid":uid,"username":username,'cont':cont,"touid":toid,'times':timerunds},function(Data){
	jQuery("#"+showid+" [id=write] [id=textfield]").val("");
					jQuerythetime=stamptotime(timerunds/1000);
					jQuerycontent=cont.replace(/\[face(100|\d{1,2})\]/g,"<img src="+emurl+"R$1.gif>");
					jQuery("#"+showid+" [id=said]").append('<span class=meshow>我'+':'+jQuerythetime+"<br></span>");
					jQuery("#"+showid+" [id=said]").append('<span class=meshow>'+jQuerycontent+"<br></span>");
					jQuery("#"+showid+" [id=said]").scrollTop(jQuery("#"+showid+" [id=said]").scrollTop()+96);
	});
}


//时间函数，吧时间戳转换成时间
function stamptotime(thestamp)
{
    var d, s;
    d = new Date(thestamp*1000);
	s='';
    s += ("0"+d.getHours()).slice(-2) + ":";
    s += ("0"+d.getMinutes()).slice(-2) + ":";
	s += ("0"+d.getSeconds()).slice(-2);
    return s;
}

function addtocookiesec(theitem){
	var thecookiechekey='talkwith'+theitem.fromid;
	if(jQuery.cookie(talkwith[thecookiechekey])){
		thecookieche=jQuery.cookie(talkwith[thecookiechekey]);
	}else{
		thecookieche=new Array;
	}
	thecookieche.push(theitem);
	jQuery.cookie(talkwith[thecookiechekey],thecookieche);
	alert(jQuery.cookie(talkwith[thecookiechekey]));
}

function addtojs(theitem){
if(in_array(theitem.fromid,waituserlist)){
}else{
	waituserlist.push(theitem.fromid);
};
	var jsthekey=theitem.fromid;
	if(talkche[jsthekey]){
		talkche[jsthekey].push(theitem);
	}else{
		talkche[jsthekey]=new Array();
		talkche[jsthekey].push(theitem);
	}
//	alert(talkche[jsthekey]);
}

function addtocookie(Data){

	jQuery.each(Data, function(i,item){
//	alert(item.timestamp);
	if(item.timestamp>lasttime){
		lasttime=item.timestamp;
		lastmem=item.ai;
		addtojs(item);
//		addtocookiesec(item);
		//jQuery("#recode").append(item.content+item.timestamp+"<br>");
	}else if(item.timestamp ==lasttime){
		if(item.ai>lastmem){
			lasttime=item.timestamp;
			lastmem=item.ai;
			addtojs(item);
//			addtocookiesec(item);
			//jQuery("#recode").append(item.content+item.timestamp+"<br>"); 
			}
		}
	});
	showtowin();
}

/*
function newmessagered(jQueryreadwin){
	
}
*/

//in_array方法 包含返回true,没有返回false
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 onlineping(){//刷新人员变动
	jQuery.get("http://192.168.0.207/oyoim/server/oyoim.php?",{'key':'ping','uid':fromid},function(Data){});//pingzaixian
//	jQuery.getJSON("http://localhost/oyoim/server/oyoim.php?",{'key':'getonline','uid':'1'},function(jsonData){
//		alert(jsonData.num);
//        jQuery("#getJSONResponse").html(jsonData.num);});
var myDate = new Date();
myday=myDate.getTime();
	jQuery.getJSON("http://192.168.0.207/oyoim/server/oyoim.php?time="+myday,{'key':'count','to':fromid},function(jsonData){
	//	alert(jsonData.num);
		newmessid=jsonData;
		if(jsonData){
        jQuery("#getmessage").html("你有"+jsonData.length+"条信息");}});
	u=setTimeout("onlineping()",5000);
}
*/
function facebut(){
	jQueryshowid=jQuery("#"+showid);//当前窗口
	var top=jQueryshowid.offset().top; var left=jQueryshowid.offset().left;
	//alert(top+"|"+left);
	jQuery("#biaoqings").css('left',left+10)
					.css('top',top+40)
					.css('z-index',index+1)
					.show();
}

function hideim(){
	jQuery("#oyoim").hide();
	jQuery("#oyoimtinybar").show();
}

function shoim(){
	jQuery("#oyoimtinybar").hide();
	jQuery("#oyoim").show();
}
function closethis(){
	types=showid.split('_');
	theid=types[2];
	jQueryshowid=jQuery("#"+showid);
	jQueryshowid.remove();
	showwinlist[theid]=0;
}
var n=0;
oldtitle=document.title;//初始化变量
newmessage='';

jQuery(document).ready(function(){
//jQuery("title").html("hello world!");
	//初始化
//	newmessageaction();
//	onlineping();
	jQuery("#oyoimtinybar").hide();
	hideim();
	jQuery("#oyoimMyAvatar").bind('click',function(){
		hideim();
	});
	
	//插入表情
	jQuery("#biaoqings > .emItem").bind('click',function(){
		jQueryshowid=jQuery("#"+showid);//当前窗口
		//alert(jQuery(this).attr('name'));
/*
		alert(jQuery("#"+showid+" [id=write] [id=textfield]").text());
		alert(jQuery("#"+showid+" [id=write] [id=textfield]").val());
*/
		if(jQuery(this).attr('name')>0){
		jQuery("#"+showid+" [id=write] [id=textfield]").val(jQuery("#"+showid+" [id=write] [id=textfield]").val()+"[face"+jQuery(this).attr('name')+"]");
		}
		jQuery("#biaoqings").hide();
	});
	
	//列表下拉弹出效果	
	jQuery("#oyoimteams li > div").toggle(function(){
		jQuery( '#' + jQuery(this).attr('id') + '_list').hide();},function(){ jQuery('#' + jQuery(this).attr('id') + '_list').show();
	});
});

	//弹出窗口效果
function talkwin(thediv){
//		alert(jQuery(thediv).attr('id'));
		thisid=jQuery(thediv).attr('id');
		thename=jQuery(thediv).attr('title')
		lens=thisid.split('_');
		chattype=lens[0];
		idnum=lens[2];
		idname=chattype+"_window_"+idnum;
		jQueryshowwin=jQuery("#"+chattype+"_window_"+idnum);
		if(jQueryshowwin.length ==1){
					jQueryzoonn=jQueryshowwin.css('z-index');
				if(jQueryzoonn<index){
					index++;
					zoonn=index*1;
					showid=jQueryshowwin.attr('id');
					jQueryshowwin.css('z-index',zoonn);
				}
		}else{
		jQuery("#lefttop").append("<div id='"+idname+"' class='box'></div>");
		index++;
		zoonn=index*1;
		showid=idname;
		jQueryshowwin=jQuery("#"+chattype+"_window_"+idnum);		
		jQueryshowwin.css('z-index',zoonn);		
		jQueryshowwin.append(jQuery("#chatwindow").html());
		jQuery("#"+chattype+"_window_"+idnum+" [class=chattitle] [class=handle bar]").text('与'+thename+'聊天中');
		jQueryshowwin.bind('dragstart',function( event ){
				return jQuery(event.target).is('.handle');
				})
			.bind('drag',function( event ){
				jQuery( this ).css({
					top: event.offsetY,
					left: event.offsetX
					});
				})
			.bind('mousedown',function(){
				jQueryzoonn=jQuery(this).css('z-index');
				if(jQueryzoonn<index){
					index++;
					zoonn=index*1;
					showid=jQuery(this).attr('id');
					jQuery(this).css('z-index',zoonn);
				}
			});
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = jQueryshowwin.height();
	var popupWidth = jQueryshowwin.width();
	//centering
	jQueryshowwin.css({
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});			
		}
//		uidname="#"+chattype+"_window_"+idnum;
	clearshanshuo(idnum);
	showwinlist[idnum]=1;	//添加到窗口显示列表
		//回车提交
	jQuery("#"+showid+" [id=write] [id=textfield]").keydown(function(event){ 
   if(event.keyCode==13){
//	   alert("hello!");
       mssend();
   } 
 }); 
}

function isonshow(theid){
	if(showwinlist[theid]){
		return true;
	}else{
		return false;
	}
}

function arrayUtil(){};
	arrayUtil.copyArray = function(arr)
	{
		var temp = [];
		for(var i in arr)
		{
		   temp[i] = arr[i];
		}
		return temp;
	}
	
	arrayUtil.indexOfArray = function(value,arr)
	{
		if(!(typeof(value) == "string" || typeof(value) == "number")) return false;
		
		for(var i in arr)
		{
		   if(arr[i] == value) return true;
		}
		return false;
	}
	
	arrayUtil.regroupArray = function(removeArr,firstArr)
	{
		var temp = [];
		for(var i in firstArr)
		{
		   temp[i] = firstArr[i];
		}
		
		for(var i in removeArr)
		{
		   for(var j in temp)
		   {
			if(removeArr[i] == temp[j])
			{
			 temp.splice(j,1);//删除第j项
			}
		   }
		}
		return temp;
	}
	
	arrayUtil.mergeArray = function(addArr,firstArr)
	{
		var temp = [];
		for(var i in firstArr)
		{
		   temp[i] = firstArr[i];
		}
		
		for(var i in addArr)
		{
		   var flag = true;
		  
		   for(var j in temp)
		   {
			if(addArr[i] == temp[j])
			{
			 flag = false;
			 break;
			}
		   }
		   if(flag)
			temp.push(addArr[i]);
		}
		return temp;
	}
