/*----------------------------------------*/
/*												      */
/*  Chatterbox JavaScript Framework       */
/*  Epigroove <http://www.epigroove.com>  */
/*													   */
/*----------------------------------------*/

var player_id = ""; // fetched during Initialize()
var account_type = ""; // fetched during Initialize()
var puzzle_id = ""; // fetched during Initialize()
var puzzle_closed = ""; // fetched during Initialize()
var last_challenge_id = ""; // fetched during Initialize()
var last_notice_id = ""; // fetched during Initialize()
var last_chat_log_id = "";
var chat_semaphore = notice_semaphore = true;
var update_frequency = 10000;

function Initialize () {
	var myAjax = new Ajax.Request ('/action/initialize', { method: 'get', onComplete: InitializePostOp } );
}

function InitializePostOp (result) {
	//$('testing').innerHTML += result.responseText + '<br>';
	var response = result.responseText;

	try {
		var data = eval("(" + result.responseText + ")"); // convert results into a javascript object
	}
	catch (e) {
		DisplayError("Initialization error. Contact Dr_God if this persists.");
		return;
	}
	
	player_id = data.player_id;
	account_type = data.account_type;
	puzzle_id = data.puzzle_id;
	puzzle_closed = data.closed;
	last_notice_id = data.last_notice_id;
	
	// populate the players list
	for (i=0; i<data.players.length; i++) {
		AddToPlayersList(data.players[i]);
	}

	// populate the friends list
	for (i=0; i<data.friends.length; i++) {
		AddToFriendsList(data.friends[i]);
	}
}

function AddChatMessage () {
	var message = $F('add_message');
	
	if (!message) {
		alert('Please enter a message');
	}
	else {
		var params = 'message=' + encodeURIComponent(message) + '&puzzleid=' + puzzle_id;
		var myAjax = new Ajax.Request ('/action/add_chat_message', { method: 'post', parameters: params, onComplete: AddChatMessagePostOp } );
	}
}

function AddChatMessagePostOp (result) {
	Field.clear('add_message');
}

function Sniffer () {
	GetUpdates();
	setTimeout('Sniffer()',update_frequency);
}

function GetUpdates () {
	if (chat_semaphore && notice_semaphore && last_notice_id != '') { // make sure GetUpdates() isn't still running from the last ping and that Initialize() is done
		chat_semaphore = notice_semaphore = false; // stop GetUpdates() from running again until this round of updates is done
		var params = 'last_chat_log_id=' + last_chat_log_id + '&last_notice_id=' + last_notice_id;
		var myAjax = new Ajax.Request ('/action/get_updates', { method: 'get', parameters: params, onComplete: GetUpdatesPostOp } );
	}
}

function GetUpdatesPostOp (result) {
	if (result.responseText) {
		try {
			var data = eval("(" + result.responseText + ")"); // convert results into a javascript object
		}
		catch (e) {
			//DisplayError("Connection error. Contact Dr_God if this persists.");
			chat_semaphore = notice_semaphore = true;	
			return;
		}
		
		$('post_message').style.display = '';
		$('loading_message').style.display = 'none';

		// parse chat messages and append them to the chat log
		if (data.chats) {
			for (i=0; i<data.chats.length; i++) {
				AppendChatMessage(data.chats[i]);
			}
			last_chat_log_id = data.last_chat_log_id;
		}
		
		// parse notices and append them to the chat log
		if (data.notices) {
			last_notice_id = data.last_notice_id;
			for (i=0; i<data.notices.length; i++) {
				if (data.notices[i].type == 'log_on') {
					AddToPlayersList(data.notices[i].player);
					UpdateStatus(data.notices[i].player.id,"on");
					//AppendNotice(data.notices[i]);
				}
				else if (data.notices[i].type == 'log_off') {
					RemoveFromPlayersList(data.notices[i].player.id);
					UpdateStatus(data.notices[i].player.id,"off");
					//AppendNotice(data.notices[i]);
				}
				else if (data.notices[i].type == 'refresh') {
					window.location = 'http://' + window.location.host;
				}
				else if (data.notices[i].type == 'log_out') {
					if (data.notices[i].player.id == player_id || data.notices[i].player.id == 0) {
						window.location = 'http://' + window.location.host + '/action/log_out';
					}
				}
			}
		}
	}
	
	chat_semaphore = notice_semaphore = true;	
}

