$(document).ready(function () {
	var mChatCount = 0;
	var mRealtimeChat = false;
	var mChatCollection = new Array();
	var mMessageCollection = [];
	var mLangPack = "";
	
	Array.prototype.remove = function(value) {
		if (this.indexOf(value)!==-1) {
			this.splice(this.indexOf(value), 1);
			return true;
		} else {
			return false;
		};
	}

	var systemCHAT = {
		initializeBase: function() {
			$.ajax({
				url: "system.ajax/ajax.handle.language.pack.php",
				type: "POST",
				dataType: "JSON",
				data: { },
				success: function(ajaxResponse) {
					mLangPack = ajaxResponse.langPack;
					systemCHAT.refreshChatWindowResize();
					systemCHAT.refreshChatWindowScroll();
					systemCHAT.refreshChatWindows();
					
					systemCHAT.closeWindow();
					systemCHAT.hideWindow();
					systemCHAT.openWindow();
					
					systemCHAT.outgogingChatMessage();
					
					if(mRealtimeChat) {
					
					} else {
						systemCHAT.AJAXRefreshChat();
					}
					
					// systemCHAT.initializeFriendsWindow();
					systemCHAT.positionateFriendsWindow();
					systemCHAT.switchFriendsWindow();
					systemCHAT.loadFriendsList();
					
					// Mini events
					systemCHAT.bodyClick();
					systemCHAT.searchFriend();
					systemCHAT.removeSearchName();
					systemCHAT.reopenChatWindows();
					systemCHAT.initializeEvents();
					systemCHAT.loadChatButtons();
				}
			});
		},
		
		initializeFriendsWindow: function () {
			$("body").append("<div class=\"eliteChatFriends hidden-xs\"><div class=\"eHead\" head-type=\"friends-window\">" + mLangPack.chat.friendswindowtitle + " (<strong id=\"friendsWindowCount\">0</strong>)</div><div class=\"friendsBody\"><ul class=\"list-group\" id=\"friendsWindowList\"></ul></div><div class=\"friendsFooter\"><input id=\"searchChatFriend\" type=\"text\" class=\"form-control\" /></div></div>");
		},
		
		reopenChatWindows: function () {
			$.ajax({
				url: "system.ajax/ajax.handle.chat.windows.php",
				type: "POST",
				dataType: "JSON",
				async: false,
				data: { handleType: -1, windowUser: -1, additionalContent: -1 },
				success: function(jr) {
					var mOutputData = jr.outputData;
					$.each(mOutputData, function(i, object) {
						var mWindowUser = mOutputData[i].WINDOWUSER;
						var mState = mOutputData[i].STATE;
						
						mChatCollection.push(mWindowUser);
						systemCHAT.initializeChatWindow(mWindowUser, mState == 1 ? 1 : 0);
					});
				}
			});
		},
		
		removeSearchName: function () {
			$("body").on("keyup", "#searchChatFriend", function () {
				if($(this).val().length == 0)
					systemCHAT.loadFriendsList();
			});
		},
		
		searchFriend: function () {
			$("body").on("keyup", "#searchChatFriend", function (e) {
				if(e.keyCode == 13) {
					var mContent = $.trim($(this).val());
					if(mContent.length > 0) {
						$("#friendsWindowList").html("<center><img src=\"system.assets/images/loader.gif\" /></center>");
						$.ajax({
							url: "system.ajax/ajax.handle.chat.search.php",
							type: "POST",
							dataType: "JSON",
							data: { nameContent: mContent },
							success: function(jr) {
								$("#friendsWindowList").html(jr.htmlContent);
							}
						});
					}
				}
			});
		},
		
		bodyClick: function() {
			$("body").on("click", ".eBody", function () {
				var mChatBodyId = $(this).attr("chat-body-id");
				$("input[chat-id=\"" + mChatBodyId + "\"]").focus();
			});
		},
		
		loadFriendsList: function () {
			$.ajax({
				url: "system.ajax/ajax.handle.chat.list.php",
				type: "POST",
				dataType: "JSON",
				data: { },
				success: function(jr) {
					$("#chatListCollection").html(jr.htmlContent);
				}
			});
		},
		
		switchFriendsWindow: function() {
			$(this).css("left", ($(window).width() - 225) + "px");
			$("body").on("click", "[head-type]", function () {
				var mFriendsContainer = $(".eliteChatFriends");
				if(mFriendsContainer.attr("window-status") == 1) {
					mFriendsContainer.css("left", ($(window).width() - 225) + "px");
					mFriendsContainer.css("top", ($(window).height() - 40) + "px");
					mFriendsContainer.attr("window-status", 0);
				} else {
					mFriendsContainer.css("left", ($(window).width() - 225) + "px");
					mFriendsContainer.css("top", ($(window).height() - 614) + "px");
					mFriendsContainer.attr("window-status", 1);
				}
			});
		},
		
		initializeChatWindow: function (mUserId, mState) {
			$.ajax({
				url: "system.ajax/ajax.handle.user.fetch.php",
				type: "POST",
				dataType: "JSON",
				data: {	userId: mUserId },
				success: function(jr) {
					$("body").append("<div window-status=\"" + mState + "\" id=\"eliteChatWindow-" + mUserId + "\" chat-window-user=\"" + mUserId + "\" class=\"eChat hidden-xs\"><div class=\"eHead ePadding\">" + jr.fullName + "<i chat-window-id=\"" + mUserId + "\" class=\"eClose glyphicon glyphicon-remove\"></i><i chat-window-id=\"" + mUserId + "\" data-location=\"window-events-" + mUserId + "\" class=\"eHide glyphicon glyphicon-" + (mState == 1 ? "chevron-down" : "chevron-up") + "\"></i></div><div class=\"eBody\" chat-body-id=\"" + mUserId + "\"></div><div class=\"eFooter\"><input chat-id=\"" + mUserId + "\" chat-window-event=\"submitmessage\" data-location=\"footer-input-" + mUserId + "\" type=\"text\" class=\"form-control\" /></div></div>");
					systemCHAT.refreshChatWindows();
					$("input[chat-id=\"" + mUserId + "\"]").focus();
				}
			});
			
			systemCHAT.refreshChatWindows();
		},
		
		AJAXRefreshChat: function () {
			setInterval(function() {
				$(".eChat").each(function () {
					var mUserId = $(this).attr("chat-window-user");
					$.ajax({
						url: "system.ajax/ajax.handle.chat.load.php",
						type: "POST",
						dataType: "JSON",
						data: { receiverUser: mUserId },
						success: function(jr) {
							$("[chat-window-user=\"" + mUserId + "\"] > .eBody").html(jr.chatContent);
							var mLastMessage = $(".messageContent-" + mUserId).last().text();
							if(mMessageCollection[mUserId] !== undefined) {
								if(mMessageCollection[mUserId] !== mLastMessage)
									$("[chat-body-id=\"" + mUserId + "\"]").scrollTop($("[chat-body-id=\"" + mUserId + "\"]")[0].scrollHeight);
							} else $("[chat-body-id=\"" + mUserId + "\"]").scrollTop($("[chat-body-id=\"" + mUserId + "\"]")[0].scrollHeight);
							mMessageCollection[mUserId] = mLastMessage;
							$(".notificationChatCount").fadeOut();
						}
					});
				});
			}, 2500);
		},
		
		AJAXSubmitChat: function (mUserId, mMessage) {
			$.ajax({
				url: "system.ajax/ajax.handle.chat.submit.php",
				type: "POST",
				dataType: "JSON",
				data: { chatMessage: mMessage, receiverUser: mUserId },
				success: function(jr) {
					
				}
			});
		},
		
		incomingChatMessage: function () {
			
		},
		
		outgogingChatMessage: function () {
			$("body").on("keyup", "[chat-window-event=\"submitmessage\"]", function (e) {
				if(e.keyCode == 13) {
					var mUserId = $(this).attr("chat-id");
					var mContent = $(this).val();
					if($.trim(mContent).length > 0) {
						systemCHAT.AJAXSubmitChat(mUserId, mContent);
						$(this).val("");
					}
				}
			});
		},
		
		refreshChatWindows: function () {
			mChatCount = 0;
			
			var mWindowHeight = $(window).height();
			var mWindowWidth = $(window).width();
			
			$(".eChat").each(function () {
				mChatCount++;
				$(this).css("left", (mWindowWidth - 235 - (mChatCount == 1 ? 290 : (mChatCount * 290))) + "px");
				if($(this).attr("window-status") == 1)
					$(this).css("top", (mWindowHeight - 325) + "px");
				else
					$(this).css("top", (mWindowHeight - 40) + "px");
			});
		},
		
		positionateFriendsWindow: function() {
			$(".eliteChatFriends").each(function () {
				if($(this).attr("window-status") == 1) {
					$(this).css("left", ($(window).width() - 225) + "px");
					$(this).css("top", ($(window).height() - 614) + "px");
				} else {
					$(this).css("left", ($(window).width() - 225) + "px");
					$(this).css("top", ($(window).height() - 40) + "px");
				}
			});
		},
		
		refreshChatWindowResize: function () {
			$(window).resize(function () {
				systemCHAT.refreshChatWindows();
				systemCHAT.positionateFriendsWindow();
			});
		},
		
		refreshChatWindowScroll: function () {
			$(window).scroll(function () {
				systemCHAT.refreshChatWindows();
				systemCHAT.positionateFriendsWindow();
			});
		},
		
		closeWindow: function () {
			$("body").on("click", ".eClose", function () {
				var mWindowId = $(this).attr("chat-window-id");
				var mUserId = $("#eliteChatWindow-" + mWindowId).attr("chat-window-user");
				mChatCollection.remove(mUserId);
				$("#eliteChatWindow-" + mWindowId).fadeOut(function () {
					$(this).remove();
					mChatCount--;
					systemCHAT.refreshChatWindows();
					
					$.ajax({
						url: "system.ajax/ajax.handle.chat.windows.php",
						type: "POST",
						dataType: "JSON",
						data: { handleType: "close", windowUser: mUserId, additionalContent: -1 },
						success: function(jr) { }
					});
				});
			});
		},
		
		hideWindow: function () {
			$("body").on("click", ".eHide", function () {
				var mWindowId = $(this).attr("chat-window-id");
				var mState = 0;
				if($(this).hasClass("glyphicon-chevron-down")) {
					$("#eliteChatWindow-" + mWindowId).animate({ top: $(window).height() - 40 });
					$("#eliteChatWindow-" + mWindowId).attr("window-status", 0);
					$(this).removeClass("glyphicon-chevron-down");
					$(this).addClass("glyphicon-chevron-up");
					mState = 0;
				} else {
					$("#eliteChatWindow-" + mWindowId).animate({ top: $(window).height() - 325 });
					$("#eliteChatWindow-" + mWindowId).attr("window-status", 1);
					$(this).removeClass("glyphicon-chevron-up");
					$(this).addClass("glyphicon-chevron-down");
					mState = 1;
				}
				
				$.ajax({
					url: "system.ajax/ajax.handle.chat.windows.php",
					type: "POST",
					dataType: "JSON",
					data: { handleType: "hide", windowUser: mWindowId, additionalContent: mState },
					success: function(jr) { }
				});
			});
		},
		
		openWindow: function() {
			$("body").on("click", "[chat-event=\"initialize\"]", function () {
				var mChatUserId = $(this).attr("chat-receiver-id");
				if($.inArray(mChatUserId, mChatCollection) == -1) {
					mChatCollection.push(mChatUserId);
					systemCHAT.initializeChatWindow(mChatUserId, 1);
					$.ajax({
						url: "system.ajax/ajax.handle.chat.windows.php",
						type: "POST",
						dataType: "JSON",
						data: { handleType: "open", windowUser: mChatUserId, additionalContent: -1 },
						success: function(jr) { }
					});
				}
			});
		},
	
		initializeEvents: function () {
			$("body").on("click", "[data-event=\"initialize-chat\"]", function (mEvent) {
				mEvent.stopPropagation();
				var mUserId = $(this).attr("data-parameter");
				if($("#userId").val() != mUserId) {
					if($.inArray(mUserId, mChatCollection) == -1) {
						mChatCollection.push(mUserId);
						systemCHAT.initializeChatWindow(mUserId, 1);
						$.ajax({
							url: "system.ajax/ajax.handle.chat.windows.php",
							type: "POST",
							dataType: "JSON",
							data: { handleType: "open", windowUser: mUserId, additionalContent: -1 },
							success: function(jr) { }
						});
					} else {
						$("#eliteChatWindow-" + mUserId).animate({ top: $(window).height() - 325 });
						$("#eliteChatWindow-" + mUserId).attr("window-status", 1);
						var mLocation = $("[data-location=\"window-events-" + mUserId + "\"]");
						$(mLocation).removeClass("glyphicon-chevron-up");
						$(mLocation).addClass("glyphicon-chevron-down");
						mState = 1;
						$("[data-location=\"footer-input-" + mUserId + "\"]").focus();
						$.ajax({
							url: "system.ajax/ajax.handle.chat.windows.php",
							type: "POST",
							dataType: "JSON",
							data: { handleType: "hide", windowUser: mUserId, additionalContent: 1 },
							success: function(jr) { }
						});
					}
				}
			});
		},
	
		loadChatButtons: function () {
			$("[data-location=\"open-chat-btn\"]").each(function () {
				var mUserId = $(this).attr("data-parameter");
				
				if($.inArray(mUserId, mChatCollection) > 0)
					$(this).html("<i class=\"glyphicon glyphicon-comment textIcon12\"></i> " + mLangPack.chat.closechat + "");
			});
			
			$("body").on("click", "[data-location=\"open-chat-btn\"]", function () {
				var mUserId = $(this).attr("data-parameter");
				if($.inArray(mUserId, mChatCollection) > 0) {
					mChatCollection.remove(mUserId);
					$("#eliteChatWindow-" + mUserId).fadeOut(function () {
						$(this).remove();
						mChatCount--;
						systemCHAT.refreshChatWindows();
							
						$.ajax({
							url: "system.ajax/ajax.handle.chat.windows.php",
							type: "POST",
							dataType: "JSON",
							data: { handleType: "close", windowUser: mUserId, additionalContent: -1 },
							success: function(jr) { }
						});
						$(this).html("<i class=\"glyphicon glyphicon-comment textIcon12\"></i> " + mLangPack.chat.openchat + "");
					});
				}
			});
		}
	};

	systemCHAT.initializeBase();
});