﻿//Global variables
var timeID;
var refreshRate = 2000; // two seconds
var rnd = Math.random();

var isFirefox;
var isIE;

var IsStart = true;
var IsBreak = false;
var Online = true;
//$$DomainSet
var cookiesDomain = null;//".lookingon.com";


var RelativeAddress = "";
if( window.location.href.indexOf("localhost") > -1)   //为测试做的补丁
    RelativeAddress = "/Schoolmate" + RelativeAddress ;
//else
//    RelativeAddress = "http://mate" + cookiesDomain + RelativeAddress ;
var ServerPage = RelativeAddress + "/Chat/Server.aspx";

    
var IsClock = false;
var ClockTime = 1000;
var Clock;

// Get browser type
function sniffBrowserType() {
	isFirefox = ( navigator.appName == "Netscape" );
	isIE = (navigator.appName == "Microsoft Internet Explorer" ); 
}

sniffBrowserType();//检测浏览器

function forbidSpeak()
{
	window.clearTimeout( Clock );
    IsClock = true;
    Clock = window.setTimeout( "allowSpeak()", ClockTime );
}

function allowSpeak()
{
    IsClock = false;
}

function getAjax()
{
	var XmlHttp;
	try
	{
		XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttp = null;
		}
	}
	//Creating object of XMLHTTP in Mozilla and Safari 
	if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttp = new XMLHttpRequest();
	}
	return XmlHttp;

}




// Start the update timer
function setTimers()
{
    if(!IsBreak)
	    timeID = window.setTimeout( "updateAll()", refreshRate );
}

// Start to update and reset the update timer
function updateAll()
{
    if(timeID)
	    window.clearTimeout( timeID );
	getMessage();
	setTimers();
}

function ShowTopMessage(_Message)
{
    var obj = getElement("TopMessageBox");
    if(obj!=null)
    {
        obj.style.display = 'block';
        var t = getElement("TopMessage");
        t.innerHTML = _Message;
        SetSize();
    }
}
function CloseTopMessage()
{
    var obj = getElement("TopMessageBox");
    if(obj!=null)
    {
        obj.style.display = 'none';
        SetSize();
    }
}

function getMessage()
{
    rnd++;
	url = ServerPage + '?action=GetMsg&uid='+getElement("UID").value+'&nick='+encodeURIComponent(getElement("UNick").value)+'&Online=' + Online + '&rnd=' + rnd;
	req = getAjax();
	req.onreadystatechange = function(){
	
		if( req.readyState == 4 ) {
		    if( req.status == 200) {
			    obj = getElement( "chatbuffer" );
			    var msg = req.responseText;
			    if(IsStart)
                {
                    hiddenLoadScreen();
                    IsStart = false;
                }
			    if(msg != null && msg !='')
			    {
			        var t = getResultValue(msg,"Command");
			        switch (t)
			        {
			            case "Break":
			            {
			                if(timeID)
			                    window.clearTimeout(timeID);
			                IsBreak=true;
			                break;
			            }
			            case "Close":
			            {
			                cmdClose(msg);
			                break;
			            }
			            case "Eval":
			            { 
			                eval(getResultValue(msg,"Parameters"));
			            }
			        }
		            setMessage(msg);
		            Html_InputBox.focus();
			    }
			    //FocusWindow();
			}
			else
			{
				if(IsStart)
                {
                    //window.location = url;
                    //alert(req.status);
			        if(timeID)
			           window.clearTimeout(timeID);
			        IsBreak = true;
			        ShowLodingTimeout();
			    }
			}
		}
	}
	if(IsStart)
    {
    //alert(url);
        var t = req;
        window.setTimeout(function(){t.abort();}, 10000 );
    }
    
	req.open( 'GET', url , true );
	req.send( null );
}


function getResultValue(_Response,_Name)
{
     if(_Name!=null && typeof(_Name)=="string" && _Name.length > 0 &&_Response!=null && typeof(_Response)=="string" && _Response.length > 8 +_Name.length)
     if(_Response.indexOf("<!--" +_Name+ ":") != -1)
     {
        var startIndex = _Response.indexOf("<!--" +_Name+ ":") + 5 +_Name.length;
	    return _Response.substring(startIndex,_Response.indexOf("-->",startIndex));
    }
    return "";
}