function AddToPlayersList (player_obj) {
	var parent_div = $('players_list');
	var players = parent_div.childNodes;
	var td_html = '';
	var dr_god = (player_obj.player_id == 1) ? ' dr_god' : '';
	
	var player_added = false;
	if (parent_div.rows.length == 0) { // the players list is empty
		var row = parent_div.insertRow(0);
		player_added = true;
	}
	else {
		// step through players list until the new player's name is greater than the current player's name
		for (x=0; x<parent_div.rows.length; x++) {
			player_info = parent_div.rows[x].getElementsByTagName("div");
			for (y=0; y<player_info.length; y++) {
				if (player_info[y].className == 'name') {
					if (player_obj.player_name.toLowerCase() < player_info[y].innerHTML.toLowerCase()) {
						var row = parent_div.insertRow(x);
						player_added = true;
						x = parent_div.rows.length; y = player_info.length; // this will kick us out of both loops
					}
				}
			}
		}
	}
	
	if (!player_added) { // this means that the player's name is greater than the last player on the players list - append the new player
		var row = parent_div.insertRow(parent_div.rows.length);
	}
	
	row.setAttribute("id","player"+player_obj.id);

	// create "buddy_icon" <td>
	var buddy_cell = row.insertCell(0);
	buddy_cell.setAttribute("className","buddy_icon"); // IE
	buddy_cell.setAttribute("class","buddy_icon");

	// create "content_td" <td>
	var content_cell = row.insertCell(1);
	content_cell.setAttribute("className","content");
	content_cell.setAttribute("class","content");

	// create and add the beef to the "buddy_icon" <td>
	buddy_cell.innerHTML = GetBuddyIcon(player_obj.id,player_obj.buddy_icon);

	// create the beef for the "content" <td>
	if (player_obj.id != player_id && account_type == 1) {
		td_html = '<span class="add_friend">';
		td_html += '<a href="javascript:AddToFriends(\'' + player_obj.id + '\');">Add to Friends</a>';
		td_html += '</span>';
	}
	td_html += '<div class="name' + dr_god + '">' + player_obj.player_name + '</div>';
	td_html += '<div class="message" style="margin-top: 7px">';
	if (player_obj.show_profile == "1") td_html += GetProfileIcon(player_obj.id,player_obj.gender);
	td_html += GetFlag(player_obj.country) ;
	td_html += '</div>';

	// add the beef
	content_cell.innerHTML = td_html;
	
	$('num_players_display').innerHTML = parseInt($('num_players_display').innerHTML) + 1; // increment the who's online display total
}

function RemoveFromPlayersList (playerid) {
	var table = $('players_list');
	var row = $('player'+playerid);
	if (row) {
		table.deleteRow(row.rowIndex);
		$('num_players_display').innerHTML = parseInt($('num_players_display').innerHTML) - 1;
	}
}

function AddToFriends (friendid) {
	// check to make sure this friend isn't already on the friends list
	if ($('friend'+friendid)) {
		alert('This player is already on your Friends List');
		return;
	}
	
	var params = 'friendid=' + friendid;
	var myAjax = new Ajax.Request ('/action/add_to_friends', { method: 'post', parameters: params, onComplete: AddToFriendsPostOp } );
	
}

function AddToFriendsPostOp (result) {
	if (result.responseText) {
		try {
			var data = eval("(" + result.responseText + ")"); // convert results into a javascript object
		}
		catch (e) {
			return;
		}
		
		AddToFriendsList(data);
		
		GoTo('friends');
		SetTab('friends_tab');
		Blink('friend'+data.id,8);
	}
}

