var last_offset= 0;
var fetching= false;
var standalone= false;
var lastchat= new Array();
var lastchat_index= 0;
var numchats= 0;
	

function update(response) {	
	
	var items = response.documentElement.getElementsByTagName('item');
	var users = response.documentElement.getElementsByTagName('user');
	var n;	
	
	var should_scroll= false;
	if ($j('#chat').scrollTop()+$j('#chat')[0].clientHeight >= $j('#chat')[0].scrollHeight-5) 
		should_scroll= true;
	
	for (n=0; n < items.length; n++)
	{   
		var name= items[n].getAttribute('name').substring(0,15);
		var identity= items[n].getAttribute('identity'); 						
		var message= items[n].firstChild.data;
		var user= null;
		for (n2=0; n2 < users.length; n2++)		
			if (users[n2].getAttribute('name')==name) user= users[n2];	
		textcolor= '#000000';
		if (user) {
			var team= parseInt(user.getAttribute('team'));
			var level= parseInt(user.getAttribute('level'));
			var status= parseInt(user.getAttribute('status'));
			var powerlevel= parseInt(user.getAttribute('powerlevel'));			
			
			switch (team%9) {
			case 0: teamcolor2='#0096FC'; break;
			case 1: teamcolor2='#ff0000';break;
			case 2: teamcolor2='#0000ff';break;
			case 3: teamcolor2='#00ff00';break;
			case 4: teamcolor2='#ffff00';break;
			case 5: teamcolor2='#00ffff';break;
			case 6: teamcolor2='#ff00ff';break;
			case 7: teamcolor2='#808080';break;
			case 8: teamcolor2='#FF69B4';break;			
			}		
			if (team >= 9) textcolor= '#ffffff';
			switch (Math.floor(team/9)) {
			case 0: teamcolor= 'transparent'; break;
			case 1: teamcolor= '#800000';break;
			case 2: teamcolor= '#000080';break;
			case 3: teamcolor= '#008000';break;
			case 4: teamcolor= '#808000';break;
			case 5: teamcolor= '#008080';break;
			case 6: teamcolor= '#800080';break;
			case 7: teamcolor= '#000000';break;
			case 8: teamcolor= '#FF1493';break;			
			}  
			
			var style= '-moz-border-radius: 5px;-webkit-border-radius: 5px;border-radius:5px;padding:0 3px;';
			var color= '';
			switch(level) {
			case 127: color='black'; break;
			case 7:   color='white'; break;
			case 6:   color='purple'; break;
			case 5:   color='blue'; break;
			case 4:   color='green'; break;
			case 3:   color='yellow'; break;
			case 2:   color='orange'; break;
			case 1:   color='red'; break;
			default: if (level > 0) color='white'; break;
			}
			if (status&1)  style+='font-style:italic;'; // away
			if (status&2)  style+='border:2px solid blue;'; // barrier			
			if (status&4 && !(status&64))  style+='background-color:#66ff66;'; // medic
			if (status&8)  { 
				style+='font-weight:bold;'; // powerup
				if (powerlevel > 1) color='#ffff80';
			}								
			if (status&16) style+='font-size:160%;line-height:12px'; // giant
			if (status&32) style+='font-size:70%;'; // midget
			if (status&64) { status&4? style+='background-color:#999933;' : style+='background-color:#996600;'; }// zomby 
			if (status&128)style+='text-shadow:2px 2px 2px #000;'; // fly			
			if (status&512)style+='opacity: 0.4;filter: alpha(opacity=40);'; // ghost
			if (hp<=0) style+='text-decoration:line-through;';	
			if (color!='') style+='color:'+color+';';
		}
		//comment.setAttribute('class', 'bd');
		
		var comment_div= document.createElement('div');
		comment_div.setAttribute('class', 'chat_list');
		if (name.indexOf('Guest')==-1) {
			if (name=='') {
				comment_div.innerHTML= '<font style="font-size:80%">' + message + '</font>';
			} else
			if (name=='Andrograde') {					
				comment_div.innerHTML= '<b style="color: black;">' + name + '</b>' + message;
			} else {
				comment_div.innerHTML= '<font style="background-color:'+teamcolor+';"><b><a style="color:'+teamcolor2+';'+style+'" href="profile.php?view='+identity+'" target="_blank">' + name +'</a></b><font style="color:'+textcolor+'"> ' + message + '</font></font>';
			}
		} else {			
			comment_div.innerHTML= '<b style="color:'+teamcolor2+'">' + name + '</b>: ' + message;			
		}
					
		$j('#chat').append(comment_div);			
		if (standalone) document.title = message.replace(/(<([^>]+)>)/ig,""); 
		numchats++;
		//last_offset++;
	}   
	
	if (numchats > 100) {
		$j('.chat_list:first').remove();
		numchats--;
	}

	last_offset = response.documentElement.getAttribute('last_offset');
	//last_offset= feed[0].getAttribute('last_offset');
	if (should_scroll)
        $j("#chat").animate({scrollTop: $j("#chat").attr("scrollHeight") }, 1000);   		
		//$j('#chat').scrollTop($j('#chat')[0].scrollHeight);
		
	if (users.length == 0) return; 
	$j('#chat_users_head').html(response.documentElement.getAttribute('numusers') +' People Online');
	
	//$j('#chat_users').html('<table>');
	var user_html= '<table class="chat_users"><tbody>';
	var game;
	var gamedir;
	var level;
	var exp;
	var feed;
	var status;
	var hp;
	var hpcolor;
	var team;
	var room;
	for (n=0; n < users.length; n++)
	{		
		if (users[n].getAttribute('name')!=null) {			
			if (users[n].firstChild!=null) identity= users[n].firstChild.data;
										else identity= '';
			name= users[n].getAttribute('name');
			if (name==null) continue;
			name= name.substring(0,15);
			game= users[n].getAttribute('game');
			gamedir= users[n].getAttribute('gamedir');
			level= parseInt(users[n].getAttribute('level'));
			exp= parseInt(users[n].getAttribute('exp'));
			feed= users[n].getAttribute('feed');
			status= parseInt(users[n].getAttribute('status'));
			hp= parseInt(users[n].getAttribute('hp'));
			team= parseInt(users[n].getAttribute('team'));
			room= users[n].getAttribute('room');			
			maxhp= parseInt(users[n].getAttribute('maxhp'));			
			powerlevel= parseInt(users[n].getAttribute('powerlevel'));			
			
			var teamcolor= '';
			var teamcolor2= '';
			var style= 'style="-moz-border-radius: 5px;-webkit-border-radius: 5px;border-radius:5px;padding:0 3px;';
			var color='';
			switch(level) {
			case 127: color='black'; break;
			case 7:   color='white'; break;
			case 6:   color='purple'; break;
			case 5:   color='blue'; break;
			case 4:   color='green'; break;
			case 3:   color='yellow'; break;
			case 2:   color='orange'; break;
			case 1:   color='red'; break;
			default: if (level > 0) color='white'; break;			
			}
			if (status&1)  style+='font-style:italic;'; // away
			if (status&2)  style+='border:2px solid blue;'; // barrier			
			if (status&4 && !(status&64))  style+='background-color:#66ff66;'; // medic
			if (status&8)  {
				style+='font-weight:bold;'; // powerup
				if (powerlevel > 1) color='#ffff80';
			}
			if (status&16) style+='font-size:160%;line-height:12px'; // giant
			if (status&32) style+='font-size:70%;'; // midget
			if (status&64) { status&4? style+='background-color:#999933;' : style+='background-color:#996600;'; }// zomby 
			if (status&128)style+='text-shadow:2px 2px 2px #000;'; // fly			
			if (status&512)style+='opacity: 0.4;filter: alpha(opacity=40);'; // ghost
			if (hp<=0) style+='text-decoration:line-through;';
			if (color!='') style+='color:'+color+';';
			style+='"';
			
			user_html+='<tr style="height:17px;">';
			if (feed!='' && feed!='0') {				
				user_html += '<td><a href="#" onclick="popup(\'../GameFeedClient.swf?feed='+identity+'\', \'Game\', 640, 480); return false;">';
				switch(parseInt(feed)) {
				case 1: user_html+='<img width="16" height="16" src="../images/soundfeedon.png">'; break;
				case 2: user_html+='<img width="16" height="16" src="../images/webcamfeedon.png">'; break;
				case 3: user_html+='<img width="16" height="16" src="../images/gamefeedon.png">'; break;
				}
				user_html+='</a></td>';
			}else
				user_html +='<td></td>';
				
			user_html += '<td><img width="16" height="16" src="authenticate.php?action=getimage&user='+identity+'"></td>' +
			             '<td><a '+style+' href="profile.php?view='+identity+'" target="_blank" title="Click to see '+name+'\'s profile">' + name + '</a></td>';
			teamcolor= '#ACF0F2';
			teamcolor2= '#0096FC';
			switch (team%9) {
			case 0: teamcolor= '#ffffff'; teamcolor2='GoldenRod'; break;
			case 1: teamcolor= '#800000'; teamcolor2='#ff0000';break;
			case 2: teamcolor= '#000080'; teamcolor2='#0000ff';break;
			case 3: teamcolor= '#008000'; teamcolor2='#00ff00';break;
			case 4: teamcolor= '#808000'; teamcolor2='#ffff00';break;
			case 5: teamcolor= '#008080'; teamcolor2='#00ffff';break;
			case 6: teamcolor= '#800080'; teamcolor2='#ff00ff';break;
			case 7: teamcolor= '#000000'; teamcolor2='#808080';break;
			case 8: teamcolor= '#FF1493'; teamcolor2='#FF69B4';break;
			}			
			switch (Math.floor(team/9)) {			
			case 1: teamcolor= '#800000';break;
			case 2: teamcolor= '#000080';break;
			case 3: teamcolor= '#008000';break;
			case 4: teamcolor= '#808000';break;
			case 5: teamcolor= '#008080';break;
			case 6: teamcolor= '#800080';break;
			case 7: teamcolor= '#000000';break;
			case 8: teamcolor= '#FF1493';break;			
			}       
			
			var hp2= parseInt(hp*255/maxhp);
			if (hp2 >= 256) hpcolor='color:#ffffff;'; else						
			if (hp > 0) hpcolor='color:#' + (15-parseInt(hp2/16)).toString(16) + (15-parseInt(hp2%16)).toString(16) + 
										parseInt(hp2/16).toString(16) + parseInt((hp2)%16).toString(16) + '00;';
					else hpcolor='color:#ff0000;';			
			if (hp2 >= 256) hpcolor+='text-shadow:1px 1px 0px #000;';
			if (hp2 < 26) hpcolor+='text-decoration: blink;';
			user_html+='<td style="width:44px;">';
			if (game!='') {								
				user_html+= '<font style="'+hpcolor+';float:left">'+hp+'</font>';				
				user_html+=' <font style="background-color:'+teamcolor+';color:'+teamcolor2+';float:right">'+exp+'</font></td>'+
							'<td><a href="show.php?game='+gamedir+'" target="_blank" title="Click to play '+game+'">' + game + '</a></td>';							
			}else {								
				user_html+='<font style="'+hpcolor+';float:left">'+hp+'</font>';				
				user_html+=' <font style="background-color:'+teamcolor+';color:'+teamcolor2+';float:right">'+exp+'</font></td>'+
							'<td><i>Just Chatting</i></td>';
			}
			user_html+='<td>'+room+'</td>';
			user_html+='</tr>';
		} else { 
			user_html +='<tr><td></td><td></td><td>'+users[n].firstChild.data+'</td><td></td><td></td></tr>';
		}				
	}	
	user_html +='</tbody></table>';
	$j('#chat_users').html(user_html);
}

