// AJAX LIVE CHAT
// 2008 (c) Ashus www.ashus.ashus.net


// ovladane objekty
window.chat_header = document.getElementById("chat_header");
window.chat_topic = document.getElementById("chat_topic");
window.chat_content = document.getElementById("chat_content");
window.chat_present = document.getElementById("chat_present");
window.chat_input = document.getElementById("chat_input");
window.chat_input_smileys = document.getElementById("chat_input_smileys");
window.chat_name = document.getElementById("chat_name");
window.chat_text = document.getElementById("chat_text");
window.chat_submit = document.getElementById("chat_submit");
window.chat_admin = document.getElementById("chat_input_tbl_admin");
window.chat_manage = document.getElementById("chat_input_tbl_manage");
window.chat_manage_selpost = document.getElementById("chat_input_tbl_manage_selpost");
window.chat_post_info = document.getElementById("post_info_cont");





// Provide the XMLHttpRequest class for IE 5.x-6.x:
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "Your browser does not support AJAX!" )
};

function Ajax_init()
	{
	this.loadAjax = function (myurl,str,method,mydiv)
		{
		if ((mydiv == "chat") && (window.content_updating))
			{
            window.content_updating = false;
			return;
			}
			
		this.mydiv =mydiv;
		this.xmlHttp = new XMLHttpRequest();
		if (this.xmlHttp==null)
			{
			alert ("Your browser does not support AJAX!");
			return;
			}
		var url=myurl;
		var mmethod=method;
		if ((str != "") && (mmethod == 'GET'))
			{
			url=url+"?"+str;
			str=null;
			}

		if (mydiv == "chat")
			{
			str = str.replace("chat_last_loaded", window.chat_last_loaded);
			str = str.replace("chat_last_present", window.chat_last_present);
            window.content_updating = true;
			}

		this.xmlHttp.onreadystatechange = function() { iIncomingData(this, mydiv); };
		this.xmlHttp.open(mmethod,url,true);
		this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.xmlHttp.send(str);
		}
	}