function AddToFriendsList (friend_obj) {
	var parent_div = $('friends_list');
	var td_html = '';
	var dr_god = (friend_obj.player_id == 1) ? ' dr_god' : '';
	
	var friend_added = false;
	if (parent_div.rows.length == 0) { // the friends list is empty
		var row = parent_div.insertRow(0);
		friend_added = true;
	}
	else {
		// step through friends list until the new friend's name is greater than the current friend's name
		for (x=0; x<parent_div.rows.length; x++) {
			friend_info = parent_div.rows[x].getElementsByTagName("div");
			for (y=0; y<friend_info.length; y++) {
				if (friend_info[y].className == 'name') {
					if (friend_obj.player_name.toLowerCase() < friend_info[y].innerHTML.toLowerCase()) {
						var row = parent_div.insertRow(x);
						friend_added = true;
						x = parent_div.rows.length; y = friend_info.length; // this will kick us out of both loops
					}
				}
			}
		}
	}
	
	if (!friend_added) { // this means that the friend's name is greater than the last friend on the friends list - append the new friend
		var row = parent_div.insertRow(parent_div.rows.length);
	}
	
	row.setAttribute("id","friend"+friend_obj.id);

	// create "buddy_icon" <td>
	var buddy_cell = row.insertCell(0);
	buddy_cell.setAttribute("className","buddy_icon"); // IE
	buddy_cell.setAttribute("class","buddy_icon");

	// create "content_td" <td>
	var content_cell = row.insertCell(1);
	content_cell.setAttribute("className","content");
	content_cell.setAttribute("class","content");

	// create and add the beef to the "buddy_icon" <td>
	buddy_cell.innerHTML = GetBuddyIcon(friend_obj.id,friend_obj.buddy_icon);

	// create the beef for the "content" <td>
	td_html = '<span class="remove_friend"><a href="javascript:RemoveFromFriends(\'' + friend_obj.id + '\');">Remove</a></span>';
	td_html += '<div class="name' + dr_god + '" style="float: none">' + friend_obj.player_name + '</div>';
	if ($('player'+friend_obj.id)) {
		td_html += '<span class="status online">online</span>';
	}
	else {
		td_html += '<span class="status">offline</span>';
	}
	td_html += '<div class="message" style="margin-top: 8px">';
	if (friend_obj.show_profile == "1") td_html += GetProfileIcon(friend_obj.id,friend_obj.gender);
	td_html += GetFlag(friend_obj.country);
	td_html += '</div>';

	// add the beef
	content_cell.innerHTML = td_html;

	// set the background color to gray if the friend isn't online
	if (!$('player'+friend_obj.id)) {
		row.setAttribute("class","offline");
		row.setAttribute("className","offline");
	}
}

function AppendChatMessage (chat_obj) {
	var dr_god = (chat_obj.player_id == 1) ? ' dr_god' : '';
	var parent_div = $('chat_log');

	// create "entry" <tr>
	var row = parent_div.insertRow(2); // insert after "post_message" and "chat_prefs" rows
	row.setAttribute("id","chat"+chat_obj.id);

	// create "buddy_icon" <td>
	var buddy_cell = row.insertCell(0);
	buddy_cell.setAttribute("className","buddy_icon"); // IE
	buddy_cell.setAttribute("class","buddy_icon");

	// create "content_td" <td>
	var content_cell = row.insertCell(1);
	content_cell.setAttribute("className","content");
	content_cell.setAttribute("class","content");

	// create and add the beef to the "buddy_icon" <td>
	buddy_cell.innerHTML = GetBuddyIcon(chat_obj.player_id,chat_obj.buddy_icon);

	// create the beef for the "content" <td>
	td_html = '<span class="time">' + chat_obj.time + '</span>';
	td_html += '<div class="name' + dr_god + '" style="float: left">' + chat_obj.player_name + '</div>';
	if (chat_obj.show_profile == "1") td_html += '<div class="flag_profile">' + GetProfileIcon(chat_obj.player_id,chat_obj.gender) + GetFlag(chat_obj.country) + '</div>';
	td_html += '<br clear="all" />';
	td_html += '<div class="message">' + chat_obj.message + '</div>';

	// add the beef
	content_cell.innerHTML = td_html;
	
	KillLastRow();
}

