
var _reload  = 3000; // update 
var _reload_inactive = 35000;    
var _timer   = null;
var _path    = "/global_data/tutorenchat/";
var _last_id = null;
var _active  = false;
var _last_message = "";
var _last_message_timestamp = 0;

/**
* Funktion parst die JSON-Rückgabe der Dateien
**/
function parse_return( ret ) {
	var count = ret.msg.length;
	var content_to_add = "";
	
	for(i=0;i<count;i++) {
		this_msg = ret.msg[i];
		if(this_msg.id > _last_id) {
			content_to_add += "<span style=\"cursor: pointer;font-weight:bold;\" "+
		        "onclick=\"return mclick('" + this_msg.sender + "');\" " +
		        "onmouseover=\"mover();\" " +
		        "onmouseout=\"mout();\">" +
		        "[" + this_msg.date + "]&nbsp;<span style=\"color:"+this_msg.color+"\">" + this_msg.sender +":</span></span> "+
				this_msg.message+"<br />";
		}
	}
	// Höchste ID als letzte empfangene ID speichern:
 	_last_id = ret.msg[0].id;
 	
 	$("#output").html( content_to_add+$("#output").html() );
 	content_to_add = "";
}

function check() {
	$.get(_path + "data/lastid?"+Math.random()*10000, function( ret ) {
		if(parseInt(ret) > _last_id)
		  get_data();

		set_timer(); 
	});
}

function get_data() {
	$.getJSON(_path + "data/msg?"+Math.random()*1000000, function(json) {
		parse_return( json );
	});
}

function set_timer() {
	clearTimeout( _timer );
	_timer = window.setTimeout("check()", _active ? _reload : _reload_inactive);
}

function send() {
	var a = document.cookie;
	var regex = /primus_user:session\_code=([a-f0-9]+);/;	
	regex.exec(a);
	
	if($("#inputtext").val()!="") {
		var now = new Date();
           	_last_message = $("#inputtext").val();
		_last_message_timestamp = now.getTime(); // update
		
		$.getJSON(_path + "add.php", {message: encodeURIComponent($("#inputtext").val()), s: RegExp.$1}, function(json) {
		  	if(json=="spam") 
		  	alert("Bitte achte darauf, nur maximal 4 Smilies zu verwenden!"); 
		  	else if(json=="banned") 
		  	alert("Du wurdest temporaer gesperrt. Bitte wende Dich an einen Mod oder Admin"); 
		  	else { $("input#inputtext").val("");
		  	  parse_return(json);
		  	  _active = true;
		  	  set_timer();
		  	  
		  	}
		});
	}
}   

function checkInput(e)
{
    if(!e) {
        e = window.event;
    }
    if(e.which) {
        taste = e.which;
    } else if(e.keyCode) {
        taste = e.keyCode;
    }
    if(taste == 13)
      send();
}
  
function open_smiliewindow() {
	var smw = window.open("/global_data/shoutbox/smilies.php", "Smilies", "width=400,height=500,location=no,toolbar=no,status=no");
}
  
// Initialisieren:
$(document).ready( function() { 
	get_data();set_timer(); 
} );
