// run loop to check if chat request initiated
// if so then display chat panel
var f;
var hasfocus = true;
var pagetitle = document.title;	// store page title to restore after chat alert flash
var bellPlayed = false;

// if window not in focus then flash title and play bell sound - for new chats and messages
function flashTitle(friend, type) {
	if (type == 'chat') {
		if (document.title != pagetitle) document.title = pagetitle; else document.title = 'Chat request from ' + friend;
	} else {
		if (document.title != pagetitle) document.title = pagetitle; else document.title = 'New Message';
	}
	if (type == 'chat') {
		if (!bellPlayed) {
			bellPlayed = true;
			if (Modernizr.audio) {
				 document.getElementById('chat-bell').play();
			}		
		} 
	}	else if (type == 'msg') {
			type = 'msg-played';
			if (Modernizr.audio) {
				 document.getElementById('msg-bell').play();
			}		
	}
	if(typeof(f) !== 'undefined') clearTimeout(f);
	if( $('#chat-alert').is(':visible') || type != 'chat') { f = setTimeout("flashTitle('" + friend + "', '" + type + "')",1000);} // every 5 seconds 
	else if (type == 'chat') document.title = pagetitle;
}

// detects if window in focus or not
// used by flashTitle function
$(document).ready(function() {
	$(window).bind("blur", function() {
		hasfocus = false;
});

	$(window).bind("focus", function() {
		hasfocus = true;
		document.title = pagetitle;
		if(typeof(f) !== 'undefined') clearTimeout(f);
	});
});
	

function chat_check(user_id, loop) {	// at this point user_id is the actual logged in users id
	chatAjax(user_id);	
	if(typeof(t) !== 'undefined')  clearTimeout(t);
	t = setTimeout("chat_check(" + user_id + ", true)",5000);	// every 5 seconds
}


function chatAjax(user_id){
	var queryString = "user=" + user_id;
	var loggedInUser = user_id;	// store actual logged in users id to pass onto end chat text in msg-check.js

	// use jQuery to send user data to mysql query and retreive response via json
	// then display appropriate popup box
	// see http://api.jquery.com/jQuery.getJSON/
	$.ajax({
		type: "GET",
		url: "/scripts/fba-chat/chat-check.ajax.php",
		cache: false,
		data: queryString,
		dataType: 'json',		
		success: function(text){
			if (text['msg'] && (!document.getElementById('fba-chat')) ) {
				if (text['msg'] == 'request' || text['msg'] == 'confirmation') {
					// display chat request popup				
					$('#chat-alert').html("<span class=\"boldgrey\">" + text['user_name'] + "</span> wants to chat with you.<br /><br /><a onClick=\"chatConfirm(" + text['user'] + ",'" + text['user_name'] + "'," + text['friend_ID'] + ",'" + text['friend_user'] + "', 'accept', '" + loggedInUser + "')\" class='small-button'>Accept</a><a onclick=\"denyRequest(" + text['user'] + ",'" + text['friend_ID'] + "')\" class='small-button'>Decline</a><a onclick=\"blockPopup(" + text['user'] + "," + text['friend_ID'] + ", '" + text['friend_user'] + "')\" class='small-button'>Block</a>");
					if(typeof(m) !== 'undefined') clearTimeout(m);	// clear any previous chat to avoid flashing between different chats
					$('#chat-alert').show();
					// if window not in focus then flash chat request in title and play bell sound
					if(!hasfocus) flashTitle(text['user_name'], 'chat');					
				}
			} else if (text['msg'] == 'active') {
				// sometimes msg check loop stops mid chat so this fires it up again
				if(typeof(m) !== 'undefined') clearTimeout(m);	// clear any previous chat to aviod possible conflicts
				msg_check(user_id, friend_id, user_name ,friend_name, loggedInUser);
			} else {
				//$('#chat-alert').hide();
				//document.getElementById('chat-alert').innerHTML = "";
			}
		}
	});	
}  


// user wants to ignore chat request so close chat request window and delete msg from database
function denyRequest(user_id, friend_id) {
		var queryString = "user_id=" + user_id + "&friend_id=" + friend_id;
		bellPlayed = false;
	
		$.ajax({
			type: "POST",
			url: "/scripts/fba-chat/chat-deny.ajax.php",
			data: queryString,
			success: function(){
				$('#chat-alert').hide();
			}
		});
		return false;
}

