var periodicalSearch;
var periodicalStats;
var periodicalChat;
var user2userChat;
var skillSearch = $A(Array(1,2,3,5));
var serverSearch = 0;
var rowTemplate = new Template ('<tr id="#{i}"><td class="td-country"><img src="/flags/#{c}.gif">#{cn}</td><td class="td-time">#{t}</td><td class="td-nick"><a href="javascript:startChat(\'#{i}\');void(0);">#{u}</a></td><td class="td-skill">#{sk}</td><td class="td-server"><img src="/img/#{s}.png"></td><td class="td-msg">#{m}</td></tr>\n');

var chatTemplate = new Template('<tr><td class="td-nick #{c}">#{u}</td><td class="td-msg">#{m}</td></tr>\n');
var currentUser = false;

function initLight(){
	xonxSearch = 0;
	liveStats();
	periodicalStats = new PeriodicalExecuter(liveStats, 10);	
}

function initScript() {
	$('page-container').show();
	$('notice').hide();
	$('menu').hide();
	$('chat-container').hide();
	$('active-users-container').hide();
	$('count-'+gameSearch+'-'+xonxSearch).parentNode.addClassName('active');
	
	SortableTable.addSortType('pureInt', 
		function(a,b){
			var pureInt = function(v){
				r = v.replace(/[^0-9]/g,'');
				if (/min/.test(v)) r = r *60;				
				return parseInt(r);
			}
			return SortableTable.compare(pureInt(a),pureInt(b));	
		}
	);
	SortableTable.setup( {rowOddClass: 'td-alternate', rowEvenClass: '' });
	
	liveSearch();
	periodicalSearch = new PeriodicalExecuter(liveSearch, 2);
	
	liveStats();
	periodicalStats = new PeriodicalExecuter(liveStats, 6);
	
	liveUsers();
	
	duSuchst();
}

function liveStats() {
	var url = '/api/livestats';
	new Ajax.Request(url, { 
		method:'get',
		onSuccess: function(transport, json){
			var data = transport.responseText.evalJSON();
			for (g=0; g<data.length; g++) {
				for (i=1; i<=5; i++) {
					if (data[g][i] != undefined) {
						c = '('+data[g][i]+')';
						if (i == xonxSearch && g == gameSearch)
							$('count-'+gameSearch+'-'+xonxSearch).parentNode.addClassName('active');
					} else c = '(0)';
					
					if ( $('count-'+g+'-'+i).innerHTML != c ) {
						new Effect.Pulsate ('count-'+g+'-'+i, { pulses: 1, duration: 0.5 } );
						$('count-'+g+'-'+i).innerHTML = c; 
					}
				}
			}
			
			// live user stats if in search mode
			if (periodicalSearch != undefined)
				liveUsers();
		}
	});
}

function liveSearch() {
	$('loading').show();
	
	var rows = $A($('live-table').getElementsByTagName('tr'));
	var rowids = Array();
	rows.each(function(r){ rowids.push(r.id); });
	rowids = $A(rowids);
	
	var url = '/live_json.php?skill='+skillSearch.toString()+'&server='+(serverSearch+1)+'&xonx='+(xonxSearch)+'&game='+gameSearch;
	
	new Ajax.Request(url, { 
		method:'get',
		onSuccess: function(transport, json){
			var data = transport.responseText.evalJSON();
			if (data.length > 0) {
				data.each( function(item) {
					rowids = rowids.without(item.i);
					if ($(item.i)) {
						$(item.i).getElementsByClassName('td-time')[0].innerHTML = getAge(item.t);
					} else {
						if (item.m.length > 40)
							item.m = item.m.substr(0, 40);      
						var n = $('live-table').insert( { top: rowTemplate.evaluate(item) });
						var x = $(n.getElementsByClassName('td-time')[0]);
						x.update(getAge(x.innerHTML));
						e = $$('#'+item.i+' .td-nick a')[0];
						new Effect.Pulsate($(item.i), { duration: 1, pulses: 1});
					}
				});
			} else notice('Leider nichts gefunden! :\'/');
				
			rowids.each(function(x){ $(x).remove(); });
			SortableTable.sort($('funwar-table'), 2, 1);
			$('loading').hide();
		}
	});
}

function getAge(s){
	m = (s / 60).floor();
	s = (s % 60);
	if (m == 0)
		return s+' sec';	
	return '>'+m+' min';
}

function skillToggle(t){
	if (t.checked) {
		skillSearch.push(t.value);
	} else skillSearch = skillSearch.without(t.value);

	periodicalSearch.stop();
	if (skillSearch.length == 0) {
		t.checked = true;
		notice('Skill Ausw&auml;hlen sonst gibts hier keine Ergebnisse :o)!');
	} else {
		liveSearch();
		periodicalSearch = new PeriodicalExecuter(liveSearch, 5);
	}	
	duSuchst();
}