function cmdClose(msg)
{
   var message = msg.substring(msg.indexOf("-->") +3);
   if(message.length>0)
   {
        alert(message);
   }
   window.close(self);
}
function postText()
{
    Html_InputBox.focus();

	OutputText('mytext');
	rnd++;
	chatbox = getElement( "mytext" );
	chat = chatbox.value;
	var now=new Date();
    var year=now.getYear();
    var month=now.getMonth();
    var day=now.getDate();
    var hours=now.getHours();
    var minutes=now.getMinutes();
    var seconds=now.getSeconds();
    var strTime =year+"-"+(month +1)+"-"+day+" "+hours+":"+minutes+":"+seconds+"";

	if(IsClock)
	{
	    setMessage("<div class='SystemMessage'><span class='Title'>系统消息：</span><span class='Content'>您发送消息太快，请稍候再试。</span><span class='Time'>(" +strTime+")</span></div>");
	    return;
	}
	if(chat=='' || chat == null)
	{
	    setMessage("<div class='SystemMessage'><span class='Title'>系统消息：</span><span class='Content'>不能发送空信息。</span><span class='Time'>(" +strTime+")</span></div>");
	    forbidSpeak();
	    return;
	}

	url = ServerPage + '?action=PostMsg&uid='+getElement("UID").value+'&unick='+encodeURIComponent(getElement("UNick").value)+'&Online=' + Online + '&Message=' + encodeURIComponent(chat) + '&rnd=' + rnd;
	req = getAjax();
	//Html_InputBox.document.body.innerHTML = url;
	req.onreadystatechange = function(){

		if( req.readyState == 4 && req.status == 200 ) {
		    var result = req.responseText;
		     var t = getResultValue(result,"Command");
			    switch (t)
			    {
			        case "Break":
			        {
			            if(timeID)
			                window.clearTimeout(timeID);
			            IsBreak=true;
			            break;
			        }
			        case "Close":
			        {
			            cmdClose(result);
			            break;
			        }
			        case "Eval":
			        {
			            eval(getResultValue(result,"Parameters"));
			        }
			    }
		    if(getResultValue(result,"Result") == 'true')
		    {
		        setMessage("<div class='Send'><span class='UName'>"+getElement("SenderUser").value+"：</span><span class='Time'>(" +strTime+")</span><span class='Message'>" +chat+"</span></div>");
    			forbidSpeak();
		    }
		    else
		    {
			    setMessage(result);
			}
            chatbox.value = "";
            Html_InputBox.document.body.innerHTML = "";

			//updateAll();
		}
//		else
//		{
//		    obj.innerHTML += "<div class='failed'>发送消息失败！请重试</div>";
//		}
	
	}
	
	req.open( 'GET', url, true );
	req.send( null );
}

function setMessage(Message)
{
    if(Message != null)
    {
//    if(Message == "truetruetrue" || Message == "true")
//        alert(Message);
	var obj = getElement( "chatbuffer" );
	obj.innerHTML += Message;
	scrollChatPane();
	}
}
function getElement( id ) 
{
	if( isIE ) {
		return document.all[ id ];
	}
	else {
		return document.getElementById( id );
	}
}



function showLoadScreen()
{
    var chat = getElement("Loading");
    Loading_content.style.display = "none";
    chat.style.display = "";
    Loading_content.style.marginTop = (getMessageBoxHeight() - Loading_content.style.height)/2;
    Loading_content.style.display = "";
    IniLodingMessage();
}

function hiddenLoadScreen()
{
    var t = getElement("Loading");
    t.style.display = "none";
    Loading_content.style.display = "none";
			    //setFocus('Text1');
    Html_InputBox.focus();
}

function scrollChatPane()
{
	var obj = getElement("chatbuffer");
	obj.scrollTop = obj.scrollHeight;
}
function setFocus(ControlName)
{
	var control = getElement(ControlName);
	if( control != null )
	{
		control.focus();
	}
}


