var getErrorNum = 0;

var lastMsgId = 0;

var connectLink = '<input class="butlink" value="重新连接" onclick="Connect();" onfocus="this.blur()" style="width:60px;">';

var downloadLink = '<input class="butlink" value="下载聊天记录" onclick="$(\'#logTxt\').val($(\'#msg\').html());$(\'form:downLoad\').submit();" onfocus="this.blur()" style="width:83px;">';

var siteTitle = document.title;

function flushTitle()
{
	
	setTimeout("document.title = '◇◆'+siteTitle+'◆◇'", 300);
	
	setTimeout("document.title = '◆◇'+siteTitle+'◇◆'", 600);

	setTimeout("document.title = '◇◆'+siteTitle+'◆◇'", 900);
	
	setTimeout("document.title = '◆◇'+siteTitle+'◇◆'", 1200);

	setTimeout("document.title = siteTitle",1500);
}

function JSAddFavorite()
{
	if ( window.sidebar && "object" == typeof( window.sidebar ) && "function" == typeof( window.sidebar.addPanel ) )
	{
		window.sidebar.addPanel( document.title, document.location.href, '' );
	}
	else if ( document.all && "object" == typeof( window.external ) )
	{
		window.external.addFavorite( document.location.href, document.title );
	}
	else
	{
		alert('请使用快捷键 Ctrl+D 将本站添加至收藏夹');
	}
}

function CookieEnable()
{
	var result=false;
	
	if(navigator.cookiesEnabled)
		return true;
	
	document.cookie = "testCookie=Yes;";
	
	var cookieSet = document.cookie;
	
	if (cookieSet.indexOf("testCookie=Yes") > -1)
		result=true;
	
	document.cookie = "";
	
	return result;
}

function startChat()
{
	$("#chat").show();
	
	$("#start").hide("slow");
	
	//$("#msg").bind("mousewheel",function(){return false;});
	
	$("#uid").attr('value','0');

	$("#content").attr('disabled',true);
	
	$("#submit").attr('disabled',true);
	
	Connect();
}

function Connect()
{
	if( $("#uid").attr("value") == 0 && $("#control").attr("disabled") == false )
	{
		$("#control").attr("disabled",true);

		$("#control").attr("value","正在连接");

		$("#msg").empty();

		updateMsg("正在帮您连接到当前路过的某人，请稍候...<a href=http://www.lanrenji.com target=_blank>快来参加商品团购~超级便宜哦~</a>");

		$.ajax
		(
			{
				type:"POST",
				url:"./connect.php",
				data:"rdm="+Math.random(),
				dataType:"json",
				timeout:12000,
				success:function(uId)
				{
					if( uId[0] >= 1 )
					{
						$("#uid").attr("value",uId[0]);

						setTimeout("getChat()",999);
					}
					else
					{
						Disconnect2();

						if( $("#uid").attr('value') > 0 )
							updateMsg("<b>连接出现异常！请"+connectLink+"。</b>");
					}
				},
				error:function(XMLHttpRequest,textStatus)
				{
					Disconnect2();

					updateMsg('<b>异常掉线！您的网络环境有点糟糕。请'+connectLink+'。</b>');
				}
			}
		);
	}
}

function Connect2()
{
	$("#control").unbind("click");

	$("#control").attr("value","断开连接");

	$("#control").bind("click",function(){Disconnect(true)});

	$("#control").attr("disabled",false);

	$("#content").attr('disabled',false);

	$("#content").attr('value','');

	$("#submit").attr('disabled',false);

	flushTitle();

	updateMsg('<b style="color:red;">已经帮您连接到某人了，先问个好吧 ^^</b> <form id="downLoad" name="downLoad" method="post" target="_blank" action="./download.php" style="display:none;"> <input type="hidden" name="logTxt" id="logTxt" value=""> </form>');
}

function Disconnect(confirmation)
{
	if( $("#uid").attr("value") > 0 && $("#control").attr("disabled") == false )
	{
		if( confirmation )
		{
			var truthBeTold = window.confirm("您确定要断开和这位陌生人的连接吗？");

			if ( !truthBeTold )
			{
				return false;
			}
		}

		$.ajax({type:"POST",url:"./disconnect.php",data:"rdm="+Math.random()});

		$("#control").attr("disabled",true);

		$("#control").attr("value","正在断开");

		Disconnect2();
		
		updateMsg("<strong>您已经终止了和现在这位陌生人的聊天，您可以"+connectLink+"到另一位陌生人。</strong>"+downloadLink);
	}
}

function Disconnect2()
{
	$("#uid").attr('value','0');

	$("#control").attr("disabled",false);

	$("#control").unbind("click");

	$("#control").attr("value","重新连接");

	$("#control").bind("click",function(){Connect()});

	$("#content").attr('disabled',true);

	$("#content").attr('value','');

	$("#submit").attr('disabled',true);
}

function getLocation()
{
	if( $("#uid").attr("value") > 0 )
	{
		$.ajax
		(
			{
				type:"POST",
				url:"./location.php",
				data:"",
				dataType:"json",
				timeout:2500,
				success:function(data)
				{
					if( data )
					{
						if( $("#uid").attr("value") > 0 )
						{
							updateMsg('<font style="color:#CC0066;"><b>系统消息：某人由</b>『'+data+'』<b>路过。</b></font>');
						}
					}
				}
			}
		);
	}
}