function serverToggle(t) {
	serverSearch = parseInt(t.value);
	periodicalSearch.stop();
	liveSearch();
	periodicalSearch = new PeriodicalExecuter(liveSearch, 5);
	duSuchst();
}

function notice(t){
	with ($('notice')){
		show();
		innerHTML = t;
	}
	new Effect.Highlight('notice', { afterFinish: 
		function(){ new Effect.BlindUp('notice'); }, 
		endcolor: '#eeeeee', duration: 3 
	});
}

function startChat(id) {
	$('loading').show();
	periodicalSearch.stop();
	periodicalStats.stop();
	chatMessageClear();
	
	$('chat-container').show();
	$('sidebar').hide();
	$('funwar-table').hide();
	new Effect.BlindUp('menu-container');
	new Effect.Morph('page-container', { style:{ paddingTop: '100px' } });
	
	currentUser = $$('#'+id+' .td-nick a')[0].innerHTML;
	searched = $A($$('#'+id+' .td-msg'))[0].innerHTML;
	$('chat-submit').disabled = $('chat-input').disabled = false;
	
	new Ajax.Request('/api/startchat', {
			parameters: 'userid='+encodeURIComponent(id),
			onSuccess: function (x) {
				x = x.responseText;
				if (/^Error/.test(x)) {
					alert('Fehler:\n'+x);
				} else {
					chatNoteAdd(x);
					chatNoteAdd(currentUser+" hat nach &raquo;<strong>"+searched+"</strong>&laquo; gesucht.");
					$('chat-input').focus();
					periodicalChat = new PeriodicalExecuter(liveChat, 2);
					liveChat();
				}
				$('loading').hide();
			}
		}
	);
}

function endChat() {
	currentUser = false;
	user2userChat = false;
	periodicalChat.stop();
	
	var url = '/api/endchat';
	new Ajax.Request(url, { 
		method:'get',
		asynchronous: false,
		onSuccess: function(transport, json){
			if (/Error/.test(transport.responseText)){
				alert('Fehler:\n'+t);
			}
		}
	});
	
}

function sendChatMessage() {
	$('chat-submit').disabled = true;
	$('loading').show();
	var msg = $('chat-input').value;
	if (msg == '') {
		alert('Leere Nachrichten kann man schwer versenden.. :-/');
	} else {
		params = 'm='+encodeURIComponent(msg);
		var url = '/api/sendmessage';
		new Ajax.Request(url, { 
			parameters: params,
			onSuccess: function(transport, json){				
				if ( transport.responseText.indexOf('Error') > -1 ){
					alert('Fehler:\n'+transport.responseText);
				}
				$('loading').hide();
				$('chat-input').value = '';
				$('chat-submit').disabled = false;
				$('chat-input').focus();
				if (user2userChat) {
					line = new Object();
					line.c = 'you';
					line.u = 'Du';
					line.m = msg.replace(/</g,'&lt;').replace(/>/g,'&gt;');
					chatMessageAdd(line);
				}
			}
		});
	}
}

function liveChat() {
	var url = '/api/livechat';
	new Ajax.Request(url, { 
		method:'get',
		onSuccess: function(transport, json){
			if (transport.responseText.indexOf('Error') != -1) {
				alert(transport.responseText);
				periodicalChat.stop();
			}
			var data = transport.responseText.evalJSON();
			data.each(
				function(line) {
					if (line.u == currentUser) {	
						line.c = 'not-you';
					} else {
						line.c = 'you';
					}
					if (user2userChat)
						line.c = (line.u == 'Du')?'you':'not-you';
						
					if ( line.m == 'LEFT_CHANNEL' ) {
						chatNoteAdd ('<strong style="color: red">'+line.u+' hat den Chatroom verlassen!</strong>');
						chatNoteAdd ('Bitte schließe nun das Chatfenster.');
						$('chat-submit').disabled = $('chat-input').disabled = true;
						periodicalChat.stop();
					} else 
						if ( line.m != '' ) 
							chatMessageAdd(line);
				}
			);			
		}
	});
}

function chatMessageClear(){
	$('chat-messages').innerHTML = '';
}

function chatMessageAdd(msg){
	$('chat-messages').insert( { bottom: chatTemplate.evaluate(msg) });
}

function siteUnload(e) {
	if (currentUser != false) endChat();
}

function chatNoteAdd(note){
	m = Object();
	m.m = note;
	m.c = 'info';
	m.u = 'Info';
	chatMessageAdd(m);
}