iIncomingData = function (xmlHttp, mydiv)
	{
	if (xmlHttp.readyState == null)
		{
		// IE6 FIX
		eval('xmlHttp = window.ajax_'+mydiv+'.xmlHttp;');
		}

	if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
        //debug zkoumani ajax odpovedi
// 		alert(mydiv+"\n\n"+xmlHttp.responseText.substring(0,400)+"\n\n...\n\n"+xmlHttp.responseText.substring(xmlHttp.responseText.lastIndexOf("class=",xmlHttp.responseText.length-400)));

		// odpovida instance pouzita pro prijem obsahu chatu, userlistu a prikazu
	    if (mydiv == "chat")
	        {
		    var recv = xmlHttp.responseText;

		    recv = recv.split("\n");
			var cnt = recv.length;
			var newpost = false;

			for (i=0;i<cnt;i++)
				{
				recv[i] = trim(recv[i]);
				if ((recv[i] != '') && (recv[i] != '1'))
				    {
				    
				    // prichazi posty
					if (recv[i].substring(0, prefix_chat_post_L) == prefix_chat_post)
					    {
                        if (( (window.max_items_pageratio == 0) && (window.cclines >= window.max_items_count) )
							|| ( (window.max_items_pageratio != 0) && (window.chat_content.scrollHeight > (window.chat_content.offsetHeight * window.max_items_pageratio)) ))
                            {
                            // odmazat prvni radek a pridat na konec nove prichozi
                            DeleteOldestAndAddNewPost(recv[i]);
							
							} else {
							// pridat novy radek
                            AddNewPost(recv[i]);
							}

						if (newpost)
							{
                            // povolime zvuky pro pristi zpravu kdyz jsme sami poslali a nahodou nekdo v tu chvili taky
							window.content_loaded = true;
							} else
							{newpost = true;}

                        MoveContentToBottom();
						}
					
					// prichazi novy seznam pritomnych
					else if (recv[i].substring(0, prefix_chat_present_L) == prefix_chat_present)
						{
						recv[i] = recv[i].substring(prefix_chat_present_L);
						window.chat_present.innerHTML = recv[i];
						
						window.present_loaded = true;
						
						// priradime udalosti znovu obrazkum / aby thickbox fungoval :D
                        $('a.thickbox').unbind();
						tb_init('a.thickbox');

						if (window.ie6)
							{$("img").pngfix();}
						}
					
					// prichazi nove crc stazeneho seznamu pritomnych
					else if (recv[i].substring(0, prefix_chat_lastpresent_L) == prefix_chat_lastpresent)
						{
						recv[i] = recv[i].substring(prefix_chat_lastpresent_L);
						window.chat_last_present = recv[i];
						}
						
					// prichazi novy topic
					else if (recv[i].substring(0, prefix_chat_topic_L) == prefix_chat_topic)
						{
						recv[i] = recv[i].substring(prefix_chat_topic_L);
						if (recv[i] != '')
							{recv[i] = recv[i] + " -&nbsp;"}

						window.chat_topic.innerHTML = recv[i];
						}
						
					// prichazi zvukovy tag
					else if (recv[i].substring(0, prefix_chat_sound_L) == prefix_chat_sound)
						{
						recv[i] = recv[i].substring(prefix_chat_sound_L);
						if ((recv[i]=="msg" && window.content_loaded)
							|| (recv[i]=="usr" && window.present_loaded))
							{
							PlaySound(recv[i]);
							}
						}

					// prichazi cistici tag
					else if (recv[i].substring(0, prefix_chat_clean_L) == prefix_chat_clean)
						{
						window.chat_content.innerHTML = "";
						window.cclines = 0;
						window.content_loaded = false;
						}
						
					// prichazi tag s oznacenim posledniho odeslaneho ID postu
					else if (recv[i].substring(0, prefix_chat_lastloaded_L) == prefix_chat_lastloaded)
						{
						window.chat_last_loaded = parseInt(recv[i].substring(prefix_chat_lastloaded_L));
						}

					}
				}

			// vlozili jsme minimalne jeden post
			if (newpost)
				{
				// priradime udalosti znovu obrazkum / aby thickbox fungoval :D
                $('a.thickbox').unbind();
				tb_init('a.thickbox');

				// povolime zvuky pro pristi zpravu
				window.content_loaded = true;
				
                // posuneme se uplne dolu na posledni prispevek
				setTimeout("MoveContentToBottom()",500);
				}

            window.content_updating = false;
            
			}
			
			// odpovida instance pouzita pro odesilani postu
			else if (mydiv == "chat_send")
			{
			var o = parseInt(xmlHttp.responseText);
			if (o == 1)
			    {
                window.chat_text.value = "";
                
                // vypneme zvuk vlastni odchozi zpravy
                if (! window.sound_own)
					{window.content_loaded = false;}
                
				// vyjimecne spustime nacteni zmen, at necekame na zobrazeni vlastniho postu ani vterinu
				// pouze za predpokladu, ze update uz nebezi / at nemame duplicity
				if ((! window.content_updating) && (! window.ie6))
				    {
					var ajax_chat_ex = new Ajax_init();
	                ajax_chat_ex.loadAjax("chat.get.php", "rep=1&last=chat_last_loaded&present=chat_last_present", "POST", "chat");
					}
				} else
				
			if (o == 2)
			    {
                DisplayBanInfo();
				}
				
			SetChatInputEnabled(true);

			}
			
			// odpovida instance pouzita pro info o postech a upravu postu
			else if (mydiv == "chat_manage")
			{
            if (xmlHttp.responseText.substring(0, prefix_info_L) == prefix_info)
				{
				// popup okno s infem
				var ofs = xmlHttp.responseText.indexOf("\n");
				var tle = xmlHttp.responseText.substr(prefix_info_L,(ofs-prefix_info_L));
				window.chat_post_info.innerHTML = "<br />" + xmlHttp.responseText.substr(ofs);
				tb_show(tle, "#TB_inline?height=350&width=440&inlineId=post_info_cont", null);
				} else

			if (parseInt(xmlHttp.responseText) == 1)
			    {
				// vyjimecne spustime nacteni zmen krome userlistu
				var ajax_chat_ex = new Ajax_init();
                ajax_chat_ex.loadAjax("chat.get.php", "rep=0&usr=0", "POST", "chat");
				}
				
			HideMarkPost();

			}
		}
	}