// show block popup and send back deny request msg to chat initiator
function blockPopup(user_id, friend_id, friend_user) {
		var queryString = "user_id=" + user_id + "&friend_id=" + friend_id + "&type=deny";
		bellPlayed = false;
		
		// first remove the chat request
		$.ajax({
			type: "POST",
			url: "/scripts/fba-chat/block-user.ajax.php",
			data: queryString,
			success: function(){
				// now show block popup
				$('#chat-alert').html('<div id="chat-close" style="margin: -4px -4px 0 0;"><img onclick="$(\'#chat-alert\').hide();" src="/images/buttons/chat-close-sprite.png" width="20" title="Close (without blocking)" alt="Close (without blocking)" id="chat-close-nosprite" /></div><br /><p><b class="blue">Permenantly Block User:</b></p><p>If you wish to report abuse from this user to the FBA team please include a note here:</p><textarea id="abuse-report" rows="4" cols="20"></textarea><p><a onclick="blockUser(' + user_id + ',' + friend_id + ', \'' + friend_user + '\')" class="block-user">Block User</a></p>');
				$('#chat-alert').show();
			}
		});
}

// add chat requestee to user's blocked users list
function blockUser(user_id, friend_id, friend_user) {
		var abuse = $('#abuse-report').val();
		var queryString = "user_id=" + user_id + "&friend_id=" + friend_id + "&type=block&abuse=" + abuse;

		// first remove the chat request
		$.ajax({
			type: "POST",
			url: "/scripts/fba-chat/block-user.ajax.php",
			data: queryString,
			dataType: 'json',	
			success: function(text){
				if (text['abuse'] == 'reported') {
					$('#chat-alert').html('<p><b class="blue">' + friend_user + '</b> has been blocked</p><p>The FBA team have been alerted.</p>');
					$('#chat-alert').delay(4000).fadeOut(800);
				} else {
					$('#chat-alert').html('<p><b class="blue">' + friend_user + '</b> has been blocked</p>');
					$('#chat-alert').delay(4000).fadeOut(800);
				}
				clearTimeout(w);	// stop previous whos online timers
				refreshWhosOnline(true);				
			}
		});
}


function limitName(username) {
	var maxlen = 24;
	if (username.length > maxlen) username = username.substring(0,maxlen - 3) + '...';
	return username.toLowerCase();
}


function chatConfirm(user_id, user_name, friend_id, friend_name, type, loggedInUser){
	bellPlayed = false;

	// set up chat form headers
	if (type == 'accept') {
		$('#chat-friend-name').html(limitName(user_name));
		$('#chat-close').html('<img onclick="endChat(\''  +  user_id  +  '\', \''  +  user_name  +  '\', \''  +  friend_id  +  '\', \''  +  friend_name  +  '\')" src="/images/buttons/chat-close-sprite.png" width="20" title="End Chat" alt="End Chat" id="chat-close-sprite" />');
		var queryString = "user_id=" + user_id + "&user_name=" + user_name + "&friend_id=" + friend_id + "&friend_name=" + friend_name + "&type=" + type;
		
	}	else if (type == 'request') {
		$('#chat-friend-name').html(limitName(friend_name));
		$('#chat-close').html('<img onclick="endChat(\''  +  friend_id  +  '\', \''  +  friend_name  +  '\', \''  +  user_id  +  '\', \''  +  user_name  +  '\')" src="/images/buttons/chat-close-sprite.png" width="20" title="End Chat" alt="End Chat" id="chat-close-sprite" />');
		var queryString = "user_id=" + user_id + "&user_name=" + user_name + "&friend_id=" + friend_id + "&friend_name=" + friend_name + "&type=" + type;
	}
	
	$('#ajaxchat-messages-container').html('');	// clear any old chats from message container
	$.ajax({
		type: "GET",
		url: "/scripts/fba-chat/chat-accept.ajax.php",
		cache: false,
		dataType: 'json',
		data: queryString,
		success: function(text){
			if (text['msg'] == 'ended') {
				$('#chat-alert').html('SOrry, but <b class="blue">' + friend_name + '</b> has meanwhile ended this chat.').show().delay(6000).fadeOut(800);
			} else {
			
				// set up and display main part of chat form

				var form_text;
				form_text = '<form method="post" name="form" class="ajaxchat-form" action="">';
				form_text += '<input type="text" id="chat-message" name="message" class="ajaxchat-input" maxlength="255" />';
				if (type != 'accept') {
					form_text += '<input type="hidden" id="friend_id" name="friend_id" value="' + friend_id + '">';
					form_text += '<input type="hidden" id="friend_name" name="friend_name" value="' + friend_name + '">';
					form_text += '<input type="hidden" id="user_id" name="user_id" value="' + user_id + '">';
					form_text += '<input type="hidden" id="user_name" name="user_name" value="' + user_name + '">';
				} else {
					form_text += '<input type="hidden" id="friend_id" name="friend_id" value="' + user_id + '">';
					form_text += '<input type="hidden" id="friend_name" name="friend_name" value="' + user_name + '">';
					form_text += '<input type="hidden" id="user_id" name="user_id" value="' + friend_id + '">';
					form_text += '<input type="hidden" id="user_name" name="user_name" value="' + friend_name + '">';	
				}
				form_text += '<input id="submit" type="submit" value=">" class="submitmsg"/>';
				form_text += '</form>';
				
				$('#chat-form').html(form_text);
				
				// max chat popup
				$('#popup-chat').show();
				$('#popup-chat').animate({
				height: "250", 
				}, 700, function() {
					// change min/max header once animation complete
					$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header.png)");
				});
					
				$('#chat-message').focus();
				$('#whos-online-popup').animate({height: "18"}, 500, function() {
					// change min/max button once animation complete
					$('#whos-online-header').css("background-image","url(../../images/buttons/fba-chat-header-max.png)");
				});
				$('#chat-alert').fadeOut(800);

				// use ajax to get form input and send to database - requires jquery
				// http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
				$(function() {
					$(".ajaxchat-form").submit(function() {
						var user_id = $("#user_id").val();
						var friend_id = $("#friend_id").val();
						var user_name = $("#user_name").val();
						var friend_name = $("#friend_name").val();
						var message = $("#chat-message").val();
						var queryString = "user_id=" + user_id + "&friend_id=" + friend_id + "&user_name=" + user_name + "&friend_name=" + friend_name + "&message=" + message;

						$.ajax({
							type: "POST",
							url: "/scripts/fba-chat/msg-check.ajax.php",
							data: queryString,
							cache: false,
							success: function(){
								document.getElementById('chat-message').value = "";
							}
						});
						return false;
					});
				});
				
				msg_check(user_id, friend_id, user_name ,friend_name, loggedInUser);			

			}
		}
	});	
}


