	$(document).ready(function(){
		// Initial
		// username array
		var user_arr = new Array();
		user_arr.push($('#info-id-accountlogin-name').text());
		// realname array
		var realname_arr = new Array();
		realname_arr.push('Tôi');

		loadlistFriends();
		
		function loadlistFriends() {
			$.ajax({
				type: "POST",
				url: "getlistfriendsacc",
				dataType: "json",
				success: function(response){
					if(response != "null") {
						$.each(response, function(entryIndex, entry){
							user_arr.push(entry['id']);
							realname_arr.push(entry['realname']);
						});
					}
				}
			});
		}	
		/////////////////////
		
		$("#btn-show-msgofflinex").click(function(){
			$.ajax({
				type: "POST",
				url: "getMsgOffline",
				beforeSend:  function() {
					$(".loading").show();
				},
				success: function(res){
					$(".loading").hide();
					$(".messagex-resultx-line, .friendrequestx-resultx-other").remove();
					var data = $.parseJSON(res);
					var amount = "0";
					$.each(data, function(entryIndex, entry){
						insertRow(entryIndex, entry.sender, entry.receiver, entry.content, entry.date);
						amount = "1";
					});
					if (amount == "0")
						$(".message-notif").append('<div class="friendrequestx-resultx-other">Không có tin nhắn nào</div>');
				}
			});	
		});
		
		function insertRow(email, fullname, avatar, content, amount){
			if (amount == "1") amount = "";
			else amount = ' (' + amount + ')';
			var html = '<div  title="Xem tin nhắn của ' + fullname + '" user="' + email + '" class="messagex-resultx-line">';
			html +=  '<div class="searchingx-result-user-avatar"><img class="bdrad2" src="' + avatar + '"/></div>';
			html +=  '<div class="searchingx-result-user-info-noti-friend"><b>' + fullname  + amount + '</b><br><span class="otrif">' + content + '</span></div>';
			html +=  '</div>';
			$(".message-notif").append(html);
		}
		
		// Xem tin nhắn
		$(document).on("click", ".messagex-resultx-line", function(){
			var receiver = $(this).attr("user");
			
			//********* Set viewed
			$.ajax({
				type: "POST",
				url: "setViewedOfflineMsg",
				data: "from=" + receiver
			});
			//*********
			
			var con = true;
			$(".chat-editor").each(function(){
				if ($(this).attr("receiver") == receiver) {
					$(this).focus();
					con = false;
					return false;
				}
			});
			if (con)
				openChatWin($('#info-id-accountlogin-name').text(), receiver, "");
			
			if ($("#btn-show-msgofflinex").text() != "") $("#btn-show-msgofflinex").html('<span>' + (parseInt($("#btn-show-msgofflinex").text()) - 1) + '</span>');
			if ($("#btn-show-msgofflinex").text() == "0") $("#btn-show-msgofflinex").empty();
			$(this).fadeOut(400, function(){
				$(this).remove();
				if ($("#btn-show-msgofflinex").text() == "")
					$(".message-notif").append('<div class="friendrequestx-resultx-other">Không có tin nhắn nào</div>');
			});
		});
		
		function openChatWin(from, to, content){
			$.ajax({
				type: "POST",
				url: "emoticon.jsp",
				success: function(res){	
					var html = '<div class="chatbox-window"><div class="chatbox-title"><div class="chatbox-username"><span id="stt_icon_' + replaceSpace(to) + '"></span> ' + getRealName(to);
					html += '</div><div class="chatbox-close"><span title="Thoát" class="chatbox-close-button">X</span></div></div><div class="chatbox-content" id="window' + replaceSpace(to) + '"><div class="chatbox-msg">' + content;
					html += '</div></div><div class="chatbox-posting"><hr class="hr-chat-separation">';
					html += '<textarea spellcheck="false" class="chat-editor" receiver="' + to + '" sender="' + from + '" autofocus></textarea>';
					html += res + '</div></div>';
					$(document.body).append(html);
					loadMessage(to, 0);
					scrollTopEvent();
					fixedChatWinPos();
				}
			});
		}
		
		function replaceSpace(content){
			content = content.replace(".", "--");
			return content.replace("@", "-");
		}
		
		function replaceToOriginal(content){
			content = content.replace("--", ".");
			return content.replace("-", "@");
		}
		
		// Get họ tên
		function getRealName(user){
			var rname = "";
			for (var i = 0; i < user_arr.length; i++){
				if (user_arr[i] == user){
					rname = realname_arr[i];
					break;
				}
			}
			return rname;
		}
		
		function loadMessage(to, offset){
			var rows = "";
			$.ajax({
				type: "POST",
				url: "getChatMsg",
				data: "receiver=" + to + "&offset=" + offset,
				beforeSend: function(){
					$("#window" + replaceSpace(to)).children(".chatbox-msg-header").html('<img src="images/loading-small.gif">');
				},
				success: function(res){
					var data = $.parseJSON(res);
					rows += data[0].id; // Header
					for(var i = 1; i < data.length; i++){
						rows += '<div class="chatbox-msg"><b>' + getRealName(data[i].sender) + '</b> ' + data[i].content + '<br><span class="system-time">' + data[i].date + '</span><hr class="hr-chat-content"></div>';
					}
					$("#window" + replaceSpace(to)).prepend(rows);
					$("#window" + replaceSpace(to)).animate({ scrollTop: $("#window" + replaceSpace(to)).height() }, 1);
				}
			});
		}
		
		// Autoload msg khi scroll top
		function scrollTopEvent(){
			$(".chatbox-content").unbind("scroll");
			$(".chatbox-content").scroll(function(){
				if ($(this).scrollTop() == 0){
					var receiver = $(this).attr("id");
					var offset = $(this).children(".chatbox-msg-header").attr("new");
					if (offset != "root"){
						$(this).children(".chatbox-msg-header").remove();
						loadMessage(replaceToOriginal(receiver.substring(6, receiver.length)), offset);
					}
				}
			});
		}
		
		// Fix cửa sổ chat
		function fixedChatWinPos(){
			var temp = 230;
			$(".chatbox-window").each(function() {
				$(this).css("margin-right", temp);
				temp += 260;
			});
		}
	});