function initAndRunAjax(url, vars, method, id, timeout, vars_firsttime)
	{

	eval('window.ajax_'+id+' = new Ajax_init();');

	var fnc = 'ajax_'+id+'.loadAjax("'+url+'", "'+vars+'", "'+method+'", "'+id+'")';

	if (vars_firsttime != "")
	    {eval('ajax_'+id+'.loadAjax("'+url+'", "'+vars_firsttime+'", "'+method+'", "'+id+'")');} else
	    {eval(fnc);}

	if (timeout > 0)
		{setInterval(fnc, timeout*1000);}
	}



function initAjaxChat()
	{
	initAndRunAjax("chat.get.php", "rep=1&last=chat_last_loaded&present=chat_last_present", "POST", "chat", 5, "rep=0");
	}


function DisplayBanInfo()
	{
    alert("Je nám líto, ale Vaše IP adresa je u nás zabanovaná.\nPokud se chcete zúčastnit chatu, požádejte správce o registraci.");
	}


function DeleteOldestAndAddNewPost(newp)
	{
    var cc = window.chat_content.innerHTML.split("\n");
    var ccnew = "";
	for (o=1;o<window.cclines;o++)
	    {
        ccnew = ccnew + cc[o] + "\n";
		}
		
	if (newp != null)
		{
		ccnew = ccnew + newp;
		} else {
		ccnew = ccnew.substr(0,ccnew.length-1);  // mazeme posledni newline
        window.cclines--;
		}
		
	window.chat_content.innerHTML = ccnew;
	}


function AddNewPost(newp)
	{
	if (window.cclines == 0)
	    {
    	window.chat_content.innerHTML = newp;
		} else {
	    window.chat_content.innerHTML = window.chat_content.innerHTML + "\n" + newp;
		}
	window.cclines++;
	}


// ostatni pomocne funkce

function submitText()
	{
	if (! window.chat_text_enabled)
		{return false;}

	var str = chat_text.value;
	str = Utf8.encode(str);
	if (str != "")
		{
		SetChatInputEnabled(false);
	 	initAndRunAjax("chat.send.php", "text="+encodeURIComponent(Utf8.decode(str)), "POST", "chat_send", 0, "");
		}
	return false;
	}


function EditPost(act)
	{
	if ((act != 'del') && (act != 'csr') && (act != 'ban') && (act != 'nfo'))
	    return;
	    
	var cnt = window.selected_posts.length;
	if (cnt > 0)
	    {
	    
		if ( (act=="nfo") || (confirm("Opravdu chcete "+((act=="del")?"smazat":((act=="csr")?"cenzurovat":" *BANOVAT* "))+" "+((cnt>1)?"vybrané příspěvky":"vybraný příspěvek")+"?")) )
		    {
			//akce
	 		window.chat_manage_selpost.style.color = "#444444";
			initAndRunAjax("chat.edit.php", "act="+act+"&id="+encodeURIComponent(window.chat_manage_selpost.innerHTML), "POST", "chat_manage", 0, "");
			}
		} else {

		alert("Před "+((act=="del")?"mazáním":((act=="csr")?"cenzurováním":((act=="ban")?"banováním":"zjištěním informací")))+" příspěvků je nutné je nejdříve vybrat.\n\nKlikněte s podržením kláves Shift nebo Ctrl na přezdívku autora u daného příspěvku a poté opakujte akci.");
		}
		
	return false;
	}