function endChat(user_id, user_name, friend_id, friend_name){
	var queryString = "user_id=" + user_id + "&friend_id=" + friend_id + "&user_name=" + user_name + "&friend_name=" + friend_name;

	$.ajax({
		type: "POST",
		url: "/scripts/fba-chat/end-chat.ajax.php",
		cache: false,
		data: queryString,
		success: function(){
			$('#chat-alert').fadeOut(800);
			document.getElementById('popup-chat').style.display = 'none';
			$('#popup-chat').unbind('toggle');
			clearTimeout(m);
		}
	});
	return false;	
}

$(document).ready(function() {

	/* add sound files to sound divs */
		
	$('#chat-bell-wrap').html('<audio id="chat-bell" preload="auto"><source src="/scripts/fba-chat/chat-bell.ogg"><source src="/scripts/fba-chat/chat-bell.mp3"></audio><audio id="msg-bell" preload="auto"><source src="/scripts/fba-chat/message-bell.ogg"><source src="/scripts/fba-chat/message-bell.mp3"></audio>	');	

	/******************
	 * pop up controls
	 */

	// custom toggle for chat box based on header clicks
	// allows for animations called elsewhere
	// more fail safe than toggle
	// use multiple selectors to repeat for min/max button
 
	$('h2#chat-friend-name, #chat-min').click(function() {
		if ($('#popup-chat').height() == 18) {
			$('#popup-chat').animate({
			height: "250", 
			}, 500, function() {
				// change min/max once animation complete
				$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header.png)");
				$('#chat-header').css({backgroundPosition: '0px 0px'});
			});
		}
		else {
			$('#popup-chat').animate({
			height: "18", 
			}, 500, function() {
				// change min/max and fade out alert box once animation complete
				$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header-max.png)");
				$('#chat-header').css({backgroundPosition: '0px 0px'});
				$('#chat-alert').fadeOut(800);
			});
		}
	});

	// hover over close button
	$('#chat-close-wrapper').hover(
	function() {
		// hover the min/max button
		if ($('#popup-chat').height() == 18)
			$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header-max-close-hover.png)");
			else 
			$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header-close-hover.png)");
	},
	function () {
		// unhover the min/max button
		if ($('#popup-chat').height() == 18)
			$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header-max.png)");
			else 
			$('#chat-header').css("background-image","url(../../images/buttons/fba-chat-header.png)");
	});	
	
	$('#chat-header').hover(function() {
		$(this).css({backgroundPosition: '0px -32px'});
	}, function() {
		$(this).css({backgroundPosition: '0px 0px'});
	});	
	
});

		
		
