/*

VERSION TALKLIFTS 
updates: return false after every on click event


dazines chat interface

settings:
ajaxPath - standard ajax calls use the format ajax.php?function=function_name
			for code igniter it will be ajax/function_name
	
to dos:
send online friends ids with every request for new messages so we know if the message is coming from a new user
update users list
1. maybe I can store current users online in sessions so i don't have to send nothing with ajax 
2. maybe I get messages and if someone is not on the list I get data about this user with another ajax call (complicated)

3. I split request for new messages in two - first get messages from users I already have on the list
	and later get messages from those I don't - this way it's easy to determine who's just got online (or is offline) and send this data back

ignore users offline (long time not seen thing)
POSSIBLE STAUTUSES (i should not send it back as 'real' status  only 'calculated' ) online, offline and ghost mode (invisible)
*/
(function($) {
	$.dazchat = function(settings) {
		var settings = $.extend($.dazchat.settings, settings||{});
		
		var statusOpened = false;
		var friendsOpened = false;
		
		var statuses = new Array();
		var users = new Array();
		var currentStatus = -1;
		var activeChatter = -1;
		var chatters = new Array();
		var chatters_count = 0;
		//this is the last id of the message you've recieved - I'm sending it with a request to only get new messages
		var update_id = 0;
		var user;
		var initialized = false;
		var messagesStopped = false;
		
		
		var notes_users = new Array();
		var notes = new Array();
		
		$('body').append('<div id="dazchat_filler"></div><div id="dazchat"><div id="log"></div><div id="dazchat_chatters"></div><div id="dazchat_friends_button"><span id="dazchat_friends_online"></span><span id="dazchat_new_message" style="display:none;">!!!</span></div><div id="dazchat_friends"><a href="#" id="dazchat_friends_close">close</a><br /><br /><div id="dazchat_friends_list"></div></div><div id="dazchat_status_button"></div><div id="dazchat_status"><a href="#" id="dazchat_status_close">close</a><br /><br /></div></div>');
		$('#dazchat_friends').hide();
		/* INTERFACE */
		var ie6 = ($.browser.msie && parseInt($.browser.version) < 7);
		if(ie6) {
			//log('Internet Explorer 6 (or even worse s**t) detected<br />');
			//alert('You are using Internet Explorer 6 (or worse)\nYour ip number has been sent to ie6morons.com database');
			log('Creating UI');
			$('#dazchat').css({	height:settings.barHeight,
								position:'absolute',
								top:0,
								right:'50%',
								marginRight:'-275px',
								display:'block',
								zIndex:'1000'
								});
			
			$('#dazchat_filler').css({
								height:settings.barHeight,
								position:'absolute',
								top:0,
								left:0,
								display:'block',
								zIndex:'999',
								opacity:0.4
								});
			scroll_dazchat();
			$(window).scroll(function() {
					scroll_dazchat();
			});
			$(window).resize(function() {
					resize_dazchat();
			});
		} else {
			$('#dazchat').css({width:'100%',
							  	height:settings.barHeight,
								position:'fixed',
								bottom:'0',
								right:'50%',
								marginRight:'-275px',
								display:'block',
								zIndex:'1000'
								});
			$('#dazchat_filler').css({width:'100%',
							  	height:settings.barHeight,
								position:'fixed',
								bottom:'0',
								left:0,
								display:'block',
								zIndex:'999',
								opacity:0.4
								});
		}
		
		function scroll_dazchat() {
			var scrollTop = $(window).scrollTop();
			var scrollLeft = $(window).scrollLeft();
			var windowHeight = $(window).height();
			var windowWidth = $(window).width();
			$('#dazchat').css({marginTop:scrollTop + windowHeight - settings.barHeight,
							 	marginLeft:scrollLeft,
								width:windowWidth});
			$('#dazchat_filler').css({marginTop:scrollTop + windowHeight - settings.barHeight,
							 	marginLeft:scrollLeft,
								width:windowWidth});
		}
		function resize_dazchat() {
			window.scroll(0,0);
			var windowHeight = $(window).height();
			var windowWidth = $(window).width();
			$('#dazchat').css({marginTop:windowHeight - settings.barHeight,
							  width:windowWidth});
			$('#dazchat_filler').css({marginTop:windowHeight - settings.barHeight,
							  width:windowWidth});
		}
		/* USER INTERFACE FUNCTIONS */
		function openFriends() {
			$('#dazchat_friends').fadeIn(function() {
					friendsOpened = true;																  
			});
			//hide the info about a new message
			$('#dazchat_new_message').hide();
		}
		function closeFriends() {
			//var height = $('#dazchat_friends').outerHeight();
			$('#dazchat_friends').fadeOut(function() {
				friendsOpened = false;																  
			});		
		}
		function openStatus() {
			$('#dazchat_status').animate({height:120},function() {
					statusOpened = true;																  
			});
		}
		function closeStatus() {
			var height = $('#dazchat_status').outerHeight();
			$('#dazchat_status').animate({height:0},function() {
				statusOpened = false;																  
			});	
		}
		
		function changeStatus(status_id) {
		
			log("changin status" + status_id);
			if(currentStatus!=status_id) {
				//proceed only if status has changed
				if(status_id=='1') {
					//if user got online start procedure
					if(!initialized) {
						initialized = true;
						get_online_users();
					} else {
						refresh_chatters();
					}
					if(messagesStopped) {
						messagesStopped = false;
						refreshMessagesList();
					}
					
					$('#dazchat_friends_button').fadeIn();
					$('.dazchat_note').fadeIn();
				} else if(status_id=='0') {
					//if user got offline stop everything										
					$('.dazchat_note').fadeOut();
					$('#dazchat_friends').fadeOut();
					friendsOpened = false;
					$('#dazchat_friends_button').fadeOut();
					$('.dazchat_window').fadeOut();
				}
				//update database
				var data = new Object();
				data.status_id = status_id;
				$.post(settings.ajaxPath + 'set_status',data);
				currentStatus = status_id;
//				$('#dazchat_status_button').html(statuses[status_id]);
				$('#dazchat_status_button').html('quit live chat');
			}
		}
		$('#dazchat_status_button').click(function () {
			//if(statusOpened) {closeStatus(); } else {openStatus();}
			
			//we should ask user if he really wants to turn the chat off					
			$.fumodal({	
				width:300,
				height:135,
				style:true,
				url:'http://www.amplifytrading.com/ajax/livechat_logout',
				title:'<b>Log out from the chat?</b>'
			});
/*			
			
			if(currentStatus==1) {
				changeStatus(0);	
			} else {
				changeStatus(1);
			}*/
			return false;
		});
		$('#dazchat_status_close').click(function() {
			closeStatus();
			return false;
		});
		$('#dazchat_friends_button').click(function() {
			//alert(friendsOpened);
			if(friendsOpened) {closeFriends(); } else {openFriends();	}							
			return false;
		});
		$('#dazchat_friends_close').click(function() {
			closeFriends();				
			return false;
		});
		
		function activate_chatter(id) {
			//log('activating chatter:' + chatters[id].login);
			//log('last read message' + chatters[id].last_message_id);
			//log('current message' + chatters[id].current_message_id);
			if(id!=activeChatter) {
				activeChatter = id;
				var data = {sender_id:id,message_id:chatters[id].current_message_id};
				$.post(settings.ajaxPath + 'set_last_message', data);
				$('.dazchat_window').fadeOut();
				$('.dazchat_window#' + id).fadeIn();
/*				if ($('.dazchat_window#' + id + ' .dazchat_window_messages')[0].scrollTop != $('.dazchat_window#' + id + ' .dazchat_window_messages')[0].scrollHeight) {
					$('.dazchat_window#' + id + ' .dazchat_window_messages')[0].scrollTop = $('.dazchat_window#' + id + ' .dazchat_window_messages')[0].scrollHeight;
				}*/
			}
		}
		
		function deactivate_chatter(id) {
			activeChatter = -1;
			$('.dazchat_window#' + id).fadeOut();
		}
		/* THIS IS WHERE ALL THE FUN BEGINS */
		//first get all possible statuses, user's status, users online and messages + all that shit
		
		$.post(settings.ajaxPath + 'get_statuses',{},function(data) {
			var st = data['statuses'];
			$(st).each(function(index,status) {
				statuses[status.id] = status.name;
				$('#dazchat_status').append('<a href="#" id="status_'+status.id+'" class="dazchat_change_status">'+status.name+'</a><br />');
			});
			changeStatus(data['user']['status_id']);
			
			//this is not working in its original form (now you can only toggle status)
			$('.dazchat_change_status').click(function () {
				var status_id = $(this).attr('id').substr(7);
				//var data = new Object();
				//data.status_id = status_id;
				changeStatus(status_id);
				closeStatus();
				//$.post(settings.ajaxPath + 'set_status',data);
				return false;
			});
			
			user = data['user'];
			log('user Id:' + user.id);
			log('user Login:' + user.login);
		},'json');
		
		// add user to list
		function append_chatter(user) {
			$('#dazchat_friends_list').append('<div id="' + user.id + '" class="dazchat_user_button"><span class="dazchat_chatter_name">' + user.login + '</span><span class="dazchat_new_message" style="display:none;">!!!</span></div>');	
		}
		
		function click_chatter() {
			var id = $(this).attr('id');
			remove_note(id);
			closeFriends();
			activate_chatter(id);
		}
		
		function over_chatter() {	$(this).css({cursor:'pointer'});}
		function out_chatter() {	$(this).css({cursor:'default'});}
		
		function get_online_users() {
			log('getting online users..');
			$.post(settings.ajaxPath + 'get_online_users',{},function(data) {
				var users = data['users'];
				$(users).each(function(index,user) {
					append_chatter(user);
					add_chatter(user);
					
					//we can show the chatter window with the welcome message
					if (settings.welcome_msg == true) {
						
						settings.welcome_msg = false;
					}							
					
				});
				count_online_chatters();
				setInterval(refresh_chatters,settings.usersRefresh);
				
				//get the typing activity
				setInterval(get_typing, 3000);
				refreshMessagesList();
				$('.dazchat_user_button').hover(over_chatter,out_chatter);
				$('.dazchat_user_button').click(click_chatter);
			},'json');
		}
		
		//gets admin's typing state
		function get_typing() {
			var user_window = $("div.dazchat_window_title").parent().parent();
			var u_id = user_window.attr('id');
			$.post(settings.ajaxPath + 'get_typing_activity', {id: u_id}, function(result) {
				$("div.dazchat_window_title").html(result);
			});
		}
	
		function create_chat_window(user) {
			$('#dazchat').append('<div id="'+user.id+'" class="dazchat_window" style="display:none;"><div class="dazchat_window_wrapper"><div class="dazchat_window_messages"></div><form name="dazchat_send_form" class="dazchat_send_form" action="#" method="post" enctype="multipart/form-data" target="_self"><input type="text" name="dazchat_message_input" class="dazchat_message_input l" value="" /><input type="submit" class="dazchat_send_button r" value="Send" /></form></div><div class="dazchat_window_bar"><div class="dazchat_window_title">'+user.login+'</div><div class="dazchat_window_close"></div></div></div>');
			
			/* $('#dazchat').append('<div id="'+user.id+'" class="dazchat_window" style="display:none;"><div class="dazchat_window_wrapper"><div class="dazchat_window_messages"></div></div><div class="dazchat_window_bar"><div class="dazchat_window_title">'+user.login+'</div><div class="dazchat_window_close"></div></div></div>'); */
			
			
			var parent = $('.dazchat_window#' + user.id);
			//temporary position windows next to each other
			//parent.css({right:(chatters_count-1)*250});
			
			$('.dazchat_window_close',parent).click(function() {
				var user_window = $(this).parent().parent();
				var id =  user_window.attr('id');
				log(id);
				deactivate_chatter(id);
			});
			
			$('.dazchat_window_name',parent).click(function() {
				//log('activating id:' + $(this).parent().attr('id'));										  
			});
			
			$('.dazchat_send_form',parent).submit(function() {
				var parent = $(this).parent().parent();
				var data = new Object();
				data.message = $('.dazchat_message_input',parent).val();
				$('.dazchat_message_input',parent).val('');
				data.reciever_id = parent.attr('id');
				log('sending message recipient:' + data.reciever_id);
				log('message:' + data.message);
				//$.post(settings.ajaxPath + 'send_message',data,refreshMessages);
				$.post(settings.ajaxPath + 'send_message',data);
				return false;
			});
		}
		
		function add_chatter(user) {
			if(!chatters[user.id]) {
				chatters[user.id] = user;
				chatters[user.id].online = true;
				//this is a current message id (the one which is waiting to be shown because the window is not active)
				chatters[user.id].current_message_id = user.last_message_id;
				chatters_count ++;
				create_chat_window(user);
				log('creating chatter:'+user.login);
			} 
		}
		
		function remove_chatter(id) {
			$('#chatter_' + id).remove();
		}
		
		function refresh_chatters() {
			if(currentStatus=='1') {
				var data = new Object();
				data.chatters = get_chatters_ids();
				//log('refreshing users ' + data.chatters);
				$.post(settings.ajaxPath + 'get_online_users_refresh',data,function(data) {
					var online = data['online'];
					var offline = data['offline'];
					if(online.length>0) {
						for(index in online) {
							log('user online: ' + online[index].id);
							if(chatters[online[index].id]==undefined) {
								//user is not on the list - create it
								//add to the list
									
								//add chat window 
								add_chatter(online[index]);
							} else {
								//user is on the list - just change status
								chatters[online[index].id].online = true;
							}
							append_chatter(online[index]);
							
							$('#dazchat_friends_list #' + online[index].id).hover(over_chatter,out_chatter);
							$('#dazchat_friends_list #' + online[index].id).click(click_chatter);
						}
					}
					if(offline.length>0) {
						for(index in offline) {
							log('user offline: ' + offline[index].id);
							chatters[offline[index].id].online = false;
							//remove from the list
							$('#dazchat_friends_list #' + offline[index].id).remove();
						}
					}
					count_online_chatters();
					
						//window.setTimeout(refresh_chatters, settings.usersRefresh);
					
				},'json');
			}
		}
		
		function count_online_chatters() {
			var online_counter = 0;
			for(var i in chatters) {
				if(chatters[i].online) {
					online_counter ++;
				}
			}
			$('.online_users_count').html(online_counter);
			
			if(online_counter==0) {
				$('#dazchat_friends_button #dazchat_friends_online').html('no contacts');
			} else {
				$('#dazchat_friends_button #dazchat_friends_online').html('contacts online (' + online_counter + ')');
			}
		}
		//this will get all the chatters we've already gathered information about because they were online or we got message from them
		function get_all_chatters() {
			var chatters_array = new Array();
			for(var index in chatters) {
				chatters_array.push(chatters[index].id);
			}
			var chatters_string = chatters_array.join(',');
			return chatters_string;
		}
		//this function only returns online chatters
		function get_chatters_ids() {
			var chatters_array = new Array();
			for(var index in chatters) {
				if(chatters[index].online) {
					chatters_array.push(chatters[index].id);
				}
			}
			var chatters_string = chatters_array.join(',');
			return chatters_string;
			//log('chatters:' + chatters_string)
		}
		//updates last message read from particular user
		function set_last_message(sender_id) {
			var data = {sender_id:sender_id};
			$.post(setting.ajaxPath + 'set_last_message',data,function(data) {
																	   
			},'json');
		}
		
		function refreshMessagesList() {
			var data = new Object();
			data.update_id = update_id;
			data.chatters = get_chatters_ids();
			$.post(settings.ajaxPath + 'get_messages',data,function(data) {
				var messages = data.messages;
				//log('recieving messages:' + messages.length);
				var user_message = true;
				for(index in messages) {
					var message = messages[index];
					if(message.sender_id==user.id) {
					
						var login_string = user.login;
						if ((login_string == 'undefined') || (user.login == null)) {
							login_string = 'you';
						}						
						
						var chat_messages = $('.dazchat_window#'+ message.reciever_id +' .dazchat_window_messages');
						$(chat_messages).append('<p class="chat_message_time">' + login_string + ' - ' + message.time +'</p>' + message.content + '<br /><br />');
						update_id = message.id;
/*						if ($(chat_messages).scrollTop != $(chat_messages).scrollHeight) {						
							$(chat_messages).scrollTop = $(chat_messages).scrollHeight;
						}*/
					} else {
						var chat_messages = $('.dazchat_window#'+ message.sender_id +' .dazchat_window_messages');						
						$(chat_messages).append('<p class="chat_message_time">' +chatters[message.sender_id].login + ' - ' + message.time + '</p>' + message.content + '<br /><br />');
/*						if ($(chat_messages).scrollTop != $(chat_messages).scrollHeight) {
							$(chat_messages).scrollTop = $(chat_messages).scrollHeight;						
						}*/
						update_id = message.id;
						var sender = chatters[message.sender_id];
						//if the recieved message is newer than the last read then show alert
						sender.current_message_id = message.id;
						
						if(message.id>sender.last_message_id) {
							//HERE IS THE NEW MESSAGE NEW MESSAGE NEW MESSAGE NEW MESSAGE NEW MESSAGE NEW MESSAGE NEW MESSAGE NEW MESSAGE
							//log('new message from:' + sender.login);
							//$('#dazchat_new_message').show();
							notify(sender);
							
						}
						user_message = false;
						//this will show you information about a new message
						//an here i check which window is active and send the last message id read from particular user
						if(message.sender_id==activeChatter) {
							log('message has been read');
							//log('updating last read message');
							//chatters[message.sender_id].last_message_id = 
							var data = {sender_id:message.sender_id,message_id:message.id};
							$.post(settings.ajaxPath + 'set_last_message', data);
						}
						
						//$('#users_list .chat_user#'+message.sender_id+' .new_message').show();
						//log('new message from:'+message.sender_id);
					}
					if(messages!=undefined && messages.length>0 && !user_message) {
						//play a new message sound
						//$('#chat_sound')[0].playSound();
					}
					//scroll window to the bottom
					//log('scrolling window: ' + $(chat_messages)[0].scrollTop);
					$(chat_messages)[0].scrollTop = $(chat_messages)[0].scrollHeight; 
				}
				if(currentStatus=='1') {	//refresh only if user is online
					window.setTimeout(refreshMessagesList, settings.messagesRefresh);											
				} else {
					messagesStopped = true;	
				}
				/*
				$('.dazchat_window_messages').each(function(i,w) {
					w.scrollTop = 100000000;
				});
				*/
			},'json');
		}
					
		function notify(sender) {
			//log('new message from:' + sender.login);
			//one user - one note
			log('notes:' + $('#dazchat_note_'+sender.id).size());
			
			if($('#dazchat_note_'+sender.id).size()==0) {
				var notes_count =  $('.dazchat_note').size();
				log('notes number:'+ notes_count);
				var new_note_pos = (notes_count*33)+33;
				$('#dazchat').append('<div id="dazchat_note_'+sender.id+'" class="dazchat_note" style="display:none;bottom:'+new_note_pos+'px">message: '+sender.login+'</div>');
			
			activate_chatter(sender.id);
			
				$('#dazchat_note_'+sender.id).click(function() {
					var user_id = $(this).attr('id').substr(13);
					activate_chatter(user_id);
					remove_note(user_id);
				});
				$('#dazchat_note_'+sender.id).fadeIn(500);
			}
		}
		
		function remove_note(user_id) {
			var el = $('#dazchat_note_'+user_id);
			while(el.next().attr('id')!=undefined) {
				el = el.next();
				current_pos = parseInt(el.css('bottom'));
				el.animate({bottom:current_pos-30});
			}
			
			$('#dazchat_note_'+user_id).remove();
		}
		
		function log(message) {
			$('#log').append(message+'<br />');	
			$('#log')[0].scrollTop = $('#log')[0].scrollHeight; 
		}
	}
	
	$.dazchat.add_to_friends = function(friend_id) {
		var data = new Object();
		data.friend_id = friend_id;
		$.post($.dazchat.settings.ajaxPath + 'add_to_friends', data, function(result) {
																		
		},'json');
	}
	
	$.dazchat.settings = {	barHeight:30,
							ajaxPath:'includes/ajax.php?function=',
							messagesRefresh:3000,
							usersRefresh:10000}
}) (jQuery);