function MarkPost(author, id, oEvent)
	{
	if ((! oEvent.shiftKey) && (! oEvent.ctrlKey))
	    {AddSmiley(author);} else
		{

		// pokud v poli je, smaze se, jinak se tam prida
	    if (! DeleteFromSelected(id))
	        {
	        window.selected_posts[window.selected_posts.length] = id;
			}

		var lst = window.selected_posts.join(",");

		if (lst != "")
			{
			window.chat_manage_selpost.innerHTML = lst;
			window.chat_manage_selpost.style.display = "inline";
			} else {
			HideMarkPost();
			}

		}

	}


function HideMarkPost()
	{
	window.selected_posts = new Array();
	window.chat_manage_selpost.innerHTML = "";
	window.chat_manage_selpost.style.display = "none";
	window.chat_manage_selpost.style.color = "";
	}


function DeleteFromSelected(what)
	{
	var ar = new Array();
	var c = 0;
	var b = false;
	for (var i=0; i<window.selected_posts.length; i++)
		{
		if (what == window.selected_posts[i])
		  	{
	        b = true;
		  	} else {
			ar[c] = window.selected_posts[i];
			c++;
			}
		}
	window.selected_posts = ar;
	return b;
	}


function AddSmiley(y)
	{
	if (! window.chat_text_enabled)
		{return false;}

	var val = window.chat_text.value;

	if ((val.length>0) && (val.substr(val.length-1) != ' '))
	    {val = val + " ";}
	val = val + y + " ";
	
	window.chat_text.value = val;
	window.chat_text.focus();
	}

function SwitchSmileys()
	{
	var elem = document.getElementById("smileys_"+window.smileys_selected);
	if (elem != null)
		{elem.style.display = "none";}
    
    window.smileys_selected++;
    
	var elem = document.getElementById("smileys_"+window.smileys_selected);
	if (elem != null)
		{elem.style.display = "block";}
		else
		{
		window.smileys_selected = 0;
		SwitchSmileys();
		}

	return false;
	}


function PlaySound(mp)
	{
	if ((mp=="msg") || (mp=="usr"))
		{
		if (window.soundsnp[mp] != "")
			{
			var np = niftyplayer("niftyPlayer_"+mp);
			if (np != null)
				{np.play();}
			}
		}
	}

function SetSound(mp, val)
	{
	if ((mp=="msg") || (mp=="usr"))
		{
		window.soundsnp[mp] = val;
		if (val != "")
			{
			var np = niftyplayer("niftyPlayer_"+mp);
			if (np != null)
				{np.load("sounds/"+val+".mp3");}
			}
		}
	}
	
function SetChatInputEnabled(val)
	{
	window.chat_text_enabled = val;
	var fcol = ((val)?"":"#555555");
    window.chat_text.style.color = fcol;
    window.chat_submit.style.color = fcol;
    if (val)
        window.chat_text.focus();
	}


function MoveContentToBottom()
	{
    window.chat_content.scrollTop = window.chat_content.scrollHeight;
	}


function FixWindowResize()
	{
	window.chat_input.style.width = (window.chat_present.offsetLeft + window.chat_present.offsetWidth - 20) + "px";
	window.chat_text.style.width = (window.chat_input.offsetWidth - window.chat_submit.offsetWidth - 37) + "px";
	window.chat_present.style.height = (window.chat_input.offsetTop - window.chat_header.offsetHeight - 15) + "px";
	window.chat_content.style.width = (window.chat_present.offsetLeft - 13) + "px";
	
	window.chat_content.style.height = window.chat_present.style.height;
	}


$(document).ready(function()
	{
	// az bude nacteno, misto onload
	
	if (window.ie6)
		{
		window.chat_input.style.bottom = "-20px";    // bo tam neni ocekavany scrollbar
		$("img").pngfix();
		}

	FixWindowResize();
	initAjaxChat();
	window.chat_text.focus();
	});