function CheckInceptDialogs()
{
    rnd++;
	url = ServerPage + '?action=GetInceptDialogs&rnd=' + rnd;
	req = getAjax();
	req.onreadystatechange = function(){
		if( req.readyState == 4 && req.status == 200 ) {
			var result =req.responseText;
			//alert(result);
            result = getResultValue(result,"Result")
			if(result!='')
			{
			    var i = result.split(">");
			    var t = i[0];
			    for(var j = 1;j<i.length;j++)
			    {
			         OpenDialog(t,i[j],"true");
			         j++;
			    
//			        var dialogID = t +"_" + i[j];
//			        var dialogID2 = i[j] +"_" + t;

//			        if(getCookie(dialogID) == "opened" || getCookie(dialogID2) == "opened")
//                    {
//                        j++;
//                    }
//                    else
//                    {
//                        msg = new Message();
//                        msg.Type= 0;
//                        msg.Uid = i[j];
//                        msg.UName = unescape(i[++j]);
//                        qm.Push(msg);
//                    }
			        
			    }
			}
		}

	}
	req.open( 'GET', url , true );
	req.send( null );
}

function focusWindow(windowName,js)
{
    if(windowName)
    {
        var o = document.createElement("a");
        o.setAttribute("target",windowName);
        o.setAttribute("href","javascript:window.focus();" + (js?js:''));
        o.setAttribute("style","display:none");
        document.body.appendChild(o);
        o.click();
    }
}

function hiddenDialog(InceptUID)
{
	rnd++;
	url = ServerPage + '?action=HiddenDialog&InceptUID=' + InceptUID + '&rnd=' + rnd;
	req = getAjax();
	req.onreadystatechange = function(){

		if( req.readyState == 4 && req.status == 200 ) {
		    var result = req.responseText;
		    if(getResultValue(result,"Result") == 'True')
		    {
		        alert("隐藏提示成功，下次登录会重新提示。");
		    }
		    else{	}
		}
	}
	req.open( 'GET', url, true );
	req.send( null );
}
function OpenDialog(t,f,Incept)
{
    //alert("open");
    var dialogID = t +"_" + f;
    var dialogID2= f +"_" + t;
    if(Incept != "true")
    {
        Incept = "false";
    }
    if((getCookie(dialogID)) != "opened" && (getCookie(dialogID2) != "opened"))
    {
    	setCookie(dialogID,"opened",null,"/",cookiesDomain);
        window.open(RelativeAddress + "/Chat/?Incept=" + Incept+"&InceptID="+f,dialogID,"height=450, width=460, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no")

    }
    else
    {
        var js = "if(document.getElementById('Loading')==null){window.resizeTo(460,450);window.moveTo(0,0);window.location='"+RelativeAddress + "/Chat/?Incept=" + Incept+"&InceptID="+f+"';}";
        if(getCookie(dialogID) == "opened")
        {
            focusWindow(dialogID,js);
        }
        else if(getCookie(dialogID2) == "opened")
        {
            focusWindow(dialogID2,js);
        }
        else
        {
            setCookie(dialogID,"opened",null,"/",cookiesDomain);
            window.open(RelativeAddress + "/Chat/?Incept=" + Incept+"&InceptID="+f,dialogID,"height=450, width=460, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no")
        }
    }
}
function OpenDialog2(t,f)
{
  var dialogID = t +"_" + f;
  var dialogID2= f +"_" + t;
  if((getCookie(dialogID)) != "opened" && (getCookie(dialogID2) != "opened"))
    {
    	setCookie(dialogID,"opened",null,"/",cookiesDomain);
        window.open(RelativeAddress + "/Chat/?Incept=true&InceptID="+f,dialogID,"height=450, width=460, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no")

    }
}

//热键发送
var PostKey=1; //发送消息的热键  1：ENTER 2：CTRL+ENTER


function keypress(evt){
	evt = evt ? evt : (window.event ? window.event : null); 
  if (PostKey==1){
		if (!evt.shiftKey&&evt.keyCode==13){
		    postText();
			return false;
		}
		return true;
	}
	if (PostKey==2){
		if (evt.ctrlKey&&evt.keyCode==10){
		    postText();
		}
	}
}
function keydown(evt){
  if (evt.altKey) {
    if (evt.keyCode==83)
    {
        postText();
    }
  }

}

function textCounter(obj,maxlength){
	if (obj.value.length>maxlength){
		obj.value=obj.value.substr(0,maxlength);
	}
}