// -------------------------------------------------------------
// Chat.js 28.08.2006
// -------------------------------------------------------------
// Tested with : Firefox / IE / Opera / Safari



//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
function getHTTPObject(serr) {
  var xmlhttp;
  
  if (window.XMLHttpRequest) 
    {
    xmlhttp = new XMLHttpRequest();
    }
  else if (window.ActiveXObject) 
    {
    try{
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
        {
        ShowMessage("Falls Sie den Internet Explorer 6 benutzten bitte prüfen Sie ob ActiveX-Controls aktiviert sind sonst ist kein Chat möglich","");            
        }
    }
  else
    {
    if (serr)
        ShowMessage("Ihr Browser unterstütz kein XMLHTTP Object. Falls Sie den Internet Explorer 6 benutzten bitte prüfen Sie ob ActiveX-Controls aktiviert sind","");    
    }  
  return xmlhttp;
}


var httpRChat;
var httpSChat;
var httpIChat;

var postrevicecomplete = true;

var ignoreduser = new Array();
var onlineusers = new Array();

function chatReceiveOnlineList()
{
    
	if (httpIChat.readyState == 4)
		{
		try{
		onlineusers = new Array();
		onlineusers = httpIChat.responseText.split("\n");
		
		chatUpdateUsersList();
		} catch (e){}
		//chatDebugTrace(httpIChat.responseText);
		//xtimeout = 
		if (!chatFinished)
		    setTimeout('chatRefreshOnlineList();',3000); //executes the next data query in 20 seconds
		}
    

}

function chatUpdateUsersList()
{
	var s1="";s2="";
	
	if (document.getElementById("question")!=null)
	{
	    var m = onlineusers[2];
	    var x = m.split("\t");
	    msg = x[1];
	    userID = x[0];
	    if (userID!=chatUserID && userID!=0 && !IsModerator)
	        {
	        EnableChatUI(false);
	        document.getElementById("status").innerHTML = "<small><i>Hinweis: Derzeit wird die obige Frage beantwortet; erst anschliessend können weitere Fragen gestellt werden. Bitte haben Sie etwas Geduld.</i></small>";
	        }
	    else
	        {
	        if (!chatFinished)
    	        EnableChatUI(true);
	        if (userID==chatUserID)
	            document.getElementById("status").innerHTML = "<i>Hinweis: <b>Ihre Frage wird nun beantwortet. Sie können ggf. weitere Nachfragen stellen.</b></i>";
	        else
	            document.getElementById("status").innerHTML = "";
	        }
    	
	    if (msg==undefined || msg=="")    
	        {
	        document.getElementById("question").innerHTML ="";
	        document.getElementById("question").style.display = "none";
	        }
	    else
	        {	        
            document.getElementById("question").innerHTML = (IsModerator ? " <img src='images/ende.gif' align='middle' title='Frage ist fertig beantwortet' style='margin-top:-7px;cursor:hand;cursor:pointer' onclick='DoAnswerFinsh()' >":"") + "<strong>Aktuelle Frage: </strong>" + msg;	    
            document.getElementById("question").style.display = "";
            }
    }    
    if (document.getElementById("chatonlineusers")!=null)
        {
	    for (i=3;i<onlineusers.length-1;i++)
		    {
		    x = onlineusers[i].split("\t");
		    if (chatIsIgnored(x[0]))
			    s2=s2+chatGetUserLink(onlineusers[i],true);			
		    else
			    s1=s1+chatGetUserLink(onlineusers[i],false);			
		    }
	    document.getElementById("chatonlineusers").innerHTML = "<li>" + s1 + "</li>";
	    document.getElementById("chatignoreonlineusers").innerHTML = "<li>" + s2 + "</li>";
	}

}

function chatIgnore(userID,add)
{
    if (IsModerator)
        {
        if (chatIsIgnored(userID))
            {
            action = "ENABLE";
            info = "Der User darf dann im Chat WIEDER schreiben";
            }
         else
            {
            action = "DISABLE";
            info = "Der User darf dann im Chat nichts mehr schreiben";
            }
            
	    if (confirm("Sind Sie sicher ? " + info))
		    {
		    url = chatURL + '?action='+action+'&blockuserID='+userID+'&userID='+chatUserID+'&PHPSESSID=' + sessionID + '&chatID=' + chatID + '&lastID=' + lastEntryID + '&rand='+Math.floor(Math.random() * 1000000);
		    if (AJAX)
			    {
	  		    httpSChat.open("GET",url, true);
			    httpSChat.onreadystatechange = ReceiveChat; 
  			    httpSChat.send(null);	
  			    }
  		    else
  			    {  			          			
			    iFRAME.src=url + "&type=noajax";      			
  			    }
  		    }
  		else return;
        }
    if (!chatIsIgnored(userID))
	    {
	    ignoreduser.push(userID);
	    }
    else
	    {
	    for (i=0;i<ignoreduser.length;i++)
		    {
		    for (e=i;e<ignoreduser.length-1;e++)
			    ignoreduser[e]=ignoreduser[e+1];
			
		    ignoreduser.pop();
		    i=1000;
		    }
	    }
	chatUpdateUsersList();

}

function chatIsIgnored(userID)
{
	for (ai=0;ai<ignoreduser.length;ai++)
		{
		if (ignoreduser[ai]==userID)
			return true;
		}
	return false;

}

function chatGetUserLink(user,ignore)
{

	u = user.split("\t");
	
	switch (u[2])
		{
		case "H":
			s = "<img border='0' alt='Das Symbol für Mann' src='images/male.gif'>";		
			break;
		case "F":
			s = "<img border='0' alt='Das Symbol für Frau' src='images/female.gif'>";
			break;
		default:
			s = "<img align='absmiddle' alt='' border='0' src='images/icon-" + u[2] + ".gif'>";				
			break;
		}
		
	a="";
	if (u.length==4)
		{		
		switch (u[3])
			{
			// chatting, something new to read
			case "A":			
				a+="<img align='absmiddle' src='images/icon-chat-add.gif' alt='Neuer Eintrag im Chat' border='0'>";			
				HasChat = true;
				break;
			// chatting, new chat
			case "N":
				a+="<img align='absmiddle' src='images/icon-chat-new.gif' alt='Neuer Chat' border='0'>";
				HasChat = true;
				break;
			// ?
			case "O":
				a+="<img align='absmiddle' src='images/icon-chat-new.gif' alt='Neuer Chat' border='0'>";				
				if (played[u[0]]!=true)
					{
					a+="<embed type=\"audio/wav\" src='sounds/dingdong.wav' style='width:0px;height:0px;' autoplay='true'></embed>";			
					//a+="<object type='audio/wav' name='dingdong' width='0' height='0' classid='CLSID:05589FA1-C356-11CE-BF01-00AA0055595A'> <param name='filename' value='sounds/dingdong.wav'></object>";
					played[u[0]] = true;
					}				
				else
					{					
					}
				HasChat = true;
				break;
			// chatting, nothing new to read
			case "C":
				a+="<img align='absmiddle' src='images/icon-chat.gif' alt='Chat' border='0'>";
				HasChat = true;
				break
            // not chatting				
			default:				
				break;
			}
		}
		
	
	if (chatUserID!="0")
		{
		if (chatUrlUser!="")
		    {
		    try{
		        add=add;
		        } catch (e){ add="";		    }
		    s+=" <a href='#' onclick=\"w=window.open('" + chatUrlUser + "&PHPSESSID=" + sessionID + "&ID=" + u[0] + "&amp;" + add + "','user_" + u[0] + "','width=" + chatPopupUserWidth + ",height=" + chatPopupUserHeight + ",scrollbars=yes,status=yes');w.focus();\">" + u[1] + "</a> ";
		    if (u[0]!=chatUserID)
		        {
		        if (document.getElementById("chatignoreonlineusers")!=null)
			        s+="<a href='#' style=\"border:0\" onclick=\"chatIgnore(" + u[0] + "," + (ignore ? "'true'":"'false'") + ");\"><img align=\"middle\" border=\"0\" alt=\"" + (!ignore ? "Mitglied ignorieren":"Mitglied nicht mehr ignorieren") + "\" src=\"images/remove.gif\" /></a>";
			    
			    if (IsModerator)
			        s+="<span style=\"cursor:hand;cursor:pointer;\" title=\"Klick fügt name@ in textzeile ein\" onclick=\"chatAddUsername('" + u[1] + "');\"><b>@</b></span>";
			    }
		    }
        else
            {
		    s+=" " + u[1] + " ";
		    if (u[0]!=chatUserID)
			    s+=" <a href='#' style=\"border:0\" onclick=\"chatIgnore(" + u[0] + "," + (ignore ? "'true'":"'false'") + ");\"><img align=\"middle\" border=\"0\" alt=\"" + (!ignore ? "Mitglied ignorieren":"Mitglied nicht mehr ignorieren") + "\" src=\"images/remove.gif\" /></a>";
            
            }
		}
	else
		s+=" " + u[1] + " ";
	
		
	return s+a+"<br>";

}

function chatRefreshOnlineList()
{
	timeout = null;
	url = chatURL + '?action=USERLIST&PHPSESSID=' + sessionID + '&chatID=' + chatID + '&rand='+Math.floor(Math.random() * 1000000);
	chatDebugTrace("Userlist: chatID:" + chatID + " lastID:" + lastEntryID + " readystate:" + httpIChat.readyState);
	
	if (AJAX)
		{
		if ((httpIChat.readyState == 4 || httpIChat.readyState == 0))
			{
  			httpIChat.open("GET",url, true);
			httpIChat.onreadystatechange = chatReceiveOnlineList; 
  			httpIChat.send(null);
			}	
		else
			{
			timeout = setTimeout('chatRefreshOnlineList();',chatUpdateSpeed); //executes the next data query in 4 seconds
			}
		}
	else
		{
		if (!chatFinished)
			{
			iFRAME.src = url + "&type=noajax";
			timeout = setTimeout('RefreshChat();',chatUpdateSpeed);
			}
		}

}

function MessageKeyDown(e)
{

	if (!e)
		e = window.event;

	if (e.keyCode)
		if (e.keyCode==13)
		    {
			SendChat();		
			return false;
			}
			
}
function chatAddUsername(name)
{
    document.getElementById('chatmessage').value += ("@"+name+":");
    try{
    document.getElementById('chatmessage').focus();
    var oRange = document.getElementById('chatmessage').createTextRange();
    oRange.moveStart("character", name.length+2);
    oRange.select();

    } catch(e){}
}

function DoAnswerFinsh()
{
	param = 'action=ANSWERFINISHED&PHPSESSID=' + sessionID + '&lastID=' + lastEntryID + '&userID=' + chatUserID + '&chatID=' + chatID;
	httpSChat.open("GET", chatURL + "?" + param, true);
	httpSChat.onreadystatechange = ReceiveChat;
	// opera does not work with setREquestheader
	//if (httpSChat.setRequestHeader) httpSChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	httpSChat.send(null);

}
function DoAnswer(mID,userID)
{
	param = 'action=ANSWER&PHPSESSID=' + sessionID + '&ID=' + mID + '&lastID=' + lastEntryID + '&userID=' + chatUserID + '&chatID=' + chatID;
	httpSChat.open("GET", chatURL + "?" + param, true);
	httpSChat.onreadystatechange = ReceiveChat;
	// opera does not work with setREquestheader
	//if (httpSChat.setRequestHeader) httpSChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	httpSChat.send(null);

}

function SendChat() 
	{	
	strChatText = document.getElementById('chatmessage').value;
	EnableChatUI(false);
	if (!AJAX)
		{
	    document.forms["chatform"].submit();
	    }
	else
		{
		//alert(strChatText);
		if (strChatText != '')
			{

			if ((httpSChat.readyState == 4 || httpSChat.readyState == 0))
				{
	  			document.getElementById('chatmessage').value='';
	  			
	  			postrevicecomplete = false;
				
				param = 'action=POST&PHPSESSID=' + sessionID + '&lastID=' + lastEntryID + '&userID=' + chatUserID + '&chatID=' + chatID + '&message='+ escape(strChatText);
				httpSChat.open("GET", chatURL + "?" + param, true);
	  			httpSChat.onreadystatechange = ReceiveChat;
				// opera does not work with setREquestheader
				//if (httpSChat.setRequestHeader) httpSChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	  			httpSChat.send(null);
				}
			else
				{
				setTimeout('SendChat();',1000);
				}
			}
		else
			{
			EnableChatUI(true);			
			}
		}
		
	 // supress onsubmit 
	}

function ShowMessage(message,timestamp)
{

	insertO = document.getElementById("chatlist");
	oLi = document.createElement('li');
    

	add = "";
	if (timestamp!="")
		{
		x = timestamp.split(' ');
		add = x[1] + " ";
		}

	oLi.setAttribute('className','systemmessage'); //for IE's sake
	oLi.setAttribute('class','systemmessage');

	oText = document.createTextNode(add + "Systemnachricht: " + message);
	
	oLi.appendChild(oText);
	
	//alert(oLi.innerHTML);
	
	
	insertO.insertBefore(oLi, insertO.firstChild);
	
	if (document.getElementById("question")!=null)
	    oLi = document.getElementById("question");
	if (oLi.scrollIntoView)
		oLi.scrollIntoView(true);

}
function ShowChatEntry(ID,userID,timestamp,username,message)
{
	if (!chatIsIgnored(userID))
		{
		// Euro Zeichen
		message = message.replace("%u20AC","€");

		insertO = document.getElementById("chatlist");
		oLi = document.createElement('li');
		if (userID==moderatorID)
		    {
		    oLi.setAttribute('className','moderator'); //for IE's sake
		    oLi.setAttribute('class','moderator');		    
		    //icon = "<img src=\"images/icon-1.gif\" />";
		    }
		else if (userID==chatUserID)
			{			
			oLi.setAttribute('className','self'); //for IE's sake
			oLi.setAttribute('class','self');			
			}
		
		oSpan = document.createElement('span');
        if (IsModerator && userID!=chatUserID)
            {
            oImg = document.createElement('IMG');
            oImg.src = "images/okay.gif";
            oImg.title="Diese Frage beantworten";
            oImg.align="middle";
            oImg.style.cursor="hand";
            oImg.style.marginTop=-6;
            oImg.setAttribute("eid",ID);
            oImg.setAttribute("userid",userID);
            oImg.onclick=function(){DoAnswer(this.getAttribute("eid"),this.getAttribute("userid"));}
            oSpan.appendChild(oImg);    
            }
		
	    oSpan.setAttribute('className','name'); //for IE's sake
	    oSpan.setAttribute('class','name');

		
		x = timestamp.split(' ');
		
		oName = document.createTextNode(x[1] + " " + username+' : ');	
		oText = document.createTextNode(message);
		
		oSpan.appendChild(oName);



		//if (icon!="")
		    //oSpan.innerHTML = x[1] + " " + icon + username+' : ' + message;
		oLi.appendChild(oSpan);


		oLi.appendChild(oText);

	    sh = oLi.innerHTML;
	    //alert(sh + " " +sh.indexOf("http://"));
	    //if (IsModerator)
	        {
	        if (sh.indexOf("http://")>-1)
	            {
	            ii = sh.indexOf("http://");
	            ee = sh.substr(ii,sh.length).indexOf(" ");
	            if (ee==-1) ee = sh.length;
	            url = sh.substr(ii,ee)
	            url = url.replace("PHPSESSID","");
	            //alert (sh.substr(i,sh.length).indexOf(" ") + "|" + url + " " + i + " "+ e);
	            oLi.innerHTML = sh.substr(0,ii) + "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>" + sh.substr(ii+ee,sh.length);
	            }
            }
		insertO.insertBefore(oLi, insertO.firstChild);
		}	
//	if (oLi.scrollIntoView)
//		oLi.scrollIntoView();

}



function chatParse(text,typ)
{
	var lines = null;
	var repeat = true;
	
	lines = text.split("||");
	if (lines!=null)	
		{
		for (e=0;e<lines.length;e++)
			{
			if (!chatFinished)
				{
				results = lines[e].split('\t'); //the fields are seperated by ---
			
				if (results.length > 0) 
					{
					if (results[0]!="")
						{
						// --- chat closed
						if (results[0]=="finished")
							{
							//alert(results[1]);
							ShowMessage(results[1],results[2]);
							
							chatFinished = true;
							EnableChatUI(false);
							repeat=false;
							
							}
						else
							{						

							if (parseInt(results[0])>parseInt(lastEntryID) || parseInt(results[0])==-1)
								{
								if (results[1]=="system")
									ShowMessage(results[4],results[2]);
								else
    								ShowChatEntry(results[0],results[1],results[2],results[3],results[4]); //inserts the new content into the page
								
								if (parseInt(results[0])!=-1)
								    lastEntryID = results[0];

								if (results[5]=="1" && results[1]!=chatUserID)
								    PlayNotify();
								
								
								if (!AJAX)
									document.getElementById("lastID").value=lastEntryID;
								
								}
							}

						}
					}
				}
			}
		}

	return repeat;
}

function EnableChatUI(b)
	{
		document.getElementById("chatmessage").disabled=!b;
		document.getElementById("chatsend").disabled=!b;
		
		//alert( document.getElementById("chatmessage"));
		if (b) document.getElementById("chatmessage").focus();

	try
		{
		if (b) document.getElementById("chatmessage").setActive();
		}
	catch (e)
		{
		}
		
		if (document.getElementById("chatnotify")!=null)
			{
			document.getElementById("chatnotify").disabled=!b;
			document.getElementById("chatclose").disabled=!b;	
			}
		
	}

function ReceiveChat() 
	{
	var repeat = true;
	var text = null;
	
	if ((httpRChat.readyState == 4) || (httpSChat.readyState == 4 && !postrevicecomplete))
		{
			//chatDebugTrace("Received: chatID:" + chatID + " typ:" + httpSChat.readyState + " " + httpRChat.readyState + " " + httpRChat.responseText);
		if (httpRChat.readyState == 4 && httpRChat.responseText!="")
			{
			text = httpRChat.responseText;
			typ = "recieve ";
			}
		if (!postrevicecomplete && httpSChat.readyState == 4 && httpSChat.responseText!="" && text==null)
			{			
			EnableChatUI(true);
			text = httpSChat.responseText;
			typ = "send ";
			postrevicecomplete = true;
			}
		
		if (text!=null)
		    {
			chatDebugTrace("Received: chatID:" + chatID + " typ:" + typ + " text:" + text);

			repeat = chatParse(text,typ);		
			}
		
		if (repeat && !chatFinished && timeout==null)		
			timeout = setTimeout('RefreshChat();',chatUpdateSpeed); //executes the next data query in 4 seconds
		}
	}

function RefreshChat()
	{
	timeout = null;
	url = chatURL + '?action=GET&PHPSESSID=' + sessionID + '&chatID=' + chatID + '&lastID=' + lastEntryID + '&rand='+Math.floor(Math.random() * 1000000);
	
	//chatDebugTrace("Refresh: chatID:" + chatID + " lastID:" + lastEntryID + " readystate:" + httpRChat.readyState);
	
	if (AJAX)
		{
		if (httpRChat.readyState == 4 || httpRChat.readyState == 0)
			{
  			httpRChat.open("GET",url, true);
			httpRChat.onreadystatechange = ReceiveChat; 
  			httpRChat.send(null);
			}	
		else
			{
			timeout = setTimeout('RefreshChat();',chatUpdateSpeed); //executes the next data query in 4 seconds
			}
		}
	else
		{
		if (!chatFinished)
			{
			iFRAME.src = url + "&type=noajax";
			timeout = setTimeout('RefreshChat();',chatUpdateSpeed);
			}
		}
	}


var AJAX=true,iFrameDoc,iFRAME,chatID,chatURL,chatUserID,lastEntryID=0,updatespeed=1000,sessionID,chatFinished=false,timeout,chatPrivate=true;
var chatUrlUser,chatPopupUserWidth="",chatPopupUserHeight="";
var IsModerator=false,moderatorID=0,answeruserID=0;

function InitChat(url,cID,uID,updatespeed,phpsessionID,SupportAJAX,bchatPrivate,urlUser,popupwidth,popupheight)
{
    httpRChat = getHTTPObject(true);
    httpSChat = getHTTPObject(false);
    httpIChat = getHTTPObject(false);


	chatID			= cID;
	chatURL			= url;
	chatUserID		= uID;
	chatUpdateSpeed = updatespeed;
	sessionID		= phpsessionID;
	
	chatPrivate         = bchatPrivate;
	chatUrlUser         = urlUser;
	
    chatPopupUserWidth  = popupwidth;
    chatPopupUserHeight = popupheight;

	if (!httpRChat) return;//SupportAJAX = false;

	AJAX			= SupportAJAX;

    chatDebugTrace("InitChat chatID:" + cID + " Ajax:" + SupportAJAX);

	if (uID!="0")
		document.getElementById('chatmessage').onkeydown = MessageKeyDown;
    
	if (SupportAJAX==false)
		InitChatNoAJAX();

	RefreshChat();
	
	//alert(chatPrivate);
	
	if (chatPrivate==false) chatRefreshOnlineList();
	
}

function InitChatNoAJAX()
{
    try
    {
    //var iframe = document.getElementById("COMM");
    iFRAME = document.getElementById("chathelper");
  //alert("iframe " + iFRAME);

	if (document.frames) {
        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the IFrame if we access it through
        // the document.frames array
	    //iFRAME = document.frames["chathelper"];
		}

 	if (iFRAME.contentDocument) {
	    // For NS6
    	iFrameDoc = iFRAME.contentDocument;
	  } else if (iFRAME.contentWindow) {
	    // For IE5.5 and IE6
    	iFrameDoc = iFRAME.contentWindow.document;
	  } else if (iFRAME.document) {
	    // For IE5
    	iFrameDoc = iFRAME.document;
	  } else
	  {

	  }
//alert(iFrameDoc);
	RefreshChat();
	} catch(e) {}
}

function ChatNotify()
{
	document.getElementById("chatnotify").disabled=true;
	t=setTimeout("ChatEnableNotify();",4000);

	url = chatURL + '?action=NOTIFY&userID=' + chatUserID + '&PHPSESSID=' + sessionID + '&chatID=' + chatID + '&lastID=' + lastEntryID + '&rand='+Math.floor(Math.random() * 1000000);
	if (AJAX)
		{
  		httpSChat.open("GET",url, true);
		httpSChat.onreadystatechange = ReceiveChat;
		httpSChat.send(null);
		}
	else
		{
		//alert(url + "&type=noajax");
		//iFrameDoc.location.href=url + "&type=noajax";
		iFRAME.src=url + "&type=noajax";
		}

}

function ChatEnableNotify()
{
	document.getElementById("chatnotify").disabled=false;
}


function ChatClose()
{

	
	if (confirm("Sind Sie sicher ?"))
		{
		url = chatURL + '?action=CLOSE&PHPSESSID=' + sessionID + '&chatID=' + chatID + '&lastID=' + lastEntryID + '&rand='+Math.floor(Math.random() * 1000000);
		if (AJAX)
			{
	  		httpSChat.open("GET",url, true);
			httpSChat.onreadystatechange = ReceiveChat; 
  			httpSChat.send(null);	
  			}
  		else
  			{
  			chatFinished = true;
  			
			iFRAME.src=url + "&type=noajax";
  			
  			}
  		}
}

function chatDebugTrace(text)
{
	oDebugArea = document.getElementById("chatdebug");
	now = Date();

	try{
	if (oDebugArea!=null)
	    {
		oDebugArea.value = now.toString() + " " + text + "\r\n" + oDebugArea.value;
		}
		}catch (e) {}
}

function chatWriteSoundControl(strHTML,ID)
{
    var elem = document.getElementById(ID);    
    elem.innerHTML = strHTML;
}