function fetchChatContent(){
	if (fetching==true) return;
	
	fetching= true;
	$j.ajax({type: "GET",
			url: "feeds/chatfeed.php", 
			dataType: "xml",
			data: { chatting: true, offset: last_offset, cache: Math.random() },
			error: function() { fetching= false; },
			success: function(response) { update(response); fetching= false; }			
	});
}

function chatinput(e) { //e is event object passed from function invocation	
	var characterCode;// literal character code will be stored in this variable

	if (e && e.which) //if which property of event object is supported (NN4)
		characterCode = e.which;
	else //character code is contained in IE's keyCode property
		characterCode = event.keyCode;
		
	if (characterCode == 13) { 	
		if 	($j('#message').val()=='/clear') {
			$j('#message').val('');
			$j('#chat').html('');
		} else {
			chat();
		}
		return false;
	} 
	if (characterCode == 38) { // up
		if (lastchat_index > 0) lastchat_index--;
		$j('#message').val(lastchat[lastchat_index]);
		return false;
	}
	if (characterCode == 40) { // down
		if (lastchat_index < lastchat.length-1) 
			$j('#message').val(lastchat[++lastchat_index]);
		else
			$j('#message').val('');
			
		return false;
	}
	return true;
}

function chat() {		
	if ($j('#message').val()=='') return; // dont send blank entries
	
	if (lastchat.length > 20) lastchat.shift();
	lastchat.push($j('#message').val());
	lastchat_index= lastchat.length;
	
	fetching= true;
	$j.ajax({type: "GET",
			url: "feeds/chatfeed.php", 
			dataType: "xml",
			data: { add: 'true', 
					chatting: true,
					message: $j('#message').val(), 
					offset: last_offset,
					cache: Math.random() },
			error: function() { fetching= false; },
			success: function(response) { update(response); fetching= false; }			
	});	
	$j('#message').val('');
}


function init_chat() {	
	$j(document).ready(function () {	
		fetchChatContent();
		setInterval("fetchChatContent()",2000);	
		
		var attributes = {
			id:"ChatWidget",
			allowScriptAccess: 'always'
		};
		swfobject.embedSWF('ChatWidget.swf', 'ChatWidget', '1', '1', '9.0.0', 'expressInstall.swf', null, null, attributes);
	});	
}