function closeChat(){
	endChat();
	new Effect.BlindDown('menu-container');
	new Effect.Morph('page-container', { style:{ paddingTop: '5px' } });
	new Effect.BlindUp('chat-container', { afterFinish: 
		function() {
			$('funwar-table').show();
			$('sidebar').show();
			liveSearch();
			periodicalSearch = new PeriodicalExecuter(liveSearch, 5);
			liveStats();
			periodicalStats = new PeriodicalExecuter(liveStats, 10);
		}
	});
}

function menuToggle(t){
	new Effect.toggle('menu', 'blind', { duration: 0.5 });
	active = 'Ergebnisse Filtern';
	inactive = 'Filtermenu schließen';
	with (t) {
		innerHTML = (innerHTML == active)?inactive:active;
		style.backgroundColor = (innerHTML == active)?'#eee':'#ddd';
	}	
}

function checkChatEnter(e){
	var characterCode
	if(e && e.which){
		e = e;
		characterCode = e.which;
	} else {
		e = event;
		characterCode = e.keyCode;
	}
	if(characterCode == 13){
		sendChatMessage();
		return false;
	} else return true;
}

Array.prototype.max = function(){
   return Math.max.apply({},this)
}


function duSuchst(){
	text = 'Du suchst '+xonxSearch+'on'+xonxSearch+' '+skillName(skillSearch)+' server '+((serverSearch==-1)?'off':'on');
	$('suche').innerHTML = text;
}

function skillName(s){
	if (s.length == 4)
		return 'skill egal';
	s = $A(s).max();
	switch(s){
		case 1: return 'low';
		case 2: return 'low-mid';
		case 3: return 'mid';
		case 5: return 'high';
	}
}


function startUser2UserChat(id, searched){	
	$('loading').show();
	periodicalSearch.stop();
	periodicalStats.stop();
	chatMessageClear();
	
	$('chat-container').show();
	$('sidebar').hide();
	$('funwar-table').hide();
	new Effect.BlindUp('menu-container');
	new Effect.Morph('page-container', { style:{ paddingTop: '100px' } });
	
	$('chat-submit').disabled = $('chat-input').disabled = false;
	
	new Ajax.Request('/api/startchat', {
			parameters: 'userid='+encodeURIComponent(id)+"&user2user=1",
			onSuccess: function (x) {
				x = x.responseText;
				if (/^Error/.test(x)) {
					alert('Fehler:\n'+x);
				} else {
					user2userChat = true;
					chatNoteAdd("User2User Chat wird gestartet..");
					chatNoteAdd("Der Onlinebenutzer hat nach <strong>"+searched+"</strong>&laquo; gesucht.");
					$('chat-input').focus();
					periodicalChat = new PeriodicalExecuter(liveChat, 2);
					liveChat();
				}
				$('loading').hide();
			}
		}
	);

}

function receiveUser2UserChat(id){
	$('loading').show();
	periodicalSearch.stop();
	periodicalStats.stop();
	chatMessageClear();
	
	//alert('incoming chat!');
	user2userChat = true;
	
	$('chat-container').show();
	$('sidebar').hide();
	$('funwar-table').hide();
	new Effect.BlindUp('menu-container');
	new Effect.Morph('page-container', { style:{ paddingTop: '100px' } });
	
	$('chat-submit').disabled = $('chat-input').disabled = false;
	chatNoteAdd("Ein Benutzer des Webinterfaces schreib dich an..");
	$('chat-input').focus();
	periodicalChat = new PeriodicalExecuter(liveChat, 2);
	liveChat();
	$('loading').hide();
}

function liveUsers(){
	var url = '/api/liveusers';
	var activeUsersTemplate = new Template("<li><a href='javascript:startUser2UserChat(\"#{id}\",\""+xonxSearch+'on'+xonxSearch+" #{sk} #{sv}\");void(0);' class='#{sv}'>#{sk}</a></li>");
	new Ajax.Request(url, { 
		method:'get',
		onSuccess: function(transport, json){
			try { 
			var data = transport.responseText.evalJSON();
			} catch(e) { alert(data); }
			$('active-users').innerHTML = '';
			if (data.length == 0) {
				$('active-users').innerHTML = '<li>z.Z. niemand :-(</li>';
				$('active-users-container').hide();
			} else $('active-users-container').show();
			
			for (i=0; i<data.length; i++) {
				if (data[i].i != undefined) {
					receiveUser2UserChat(data[i].i);
				} else {
					data[i].sv = (data[i].sv==0)?'off':'on';
					data[i].sk = skillName(data[i].sk);
					var n = $('active-users').insert( { top: activeUsersTemplate.evaluate(data[i]) });
				}
			}
			
		}
	});
}

function listHover(t,d){
	//~ t.innerHTML+='<p class=".hover-text"><i>'+d+'</i></p>';
}

function listHoverOut(){
	//~ $$(".hover-text").each(Element.remove);
}