function getChat()
{
	if( $("#control").attr('value') == "正在连接" )
	{
		$.ajax
		(
			{
				type:"POST",
				url:"./find.php",
				data:"rdm="+Math.random(),
				dataType:"json",
				cache:false,
				timeout:9000,
				success:function(msg)
				{
					if( msg[0] == "1" )
					{
						Connect2();

						getLocation();

						getMsg(0);
					}
					else if( msg[0] == "-1" )
					{
						if( $("#uid").attr('value') > 0 )
							updateMsg('<b>您被系统T出了！</b>需要'+connectLink+'吗？');

						Disconnect2();
					}
					else if( msg[0] == "0" )
					{
						setTimeout("getChat()",1500);
					}

					getErrorNum = 0;
				},
				error:function(XMLHttpRequest,textStatus)
				{
					getErrorNum++;

					if( getErrorNum >= 2 )
					{
						Disconnect2();

						updateMsg('<b>由于网络连接异常导致您掉线了，需要'+connectLink+'吗？</b>');

						getErrorNum = 0;
					}
					else
					{
						getChat();
					}
				}
			}
		);
	}
}

function quickMsg(e)
{
	var a;

	if( window.event )
	{
		a = e.keyCode;
	}
	else if( e.which )
	{
		a = e.which;
	}
	
	if( a == 13 )
	{
		return sendMsg();
	}
}

function updateMsg(msg)
{
	if( msg.length > 0 )
	{
		if( $("#msg").html() != "" )
		{
			msg = "<br>" + msg;
		}

		$("#msg").append(msg);
	
		$("#msg")[0].scrollTop=$("#msg")[0].scrollHeight;
	}
}

function sendMsg()
{
	var msg = $.trim($("#content").attr("value"));

	if( $("#uid").attr("value") > 0 && msg.length >= 1 )
	{
		$("#content").attr('disabled',true);

		$("#submit").attr('value','正在发送');

		$("#submit").attr('disabled',true);

		$.ajax
		(
			{
				type:"POST",
				url:"./send.php",
				data:"msg="+encodeURIComponent(msg),
				dataType: "json",
				timeout:6000,
				success:function(data)
				{
					if( $("#uid").attr("value") > 0 )
					{
						$("#content").attr('disabled',false);

						$("#submit").attr('disabled',false);

						$("#submit").attr('value','发送消息');

						if( data[0] >= 1 )
						{
							$("#content").attr("value",'');

							updateMsg('<font style="color:blue;"><b>你自已：</b>'+data[1]+'</font>');
						}
						else
						{
							if( data[1] == 0 )
								updateMsg("<b><font style='color:green;'>系统消息：</font>服务器繁忙！</b>");

							if( data[1] == 1 )
								updateMsg("<b><font style='color:green;'>系统消息：</font>每条消息请控制在 1 至 90 个字之间.</b>");
							
							if( data[1] == 2 )
								updateMsg("<b><font style='color:green;'>系统消息：</font>您的语速太快了，歇会儿吧。</b>");
						}

						$("#content").focus();
					}
				},
				error:function(XMLHttpRequest,textStatus)
				{
					if( $("#uid").attr("value") > 0 )
					{
						$("#content").attr('disabled',false);

						$("#submit").attr('disabled',false);

						$("#submit").attr('value','发送消息');

						updateMsg("<b><font style='color:green;'>系统消息：</font>消息发送超时，请重试！</b>");

						$("#content").focus();
					}
				}
			}
		);
	}
}

function getMsg(id)
{
	if( $("#uid").attr("value") > 0 )
	{
		$.ajax({
				type:"POST",
				url:"./msg.php",
				data:"id="+id,
				dataType:"json",
				cache:false,
				timeout:8000,
				success:function(msg)
				{
					if( $("#uid").attr("value") > 0 )
					{
						if( msg[0] == "-1" )
						{
							Disconnect2();

							updateMsg('<font color=green>您被系统T出了！</font>需要'+connectLink+'吗？');
						}
						else if( msg[0] == "0" )
						{
							Disconnect2();
							
							updateMsg('<font color=green>对方已断开与您的连接。</font>您可以'+connectLink+'一个人。'+downloadLink);
						}
						else
						{
							if( msg[1].length > 0 )
							{
								flushTitle();

								for(var i=0;i<msg[1].length;i++)
								{
									updateMsg('<font style="color:red;"><b>陌生人：</b>'+msg[1][i]+'</font>');
								}
							}

							setTimeout("getMsg("+msg[2]+")",2222);

							lastMsgId = msg[2];
						}
					}

					getErrorNum = 0;
				},
				error:function(XMLHttpRequest,textStatus)
				{
					getErrorNum++;

					if( getErrorNum >= 3 )
					{
						Disconnect2();

						updateMsg('<font style="color:red">由于网络连接异常导致您掉线了，需要'+connectLink+'吗？'+downloadLink+"</font>");

						getErrorNum = 0;
					}
					else
					{
						getMsg(lastMsgId);
					}
				}
			});
	}
}

function getStat()
{
	$.ajax
	(
		{
			type:"POST",
			url:"./stat.php",
			data:"rdm="+Math.random(),
			dataType: "json",
			success:function(m)
			{
				//$("#N_0").text(m[0]);
				//$("#N_1").text(m[1]);
				$("#N_2").text(m[2]);
			}
		}
	);
	
	setTimeout("getStat();",60000);
}

$(document).ready(function()
							{
								if( !CookieEnable() )
								{
									$("#enter").click(function(){alert('您的浏览器必须启用Cookie才能继续访问本站！')});
								}
								else
								{
									imgLoader = new Image();

									imgLoader.src = "../images/start_2.jpg";
									
									$("#enter").mouseover(function(){this.className='enter2';});

									$("#enter").mouseout(function(){this.className='enter';});
								
									$("#enter").click(function(){startChat()});
								
									getStat();
								}
							}
					);

$(window).unload( function () { Disconnect(false); } );

window.onbeforeunload = function (){if ($("#uid").attr("value") > 0){return '★★★离开本页将结束本次会话★★★';}};