function RemoveFromFriends (friendid) {
	var params = 'friendid=' + friendid;
	var myAjax = new Ajax.Request ('/action/remove_from_friends', { method: 'post', parameters: params } );

	table = $('friends_list');
	row = $('friend'+friendid);
	if (row) {
		table.deleteRow(row.rowIndex);
	}
}

function Blink (divid,repetitions) {
	if ($(divid)) {
		if (repetitions % 2 == 0) {
			$(divid).style.backgroundColor = '#fffa5e';
		}
		else {
			$(divid).style.backgroundColor = '';
		}
		repetitions--;
		if (repetitions > 0) setTimeout('Blink(\''+divid+'\',\''+repetitions+'\')',200);
	}
}

function AppendNotice (notice_obj) {
	var parent_div = $('chat_log');
	var td_html = "";
	
	if (notice_obj.type == 'log_on') {
		var message = notice_obj.player.player_name + ' has logged on';
		var style = 'logged_on';
	}
	else if (notice_obj.type == 'log_off') {
		var message = notice_obj.player.player_name + ' has logged off';
		var style = 'logged_off';
	}
	
	// create "entry" <tr>
	var row = parent_div.insertRow(2); // insert after "post_message" and "chat_prefs" rows
	row.setAttribute("id","chat"+notice_obj.id);

	// create the "contents" <td>
	var contents_cell = row.insertCell(0);
	contents_cell.colSpan = 2;
	contents_cell.setAttribute("className",style); // IE
	contents_cell.setAttribute("class",style);
	
	// create the beef of the new node
	td_html = '<span class="time">' + notice_obj.time + '</span>';
	td_html += '<div class="message">' + message + '</div>';
	
	// add the beef
	contents_cell.innerHTML = td_html;

	KillLastRow();
}

function AppendChallenge (challenge_obj) {
	var buddy_padding = (challenge_obj.buddy_icon) ? ' style="margin-left: 40px"' : '';
	var dr_god = (challenge_obj.player_id == 1) ? ' dr_god' : '';
	var challenge_html = '';
	
	challenge_html = '<div class="entry" id="challenge_entry' + challenge_obj.id + '">';
	challenge_html += '<span class="time">' + challenge_obj.time + '</span>';
	if (challenge_obj.buddy_icon) challenge_html += '<div class="buddy_icon"><img src="buddy_icons/' + challenge_obj.buddy_icon + '" height="32" width="32" /></div>';
	challenge_html += '<div class="text"' + buddy_padding + '>';
	challenge_html += '<div class="name' + dr_god + '">' + challenge_obj.player_name + '</div>';
	challenge_html += '<a href="#">Accept</a> | <a href="javascript:DeclineChallenge(' + challenge_obj.id + ')">Decline</a>';
	challenge_html += '</div>';
	challenge_html += '</div>';

	$('num_challenges').innerHTML = parseInt($('num_challenges').innerHTML) + 1;
	$('challenges_list').innerHTML = challenge_html + $('challenges_list').innerHTML;
}

function DeclineChallenge (challengeid) {
	var params = 'challenge_id=' + challengeid;
	var myAjax = new Ajax.Request ('/action/decline_challenge', { method: 'post', parameters: params, onComplete: DeclineChallengePostOp } );
}

function DeclineChallengePostOp (result) {
	if (result.responseText) { // challenge was successfully declined
		// hide the challenge
		var div_id = 'challenge_entry' + challengeid;
		$(div_id).style.display = 'none';
		
		// decrement the num_challenges total
		$('num_challenges').innerHTML = parseInt($('num_challenges').innerHTML) - 1;
	}
}

function GoTo (window_name) {
	var windows = document.getElementsByClassName('chatter_pane');
	for (i=0; i<windows.length; i++) {
		windows[i].style.display = 'none';
	}

	$(window_name).style.display = 'block';
}

function SetTab (tag_name) {
	var tabs = document.getElementsByClassName('tab');
	for (i=0; i<tabs.length; i++) {
		tabs[i].className = 'tab';
	}
	
	$(tag_name).className = 'tab on';
}

