var mContainerCollection = {};
var mCurrentIndex = 0;
var mLangPack = "";

var systemGLOBAL = {
	initializeBase: function() {
		$("body").tooltip({ selector: '[data-toggle="tooltip"]' });
	
		$.ajax({
			url: "system.ajax/ajax.handle.language.pack.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function(ajaxResponse) {
				mLangPack = ajaxResponse.langPack;
	
				systemGLOBAL.initializeNotificationGlobal();
				systemGLOBAL.initializeNotificationMessages();
				systemGLOBAL.initializeNotificationFriends();
				systemGLOBAL.initializeCount();
				
				systemGLOBAL.globalSignout();
				systemGLOBAL.commentLikeEvent();
				systemGLOBAL.removeContainer();
				// systemGLOBAL.popOverProfileInformation();
				systemGLOBAL.onPageOpen();
				systemGLOBAL.onPageLeave();
				systemGLOBAL.initializeTimeline(false);
				systemGLOBAL.loadMoreComments();
				systemGLOBAL.addFriend();
				systemGLOBAL.removeFriend();
				systemGLOBAL.loadFriendButtons();
				systemGLOBAL.displayMore();
				systemGLOBAL.displayMoreMentions();
				systemGLOBAL.dragAbleContainer();
				systemGLOBAL.searchBox();
				systemGLOBAL.sendProfileEvent();
				systemGLOBAL.doubleClickComment();
				systemGLOBAL.gallerySwitch();
				systemGLOBAL.reportFunction();
				systemGLOBAL.initializeFriends();
				systemGLOBAL.changeProfileSettings();
				
				systemGLOBAL.friendStatus();
				systemGLOBAL.changePictures();
				systemGLOBAL.initializeLinkShare();
				systemGLOBAL.loadNotificationCollection();
			}
		});
	},
	
	initializeNotificationGlobal: function () {
		$.ajax({
			url: "system.ajax/ajax.handle.notifications.global.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function(jr) {
				$("#notificationsGlobal").html(jr.containerHTML);
			}
		});
	},
	
	initializeNotificationMessages: function () {
		$.ajax({
			url: "system.ajax/ajax.handle.notifications.messages.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function(jr) {
				$("#notificationsMessages").html(jr.containerHTML);
			}
		});
	},
	
	initializeNotificationFriends: function () {
		$.ajax({
			url: "system.ajax/ajax.handle.notifications.friends.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function(jr) {
				$("#notificationsFriends").html(jr.containerHTML);
			}
		});
	},
	
	globalSignout: function () {
		$("body").on("click", ".signOut", function () {
			swal({
				title: mLangPack.global.areyousure,
				text: mLangPack.global.aboutsignout,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: "btn-warning",
				confirmButtonText: mLangPack.global.yessignout,
				cancelButtonText: mLangPack.global.nosignout,
				closeOnCancel: true,
				closeOnConfirm: false
			}, function () {
				$.ajax({
					url: "system.ajax/ajax.handle.logout.php",
					type: "POST",
					dataType: "JSON",
					data: { },
					success: function(jr) {
						swal({
							title: mLangPack.global.signedout,
							text: mLangPack.global.signedouttext,
							type: "success",
							showCancelButton: false,
							confirmButtonClass: "btn-success",
							confirmButtonText: mLangPack.global.goodbye
						}, function () {
							location.reload();
						});
					}
				});
			});
		});
	},
	
	commentLikeEvent: function() {
		$("body").on("click", ".commentLikeEvent", function() {
			var mCommentId = $(this).attr("comment-id");
			var mCurrentHTML = $(this).html();
			$(this).html("<img src=\"system.assets/images/loader.gif\" />");
			var mThis = $(this);
			var mCommentLikeCountElement = $("#comment-like-count-" + mCommentId);
			var mCommentLikeCount = parseInt(mCommentLikeCountElement.html());
			
			$.ajax({
				url: "system.ajax/ajax.handle.timeline.commentlike.php",
				type: "POST",
				dataType: "JSON",
				data: { commentId: mCommentId },
				success: function(jsonResponse) {
					if(jsonResponse.isLike == true) {
						mCommentLikeCount = mCommentLikeCount + 1;
						mCommentLikeCountElement.html(mCommentLikeCount);
						mThis.html(mLangPack.global.unlikethis);
					} else {
						mCommentLikeCount = mCommentLikeCount - 1;
						mCommentLikeCountElement.html(mCommentLikeCount);
						mThis.html(mLangPack.global.likethis);
					}
				}
			});
		});
	},
	
	removeContainer: function () {
		$("body").on("click", ".remove-container", function () {
			var mContainerId = $(this).attr("container-id");
			swal({
				title: mLangPack.global.areyousure,
				text: mLangPack.global.containertextdelete,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: "btn-warning",
				confirmButtonText: mLangPack.global.yesdelete,
				closeOnConfirm: false
			}, function () {
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.delete.php",
					type: "POST",
					dataType: "JSON",
					data: { containerId: mContainerId },
					success: function(jr) {
						swal(mLangPack.global.deleted, mLangPack.global.entrydeleted, "success");
						$("[container-id=\"" + mContainerId + "\"]").fadeOut();
					}
				});
			});
		});
	},
	
	popOverProfileInformation: function() {
		$("body").on("mouseover", ".profilePopOver", function(e) {
			var mOffsetTop = $(this).offset().top;
			var mOffsetLeft = $(this).offset().left;
			var mUserId = $(this).attr("profile-popover-id");
			
			$("#profileMiniContainer").css("position", "absolute");
			$("#profileMiniContainer").css("top", (mOffsetTop - 135) + "px");
			$("#profileMiniContainer").css("left", (mOffsetLeft - 140) + "px");
			$("#profileMiniContainer").show();
			
			$.ajax({
				url: "system.ajax/ajax.handle.fetch.user.info.php",
				type: "POST",
				dataType: "JSON",
				data: { userId: mUserId },
				success: function(jr) {
					$("#profileMiniContainerLoading").hide();
					$("#profileMiniInnerContent").fadeIn();
					
					$(".miniCover").css("background-image", "url('" + jr.profileCover + "'), url('https://scontent-a-fra.xx.fbcdn.net/hphotos-xap1/v/t1.0-9/68450_599037243502284_1151103777_n.jpg?oh=86ce330a72cd408569add3bcf3a2893c&oe=54F95D20')");
					$(".miniPicture").css("background-image", "url('" + jr.profilePicture + "')");
					$(".miniFullname").html("<a href=\"page.profile.php?profile-id=" + mUserId + "\">" + jr.fullName + "</a>");
				}
			});
		});
		
		$("body").on("mouseover", "#profileMiniContainer", function () {
			$("#profileMiniContainer").show();
		});
		
		$("body").on("mouseleave", ".profilePopOver, #profileMiniContainer", function() {
			setTimeout(function() {
				if(!$("#profileMiniContainer").is(":hover")) {
					$("#profileMiniContainerLoading").show();
					$("#profileMiniInnerContent").fadeOut();
					$("#profileMiniContainer").stop().hide();
				}
			}, 500);
		});
	},
	
	onPageOpen: function () {
		
	},
	
	onPageLeave: function () {
		
	},
	
	initializeTimeline: function(mRefresh) {
		if(mRefresh) {
			mCurrentPosition = 0;
			$("#postText, #postLocation, #fileToUpload, #postHashtags_tagsinput, #postMentions").val("");
		}
		
		$.ajax({
			url: "system.ajax/ajax.handle.timeline.fetch.php",
			type: "POST",
			dataType: "JSON",
			data: { currentPosition: mCurrentPosition, userId: $("#currentPage").val() == "page.timeline" ? "timeline" : $("#profileUserId").val() },
			success: function(jsonResponse) {
				if(jsonResponse.containerCount > 0) {
					$("#containerTimeline").show();
					$("#emptyTimeline").remove();
					if(mRefresh == true) {
						var mPreviousHTML = $("#postButtonType").html();
						$("#postButtonType").fadeOut(function() {
							$(this).html("<center><h4>" + mLangPack.global.postsubmitted + "</h4><img src=\"system.assets/images/icons/svg/clipboard.svg\" /></center>");
							$(".clearfix").remove();
							$("#containerTimeline").html(jsonResponse.containerHTML);
						}).fadeIn().delay(1000).fadeOut(function() {
							$(this).html(mPreviousHTML);
						}).fadeIn();
						
						systemTimeline.initializeAllComments();
					} else {
						$(".clearfix").remove();
						$("#containerTimeline").html($("#containerTimeline").html() + jsonResponse.containerHTML);
					}

					mCurrentPosition = mCurrentPosition + 15;
				} else {
					$("#containerTimeline").hide();
					$("body").append("<div id=\"emptyTimeline\" class=\"row\"><div class=\"col-md-6 col-md-offset-3\"><center class=\"well\">" + mLangPack.global.emptytimeline + "</center></div></div>");
				}
				
				systemGLOBAL.loadTimelineComments();
			},
			error: function() { $("#containerTimeline").html(mLangPack.global.timelineerror); }
		});
	},
	
	loadMoreComments: function () {
		$("body").on("click", "[data-event=\"load-comments\"]", function () {
			$(this).remove();
			var mContainerId = $(this).attr("data-parameter");
			var mFancy = $(this).attr("data-fancy");
			
			if(mContainerCollection[mContainerId] === undefined)
				mContainerCollection[mContainerId] = 3;
			
			$.ajax({
				url: "system.ajax/ajax.handle.timeline.commentload.php",
				type: "POST",
				dataType: "JSON",
				data: { containerId: mContainerId, containerIndex: mContainerCollection[mContainerId] },
				success: function(ajaxResponse) {
					var mCurrentHTML = $("#commentsFields-" + mContainerId).html();
					$("#commentsFields-" + mContainerId).html(ajaxResponse.commentHTML + mCurrentHTML);
					mContainerCollection[mContainerId] += 3;
				}
			});
			
			if(mFancy == "true") {
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.commentload.php",
					type: "POST",
					dataType: "JSON",
					data: { containerId: mContainerId, containerIndex: mContainerCollection[mContainerId], outputType: false },
					success: function(ajaxResponse) {
						var mCurrentHTML = $("#fancyCommentArea").html();
						$("#fancyCommentArea").html(ajaxResponse.commentHTML + mCurrentHTML);
						mContainerCollection[mContainerId] += 3;
					}
				});
			}
		});
	},
	
	loadTimelineComments: function () {
		$(".timeline-body").each(function() {
			var mContainerId = $(this).attr("container-id");
			var mCommentsElement = $("#commentsFields-" + mContainerId);
			$(mCommentsElement).html("<center><img src=\"system.assets/images/loader.gif\" /></center>");
			$.ajax({
				url: "system.ajax/ajax.handle.timeline.commentload.php",
				type: "POST",
				dataType: "JSON",
				data: { containerId: mContainerId, containerIndex: 0 },
				success: function(ajaxResponse) {
					$(mCommentsElement).html("");
					$(mCommentsElement).html(ajaxResponse.commentHTML);
				}
			});
		});
	},
	
	setFriendButton: function(mElement, mState) {
		if(mState == 0) {
			$(mElement).removeClass("btn-warning").removeClass("btn-danger").addClass("btn-primary");
			$(mElement).html("<i class=\"glyphicon glyphicon-plus textIcon12\"></i> " + mLangPack.global.addfriend);
			$(mElement).attr("data-event", "add-friend");
			$(mElement).attr("data-state", mState);
		} else if(mState == 1) {
			$(mElement).removeClass("btn-primary").removeClass("btn-danger").addClass("btn-warning");
			$(mElement).html("<i class=\"glyphicon glyphicon-plus textIcon12\"></i> " + mLangPack.global.pending);
			$(mElement).attr("data-event", "remove-friend");
			$(mElement).attr("data-state", mState);
		} else if(mState == 2) {
			$(mElement).removeClass("btn-primary").removeClass("btn-warning").addClass("btn-danger");
			$(mElement).html("<i class=\"glyphicon glyphicon-minus textIcon12\"></i> " + mLangPack.global.remove);
			$(mElement).attr("data-event", "remove-friend");
			$(mElement).attr("data-state", mState);
		}
	},
	
	setFriendButtonMini: function(mElement, mState) {
		if(mState == 0) {
			$(mElement).removeClass("btn-warning").removeClass("btn-danger").addClass("btn-primary");
			$(mElement).html("<i class=\"glyphicon glyphicon-plus textIcon12\"></i>");
			$(mElement).attr("data-event", "add-friend-mini");
			$(mElement).attr("data-state", mState);
		} else if(mState == 1) {
			$(mElement).removeClass("btn-primary").removeClass("btn-danger").addClass("btn-warning");
			$(mElement).html("<i class=\"glyphicon glyphicon-plus textIcon12\"></i>");
			$(mElement).attr("data-event", "remove-friend-mini");
			$(mElement).attr("data-state", mState);
		} else if(mState == 2) {
			$(mElement).removeClass("btn-primary").removeClass("btn-warning").addClass("btn-danger");
			$(mElement).html("<i class=\"glyphicon glyphicon-minus textIcon12\"></i>");
			$(mElement).attr("data-event", "remove-friend-mini");
			$(mElement).attr("data-state", mState);
		}
	},
	
	addFriend: function () {
		$("body").on("click", "[data-event=\"add-friend\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mFriendId = $(this).attr("data-parameter");
			var mElement = $(this);
			
			$.ajax({
				url: "system.ajax/ajax.handle.friend.add.php",
				type: "POST",
				dataType: "JSON",
				data: { friendId: mFriendId },
				success: function(ajaxResponse) {
					if(ajaxResponse.isValid == true)
						systemGLOBAL.setFriendButton(mElement, 1);
				}
			});
		});
		
		$("body").on("click", "[data-event=\"add-friend-mini\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mFriendId = $(this).attr("data-parameter");
			var mElement = $(this);
			
			$.ajax({
				url: "system.ajax/ajax.handle.friend.add.php",
				type: "POST",
				dataType: "JSON",
				data: { friendId: mFriendId },
				success: function(ajaxResponse) {
					if(ajaxResponse.isValid == true)
						systemGLOBAL.setFriendButtonMini(mElement, 1);
				}
			});
		});
	},
	
	removeFriend: function () {
		$("body").on("click", "[data-event=\"remove-friend\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mFriendId = $(this).attr("data-parameter");
			var mElement = $(this);
			
			swal({
				title: mLangPack.global.areyousure,
				text: mLangPack.global.removefriendwarning,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: "btn-warning",
				confirmButtonText: mLangPack.global.yes,
			}, function () {
				$.ajax({
					url: "system.ajax/ajax.handle.friend.remove.php",
					type: "POST",
					dataType: "JSON",
					data: { friendId: mFriendId },
					success: function(ajaxResponse) {
						if(ajaxResponse.isValid == true)
							systemGLOBAL.setFriendButton(mElement, 0);
					}
				});
			});
		});
		
		$("body").on("click", "[data-event=\"remove-friend-mini\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mFriendId = $(this).attr("data-parameter");
			var mElement = $(this);
			
			$.ajax({
				url: "system.ajax/ajax.handle.friend.remove.php",
				type: "POST",
				dataType: "JSON",
				data: { friendId: mFriendId },
				success: function(ajaxResponse) {
					if(ajaxResponse.isValid == true)
						systemGLOBAL.setFriendButtonMini(mElement, 0);
				}
			});
		});
	},
	
	loadFriendButtons: function () {
		$("body").on("hover", "[data-state=\"1\"]", function () {
			if($(this).is("data-mini"))
				$(this).html("<i class=\"glyphicon glyphicon-minus textIcon12\"></i>");
			else
				$(this).html("<i class=\"glyphicon glyphicon-minus textIcon12\"></i> " + mLangPack.global.cancel);
		}).on("mouseleave", "[data-state=\"1\"]", function () {
			if($(this).is("data-mini"))
				$(this).html("<i class=\"glyphicon glyphicon-plus textIcon12\"></i>");
			else
				$(this).html("<i class=\"glyphicon glyphicon-plus textIcon12\"></i> " + mLangPack.global.pending);
		});
	
		$("[data-event=\"add-friend\"]").each(function () {
			var mFriendId = $(this).attr("data-parameter");
			var mElement = $(this);
			
			$.ajax({
				url: "system.ajax/ajax.handle.friend.load.php",
				type: "POST",
				dataType: "JSON",
				data: { friendId: mFriendId },
				success: function(ajaxResponse) {
					systemGLOBAL.setFriendButton(mElement, ajaxResponse.currentState);
				}
			});
		});
	},
	
	displayMore: function () {
		$("body").on("click", "[data-event=\"display-more-comment\"]", function () {
			var mCommentId = $(this).attr("data-parameter");
			var mCommentBox = $("#commentLocation-" + mCommentId);
			$.ajax({
				url: "system.ajax/ajax.handle.single.comment.php",
				type: "POST",
				data: { commentId: mCommentId },
				success: function(ajaxResponse) {
					$(mCommentBox).html(ajaxResponse.commentText);
				}
			});
		});
	},
	
	displayMoreMentions: function () {
		$("body").on("click", "[data-event=\"display-mentions\"]", function () {
			var mContainerId = $(this).attr("data-parameter");
			$.ajax({
				url: "system.ajax/ajax.handle.fetch.mentions.php",
				type: "POST",
				dataType: "JSON",
				data: { containerId: mContainerId },
				success: function(ajaxResponse) {
					swal("", ajaxResponse.htmlContainer);
				}
			});
		});
	},
	
	dragAbleContainer: function () {
		var mOldYPosition = 0;
		$("#dragAbleContainer").draggable({ axis: "y", containment: [0, -167, 0, 0], drag: function(event, ui) {
			var mCurrentYPosition = ui.position.top;
			if(mOldYPosition - mCurrentYPosition > 0) {
				var mElement = $("#dragAbleContainer");
				$(mElement).css("height", "200px");
			
				$("#dragAbleParent").css("height", "375px");
				$("#dragAbleParent").css("top", "-170px");
				$("#searchResults").hide();
			}
			mOldYPosition = mCurrentYPosition;
		}});
		
		if (navigator.geolocation)
			navigator.geolocation.getCurrentPosition(weatherWidgetCallback);
		
		function weatherWidgetCallback(mPosition) {
			var mLatitude = mPosition.coords.latitude;
			var mLongitude = mPosition.coords.longitude;
			var mAPIKey = "fa9047949f0c2a05379baa2292e2019a";
			
			$.ajax({
				url: "http://api.forecast.io/forecast/" + mAPIKey + "/" + mLatitude + "," + mLongitude + "",
				type: "GET",
				dataType: "jsonp",
				crossDomain: true,
				data: { },
				success: function(ajaxResponse) {
					var mOutput = ajaxResponse;
					var mTempF = mOutput.currently.temperature;
					var mTempC = Math.round((mOutput.currently.temperature - 32) * 5 / 9);
					
					$("#widgetWeatherTemperatureF").html(mTempC);
					$("#widgetWeatherTemperatureC").html(mTempC);
					
					$("#weatherIcon").removeClass("wi wi-day-sunny-overcast").addClass("wi wi-day-sunny");
				}
			});
			
			$.ajax({
				url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + mLatitude + "," + mLongitude + "",
				type: "GET",
				dataType: "json",
				crossDomain: true,
				data: { },
				success: function(ajaxResponse) {
					var mOutput = ajaxResponse["results"][0]["address_components"];
					$.each(mOutput, function(i, mData) {
						if(mData["types"][0] == "locality") {
							var mCityName = mData["long_name"];
							$("#widgetWeatherLocationText").html(mCityName);
						}
					});
				}
			});
			
			function getNewHourValues() {
				var mCurrentDate = new Date();
				var mHours = mCurrentDate.getHours();
				var mMinutes = mCurrentDate.getMinutes();
				var mSeconds = mCurrentDate.getSeconds();
				
				var mWeekDays = new Array(mLangPack.global.sunday, mLangPack.global.monday, mLangPack.global.tuesday, mLangPack.global.wednesday, mLangPack.global.thursday, mLangPack.global.friday, mLangPack.global.saturday);
				var mWeekDay = mWeekDays[mCurrentDate.getDay()];
				
				if(mHours < 10)
					mHours = "0" + mHours;
				
				if(mMinutes < 10)
					mMinutes = "0" + mMinutes;
					
				if(mSeconds < 10)
					mSeconds = "0" + mSeconds;
					
				$("#widgetClockTime").html(mHours + ':' + mMinutes + ':' + mSeconds);
				$("#widgetClockDay").html(mWeekDay);
				setTimeout(getNewHourValues, 1000);
			}
			setTimeout(getNewHourValues, 1000);
		}
	},
	
	searchBox: function () {
		function appendSearchBox() {
			var mElement = $("#dragAbleContainer");
			$(mElement).css("height", "370px");
			$(mElement).css("top", "0px");
			
			$("#dragAbleParent").css("height", "700px");
			$("#dragAbleParent").css("top", "-340px");
		}
		
		function removeSearchBox() {
			var mElement = $("#dragAbleContainer");
			$(mElement).css("height", "200px");
			
			$("#dragAbleParent").css("height", "375px");
			$("#dragAbleParent").css("top", "-170px");
		}
		
		$("body").on("keyup", "#searchBoxTop", function () {
			var mLookUp = $.trim($(this).val());
			if(mLookUp.length > 0) {
				$.ajax({
					url: "system.ajax/ajax.handle.search.users.php",
					type: "POST",
					dataType: "JSON",
					data: { lookUp: mLookUp },
					success: function(ajaxResponse) {
						if(ajaxResponse.resultCount > 0) {
							$("#searchResults").fadeIn(function () {
								appendSearchBox();
								$(this).html(ajaxResponse.resultContent);
							});
						}
					}
				});
			} else {
				$("#searchResults").fadeOut().html("");
				removeSearchBox();
			}
		});
	},
	
	sendProfileEvent: function () {
		$("body").on("click", "[data-event=\"send-profile\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mProfileId = $(this).attr("data-parameter");
			top.location = "page.profile.php?profile-id=" + mProfileId;
		});
	},
	
	doubleClickComment: function () {
		$("body").on("click", ".comment-text", function (mEvent) {
			mEvent.stopPropagation();
			var mElement = $(this);
			$(mElement).removeClass("comment-text");
			var mLocation = $(mElement).attr("location-id");
			$.ajax({
				url: "system.ajax/ajax.handle.comment.load.php",
				type: "POST",
				dataType: "JSON",
				data: { commentId: mLocation },
				success: function(ajaxResponse) {
					$(mElement).html("<textarea edit-location=\"" + mLocation + "\" location-id=\"" + mLocation + "\" rows=\"4\" class=\"edit-comment\" data-event=\"save-comment\">" + $.trim(ajaxResponse.newCommentHTML) + "</textarea>");
					$("[edit-location=\"" + mLocation + "\"]").focus();
					$("[edit-location=\"" + mLocation + "\"]").focusout(function () {
						$.ajax({
							url: "system.ajax/ajax.handle.comment.load.php",
							type: "POST",
							dataType: "JSON",
							data: { commentId: mLocation },
							success: function(ajaxResponse) {
								$("[edit-location=\"" + mLocation + "\"]").remove();
								var mNewCommentContent = ajaxResponse.newCommentHTML;
								$("#commentLocation-" + mLocation).html(mNewCommentContent);
								$("#commentLocation-" + mLocation).addClass("comment-text");
							}
						});
					});
				}
			});
		});
		
		$("body").on("keyup", "[data-event=\"save-comment\"]", function (e) {
			var mElement = $(this);
			if(e.keyCode == 13) {
				var mLocation = $(this).attr("location-id");
				var mComment = $.trim($(this).val());
				if(mComment.length > 0) {
					$.ajax({
						url: "system.ajax/ajax.handle.comment.change.php",
						type: "POST",
						dataType: "JSON",
						data: { commentId: mLocation, newContent: mComment },
						success: function(ajaxResponse) {
							$(mElement).remove();
							var mNewCommentContent = ajaxResponse.newCommentHTML;
							$("#commentLocation-" + mLocation).html(mNewCommentContent);
							$("#commentLocation-" + mLocation).addClass("comment-text");
						}
					});
				} else {
					$(this).remove();
					// load again the fucking comment -_-
				}
			}
		});
	},
	
	gallerySwitch: function () {
		var mIndex = 0;
		$(".galleryName").each(function () {
			if(mIndex == 0) {
				var mAlbumId = $(this).attr("data-parameter");
				loadAlbum(mAlbumId, $(this));
			}
			mIndex++;
		});
	
		$("body").on("mouseover", ".galleryOverlay", function () {
			$(this).css("opacity", "1");
		});
		
		$("body").on("mouseleave", ".galleryOverlay", function () {
			$(this).css("opacity", "0");
		});
		
		$("#selectAlbum").change(function () {
			var mAlbumId = $("#selectAlbum option:selected").attr("data-parameter");
			loadAlbum(mAlbumId, -1);
		});
		
		function loadAlbum(mAlbumId, mElement) {
			$("#galleryContent").html("<center><img src=\"system.assets/images/loader.gif\" /></center>");
			$(".galleryName").each(function() {
				$(this).removeClass("active");
			});
			
			if(mElement !== -1)
				$(mElement).addClass("active");
				
			var mAlbumId = mAlbumId == -1 ? $(mElement).attr("data-parameter") : mAlbumId;
			$.ajax({
				url: "system.ajax/ajax.handle.load.gallery.php",
				type: "POST",
				dataType: "JSON",
				data: { albumId: mAlbumId },
				success: function(ajaxResponse) {
					$("#galleryContent").html(ajaxResponse.htmlContent);
				}
			});
		}
		
		$("body").on("click", ".galleryElement", function () {
			var mImageId = $(this).attr("data-parameter");
			var mImageSrc = $("[data-location=\"galleryPicture-" + mImageId + "\"]").attr("data-parameter");
			
			initializeFancyImage(mImageId, mImageSrc);
		});
		
		$("body").on("click", "[data-event=\"display-fancy\"]", function () {
			var mImageId = $(this).attr("data-parameter");
			var mImageSrc = $(this).attr("src");
			initializeFancyImage(mImageId, mImageSrc);
		});
		
		$("body").on("click", "[data-event=\"display-fancy-image\"]", function () {
			var mImageSrc = $(this).attr("src");
			initializeFancyImage(-1, mImageSrc);
		});
		
		function initializeFancyImage(mImageId, mImageSrc) {
			if(mImageId !== -1) {
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.fetch.info.php",
					type: "POST",
					dataType: "JSON",
					data: { imageId: mImageId },
					success: function(ajaxResponse) {
						$("#fancyDescriptionContent").html(ajaxResponse.postText);
						$("#fancyUsernameLink").attr("href", "page.profile.php?id=" + ajaxResponse.userId);
						$("#fancyUsernameLink").text(ajaxResponse.fullName);
						$("#fancyImageElement").attr("src", mImageSrc);
						$("#fancyCommentInput").attr("container-id", ajaxResponse.timelineId);
						$("#fancyTimeAgo").text(ajaxResponse.timeAgo);
						$("#fancyPublicy").attr("class", "glyphicon glyphicon-" + ajaxResponse.iconPublicy);
						$(".fancyProfilePicture").attr("src", ajaxResponse.userPicture);
						
						$.ajax({
							url: "system.ajax/ajax.handle.timeline.commentload.php",
							type: "POST",
							dataType: "JSON",
							data: { containerId: ajaxResponse.timelineId, containerIndex: 0, outputType: false },
							success: function(ajaxResponse) {
								$("#fancyCommentArea").html("");
								$("#fancyCommentArea").html(ajaxResponse.commentCount > 0 ? ajaxResponse.commentHTML : "<li><i class=\"glyphicon glyphicon-comment font12\"></i> " + mLangPack.global.nocomments + "</li>");
							}
						});
						
						$("#fancyModal").modal("show");
					}
				});
			} else {
				$("#fancyImageElement-image").attr("src", mImageSrc);
				$("#fancyModalImage").modal("show");
			}
		}
	
		$("body").on("click", ".galleryName", function () {
			var mElement = $(this);
			loadAlbum(-1, mElement);
		});
		
		$("body").on("click", "#createAlbum", function () {
			$("#createAlbumModal").modal("show");
		});
		
		$("body").on("click", "#modifyAlbum", function () {
			$("#modifyAlbumModal").modal("show");
		});
		
		$("body").on("click", ".modifyAlbumName", function (mEvent) {
			mEvent.stopPropagation();
			var mElement = $(this);
			var mAlbumId = $(mElement).attr("data-parameter");
			var mAlbumName = $.trim($("[data-location=\"modifyAlbumName-" + mAlbumId + "\"]").attr("data-old-name"));
			$(mElement).html("<input data-parameter=\"" + mAlbumId + "\" data-location=\"modifyAlbumInput-" + mAlbumId + "\" type=\"text\" class=\"form-control modifyAlbumInputSave\" value=\"" + mAlbumName + "\" />");
			$("[data-location=\"modifyAlbumInput-" + mAlbumId + "\"]").focus();
		});
		
		$("body").on("click", "[data-event=\"deleteAlbum\"]", function () {
			var mAlbumId = $(this).attr("data-parameter");
			
			swal({
				title: mLangPack.global.areyousure,
				text: mLangPack.global.albumdeletewarning,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: "btn-warning",
				confirmButtonText: mLangPack.global.yesdelete,
				cancelButtonText: mLangPack.global.nocancel,
				closeOnConfirm: false,
				closeOnCancel: true
			}, function (isConfirm) {
				if(isConfirm) {
					$.ajax({
						url: "system.ajax/ajax.handle.album.delete.php",
						type: "POST",
						dataType: "JSON",
						data: { albumId: mAlbumId },
						success: function(ajaxResponse) {
							if(ajaxResponse.isValid) {
								$("[data-location=\"albumListRow-" + mAlbumId + "\"]").fadeOut();
								$("[data-location=\"albumCollection-" + mAlbumId + "\"]").fadeOut();
								var mStandardAlbum = $("[data-album-standard=\"yes\"]").attr("data-parameter");
								loadAlbum(mStandardAlbum, $("[data-album-standard=\"yes\"]"));
								swal(mLangPack.global.deleted, mLangPack.global.albumdeleted, "success");
							}
						}
					});
				}
			});
		});
		
		$("body").on("keyup", ".modifyAlbumInputSave", function (e) {
			if(e.keyCode == 13) {
				var mElement = $(this);
				var mAlbumId = $(mElement).attr("data-parameter");
				var mAlbumName = $.trim($(mElement).val());
				
				if(mAlbumName.length > 0) {
					$.ajax({
						url: "system.ajax/ajax.handle.album.change.php",
						type: "POST",
						dataType: "JSON",
						data: { albumName: mAlbumName, albumId: mAlbumId },
						success: function(ajaxResponse) {
							if(ajaxResponse.isValid) {
								$("[data-location=\"modifyAlbumInput-" + mAlbumId + "\"]").remove();
								$("[data-location=\"modifyAlbumName-" + mAlbumId + "\"]").html(mAlbumName);
								$("[data-location=\"albumListName-" + mAlbumId + "\"]").html(mAlbumName);
							} else
								$("[data-location=\"modifyAlbumInput-" + mAlbumId + "\"]").css("border", "1px solid red");
						}
					});
				} else
					$("[data-location=\"modifyAlbumInput-" + mAlbumId + "\"]").css("border", "1px solid red");
			}
		});
		
		$("body").on("click", "#submitNewAlbum", function () {
			var mAlbumName = $.trim($("#albumName").val());
			
			if(mAlbumName.length > 0) {
				$.ajax({
					url: "system.ajax/ajax.handle.album.create.php",
					type: "POST",
					dataType: "JSON",
					data: { albumName: mAlbumName },
					success: function(ajaxResponse) {
						if(ajaxResponse.isValid) {
							$("#albumCollection").append("<li data-toggle=\"tooltip\" data-placement=\"top\" title=\"\" data-parameter=\"" + ajaxResponse.albumId + "\" class=\"galleryName\" role=\"presentation\" data-original-title=\"" + ajaxResponse.albumCreated + "\"><a href=\"javascript:;\">" + ajaxResponse.albumName + "</a></li>");
							$("#createAlbumModal").modal("hide");
							swal(mLangPack.global.goodjob, mLangPack.global.addedcollection, "success");
						} else {
							swal(mLangPack.global.oops, mLangPack.global.albumnameinuse, "error");
						}
					}
				});
			} else {
				swal(mLangPack.global.oops, mLangPack.global.albumnameempty, "error");
			}
		});
	},
	
	reportFunction: function () {
		$("body").on("click", "[data-event=\"report\"]", function () {
			var mType = $(this).attr("data-type");
			var mId = $(this).attr("data-parameter");
			swal({
				title: mLangPack.global.areyousure,
				text: mLangPack.global.submitreport,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: "btn-warning",
				confirmButtonText: "Yes, report it!",
				closeOnConfirm: false
			}, function () {
				$.ajax({
					url: "system.ajax/ajax.handle.report.php",
					type: "POST",
					dataType: "JSON",
					data: { reportType: mType, reportId: mId },
					success: function(ajaxResponse) {
						swal(mLangPack.global.reported, mLangPack.global.reportsubmitted, "success");
					}
				});
			});
		});
	},
	
	initializeFriends: function() {
		$("#friendsCollection").append("<center style=\"margin-top: 15px\"><img src=\"system.assets/images/loader.gif\" /></center>");
		$.ajax({
			url: "system.ajax/ajax.handle.friends.load.php",
			type: "POST",
			dataType: "JSON",
			data: { currentIndex: 0, profileId: $("#profileUserId").val() },
			success: function(ajaxResponse) {
				$("#friendsCollection").html(ajaxResponse.htmlOutput.length > 0 ? ajaxResponse.htmlOutput : "<center><h4>" + mLangPack.global.nofriends + "</h4></center>");
			}
		});
		
		$("#friendsCollection").scroll(function() {
			if($("#friendsCollection").scrollTop() + $("#friendsCollection").height() == $("#friendsCollection").height()) {
				mCurrentIndex = mCurrentIndex + 30;
				$.ajax({
					url: "system.ajax/ajax.handle.friends.load.php",
					type: "POST",
					dataType: "JSON",
					data: { currentIndex: mCurrentIndex, profileId: $("#profileUserId").val() },
					success: function(ajaxResponse) {
						$("#friendsCollection").html($("#friendsCollection").html() + ajaxResponse.htmlOutput);
					}
				});
			}
		});
	},
	
	changeProfileSettings: function () {
		if($("#profileUserId").val() == $("#userId").val()) {
			$("body").on("click", ".profileColumn", function (event) {
				event.stopPropagation();
				var mParam = $(this).attr("data-parameter");
				var mValue = mParam != "pass" ? $.trim($(this).text()) : "";
				$(this).html("<input data-type=\"profile-input\" value=\"" + mValue + "\" type=\"text\" class=\"form-control\" data-location=\"" + mParam + "\" />");
			});
			
			$("body").on("click", "[data-type=\"profile-input\"]", function(event) {
				event.stopPropagation();
			});
			
			$("body").on("keyup", "[data-type=\"profile-input\"]", function(e) {
				event.stopPropagation();
				if(e.keyCode == 13) {
					var mLocation = $(this).attr("data-location");
					var mColumn = $("[data-parameter=\"" + mLocation + "\"]");
					var mNewVal = $(this).val();
					
					var entityMap = {
						"&": "&amp;",
						"<": "&lt;",
						">": "&gt;",
						'"': '&quot;',
						"'": '&#39;',
						"/": '&#x2F;'
					};

					function escapeHtml(string) {
						return String(string).replace(/[&<>"'\/]/g, function (s) {
						  return entityMap[s];
						});
					}
					  
					mNewVal = escapeHtml(mNewVal);
					
					if(mLocation == "residence")
						$(mColumn).html("<i class=\"glyphicon glyphicon-map-marker font14\"></i> " + mNewVal + " <img class=\"thumbnail\" style=\"width: 100%; margin-top: 5px\" src=\"http://maps.googleapis.com/maps/api/staticmap?center=" + mNewVal + "&zoom=13&size=800x100&maptype=roadmap\" />");
					else
						$(mColumn).text(mNewVal);
						
					$.ajax({
						url: "system.ajax/ajax.handle.profile.settings.php",
						type: "POST",
						dataType: "JSON",
						data: { settingLocation: mLocation, settingValue: mNewVal },
						success: function(ajaxResponse) {
							
						}
					});
				}
			});
		}
	},
	
	friendStatus: function () {
		$("body").on("click", "[data-event=\"accept-friend\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mUserId = $(this).attr("data-parameter");
			$("[friendstatus-location=\"" + mUserId + "\"]").fadeOut();
			$.ajax({
				url: "system.ajax/ajax.handle.friend.status.php",
				type: "POST",
				dataType: "JSON",
				data: { senderUser: mUserId, friendStatus: 1 },
				success: function(ajaxResponse) { }
			});
		});
		
		$("body").on("click", "[data-event=\"decline-friend\"]", function (mEvent) {
			mEvent.stopPropagation();
			var mUserId = $(this).attr("data-parameter");
			$("[friendstatus-location=\"" + mUserId + "\"]").fadeOut();
			$.ajax({
				url: "system.ajax/ajax.handle.friend.status.php",
				type: "POST",
				dataType: "JSON",
				data: { senderUser: mUserId, friendStatus: 0 },
				success: function(ajaxResponse) { }
			});
		});
		
		$("body").on("click", ".timeline-share-event", function () {
			var mContainerId = $(this).attr("container-id");
			swal({
				title: mLangPack.global.areyousure,
				text: mLangPack.global.sharetext,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: "btn-warning",
				confirmButtonText: mLangPack.global.yesshare,
				closeOnConfirm: false
			},
			function () {
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.share.php",
					type: "POST",
					dataType: "JSON",
					data: { containerId: mContainerId },
					success: function () { }
				});
				swal(mLangPack.global.shared, mLangPack.global.sharedtext, "success");
			});
		});
	},
	
	initializeCount: function () {
		$.ajax({
			url: "system.ajax/ajax.handle.notifications.unread.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function (ajaxResponse) {
				if(ajaxResponse.friendCount > 0) {
					$(".notificationFriendsCount").fadeIn();
					$(".notificationFriendsCount").text(ajaxResponse.friendCount);
					systemGLOBAL.initializeNotificationFriends();
				}
				
				if(ajaxResponse.messageCount > 0) {
					$(".notificationChatCount").fadeIn();
					$(".notificationChatCount").text(ajaxResponse.messageCount);
					systemGLOBAL.initializeNotificationMessages();
				}
				
				if(ajaxResponse.globalCount > 0) {
					$(".notificationGlobalCount").fadeIn();
					$(".notificationGlobalCount").text(ajaxResponse.globalCount);
					systemGLOBAL.initializeNotificationGlobal();
				}
			}
		});
		
		$("body").on("click", "#chatList", function () {
			$.ajax({
				url: "system.ajax/ajax.handle.notifications.read.php",
				type: "POST",
				dataType: "JSON",
				data: { readParam: 0 },
				success: function () {
					$(".notificationChatCount").fadeOut();
				}
			});
		});
		
		$("body").on("click", "#globalList", function () {
			$.ajax({
				url: "system.ajax/ajax.handle.notifications.read.php",
				type: "POST",
				dataType: "JSON",
				data: { readParam: 1 },
				success: function () {
					$(".notificationGlobalCount").fadeOut();
				}
			});
		});
		
		setTimeout(systemGLOBAL.initializeCount, 5000);
	},
	
	changePictures: function () {
		$("body").on("click", "[data-event=\"change-pictures\"]", function () {
			$("#changeModal").modal("show");
		});
	},
	
	initializeLinkShare: function () {
		var mHasLink = false;
		var mURLRegex = /(https?:\/\/[^\s]+)/g;
		$("body").on("keyup", "#postText", function () {
			if($(this).val().length < 10)
				$("#linkResult").html("");
			
			var mVal = $(this).val();
			mVal.replace(mURLRegex, function(mURL) {
				$.ajax({
					url: "system.ajax/ajax.handle.url.content.php",
					type: "POST",
					dataType: "HTML",
					data: { urlContent: mURL },
					success: function(mSource) {
						var mTitle = $(mSource).filter("title");
						mTitle = $(mTitle).text();
						
						var mMetaDesc = $(mSource).filter("[name=description]");
						mMetaDesc = $(mMetaDesc).attr("content");
						
						if(mMetaDesc === undefined)
							mMetaDesc = "";
						
						$("#linkResult").html("<strong class=\"smallFont\">" + mTitle + "</strong><br /><span class=\"tinyFont\">" + mMetaDesc + "</span>");
					}
				});
			});
		});
	},
	
	loadNotificationCollection: function () {
		$.ajax({
			url: "system.ajax/ajax.load.notifications.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function(jr) {
				$("#notificationListCollection").html(jr.htmlContent);
			}
		});
	}
};
systemGLOBAL.initializeBase();