function LogOut (playerid) {
	var params = 'playerid=' + playerid;
	var myAjax = new Ajax.Request ('/action/log_out', { method: 'post', parameters: params } );
}

function UpdateStatus (friendid,type) {
	if ($('friend'+friendid)) {
		var tags = $('friend'+friendid).getElementsByTagName("span");
	
		for (x=1; x<tags.length; x++) {
			if (tags[x].className == 'status' || tags[x].className == 'status online') {
				if (type == "on") {
					tags[x].innerHTML = "online";
					tags[x].className = "status online";
					$('friend'+friendid).className = "";
				}
				else {
					tags[x].innerHTML = "offline";
					tags[x].className = "status";
					$('friend'+friendid).className = "offline";
				}
			}
		}
	}
}

function ToggleChatDrawer (div) {
	if ($(div).style.display == 'none') {
		$('chat_log_div').scrollTop = 0;
		$(div).style.display = '';
		document.post_message.add_message.focus();
	}
	else {
		$(div).style.display = 'none';
	}
}

function Hide (div) {
	$(div).style.display = 'none';
}

function Show (div) {
	$(div).style.display = '';
}

function ViewEntireChatLog () {
	window.open("chat_log/" + puzzle_id, "", "left=50,top=50,width=400,height=500,menubar=no,location=no,resizable=yes,scrollbars=yes,status=no");
}

function GetFlag (country) {
	if (!country) {
		return '';
	}
	else {
		var image_name = country.replace(new RegExp(/\s/gi),"_");
		image_name = image_name.toLowerCase();
		return '<img src="/flags/' + image_name + '.gif" height="12" width="20" align="absmiddle" alt="' + country + '" />';
	}
}

function GetProfileIcon (player_id,gender) {
	var link = '<a href="javascript:void(0);" title="View Profile" onClick="DisplayPopUp(\'/profile_mini.php?id=' + player_id + '\',350,400); return false;" style="background: transparent; margin-right: 8px">';
	
	if (gender == 'Male') link += '<img src="/images/profile_male.gif" height="12" width="12" align="absmiddle" alt="Profile" />';
	else if (gender == 'Female') link += '<img src="/images/profile_female.gif" height="12" width="12" align="absmiddle" alt="Profile" />';
	else link += '<img src="/images/profile_neutral.gif" height="12" width="12" align="absmiddle" alt="Profile" />';
	
	link += '</a>';
	
	return link;
}

function GetBuddyIcon (player_id,buddy_icon) {
	var link = "";
	
	if (buddy_icon != 'no_icon.jpg') link = '<a href="javascript:void(0);" title="View Profile" onClick="DisplayPopUp(\'/profile_mini.php?id=' + player_id + '\',350,400); return false;" style="background: transparent; margin-right: 8px">';
	link += '<img src="buddy_icons/' + buddy_icon + '" height="32" width="32" class="buddy_icon" />';
	if (buddy_icon != 'no_icon.jpg') link += '</a>';
	
	return link;
}

function DisplayPopUp (url,width,height) {
	window.open(url,'','status=yes,scrollbars=yes,resizable,width='+width+',height='+height);
}

function DisplayError (message) {
	var parent_div = $('chat_log');
	var td_html = "";
	var today = new Date();
	var hours = today.getHours();
	var minutes = today.getMinutes();
	
	// create "entry" <tr>
	var row = parent_div.insertRow(2); // insert after "post_message" and "chat_prefs" rows

	// create the "contents" <td>
	var contents_cell = row.insertCell(0);
	contents_cell.colSpan = 2;
	contents_cell.className = "error";
	
	// format time
	if (hours > 12) hours = hours - 12;
	if (minutes < 10) minutes = "0" + minutes;
	
	// create the beef of the new node
	td_html = '<span class="time">' + hours + ":" + minutes + '</span>';
	td_html += '<div class="message">' + message + '</div>';
	
	// add the beef
	contents_cell.innerHTML = td_html;
	
	KillLastRow();
}

function KillLastRow() {
	var parent_div = $('chat_log');
	if (parent_div.rows.length == 52) {
		parent_div.deleteRow(51);
	}
}