var mMediaStorage;
var mImageAppended = false;
var mCurrentPosition = 0;
var mLangPack = "";

var systemTimeline = {
	initializeBase: function() {
		$.ajax({
			url: "system.ajax/ajax.handle.language.pack.php",
			type: "POST",
			dataType: "JSON",
			data: { },
			success: function(ajaxResponse) {
				mLangPack = ajaxResponse.langPack;
				$("a[title]").tooltip();
				$(".tagsinput").tagsInput();
				
				$("#privacyButtons .btn").click(function() {
					$("#postPrivacy").val($(this).attr("privacy-value"));
				});
				
				var mMyPost = $("[rel=tooltip]");
				var mSize = $(window).width();
				
				for(i = 0; i < mMyPost.length; i++) {
					mPost = $(mMyPost[i]);
					
					if(mPost.hasClass("invert") && mSize >= 767) {
						mPost.tooltip( { placement: "top"} );
						mPost.css("cursor", "pointer");
					} else {
						mPost.tooltip( { placement: "top"} );
						mPost.css("cursor", "pointer");
					}
				}
				
				systemTimeline.imageLikeEffects();
				systemTimeline.postLocationKeyUp();
				systemTimeline.postMediaLoad();
				systemTimeline.postSubmitA();
				systemTimeline.bottomScrollEvent();
				systemTimeline.likeEvent();
				systemTimeline.commentEvent();
				systemTimeline.submitCommentEvent();
				systemTimeline.removeComment();
				systemTimeline.displayLikes();
				// systemTimeline.popOverProfileInformation();
			}
		});
	},
	
	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>");
					$(".miniFriendsCount").html("<span class=\"label label-primary\">" + jr.friendsCount + "</span>");
					$(".miniFollowerCount").html("<span class=\"label label-primary\">" + jr.followerCount + "</span>");
				}
			});
		});
		
		$("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);
		});
	},
	
	imageLikeEffects: function() {
		$("body").on("dblclick", ".timeline-body, .container-image", function() {
			var mContainerId = $(this).attr("container-id");
			var mSender = $("#timeline-like-event-" + mContainerId);
			var mLikeContainer = $("#container-like-count-" + mContainerId);
			var mLikeCount = parseInt(mLikeContainer.html());
			$("#like-event-icon-id-" + mContainerId).fadeIn(250).fadeOut(250);
			$.ajax({
				url: "system.ajax/ajax.handle.timeline.like.php",
				type: "POST",
				dataType: "JSON",
				data: { containerId: mContainerId },
				success: function(jr) {
					if(jr.isLike == true) {
						mSender.html("<i class=\"glyphicon glyphicon-thumbs-up icon-text\"></i> " + mLangPack.timeline.unlike);
						mLikeContainer.html(mLikeCount + 1);
					}
					else {
						mSender.html("<i class=\"glyphicon glyphicon-thumbs-up icon-text\"></i> " + mLangPack.timeline.like);
						mLikeContainer.html(mLikeCount - 1);
					}
				}
			});
		});
	},
	
	displayLikes: function() {
		$("body").on("click", ".display-likes", function() {
			var mLikesType = $(this).attr("display-likes-type");
			var mLikesIdentifier = $(this).attr(mLikesType + "-id");
			$.ajax({
				url: "system.ajax/ajax.handle.fetch.likes.php",
				type: "POST",
				dataType: "JSON",
				data: { likesIdentifier: mLikesIdentifier, likesType: mLikesType },
				success: function(jsonResponse) {
					swal("", jsonResponse.htmlContainer);
				}
			});
		});
	},
	
	initializeComments: function(mContainerId) {
		$("#commentsFields-" + mContainerId).html("<div class=\"panel-footer\"><center><img src=\"system.assets/images/loader.gif\" /></center></div>");
		$.ajax({
			url: "system.ajax/ajax.handle.timeline.commentload.php",
			type: "POST",
			dataType: "JSON",
			data: { containerId: mContainerId, containerIndex: 0 },
			success: function(jsonResponse) {
				$("#commentsFields-" + mContainerId).html(jsonResponse.commentHTML).slideDown();
				mContainerCollection[mContainerId] = 5;
			}
		}).done(function() {
		});
	},
	
	submitCommentEvent: function() {
		$("body").on("keyup", ".submitCommentEvent", function(mKeyCode) {
			if(mKeyCode.which == 13 && $.trim($(this).val()).length > 0) {
				var mContainerId = $(this).attr("container-id");
				var mContainerFooter = $("#panel-footer-" + mContainerId);
				var mCommentText = $(this).val();
				
				$(this).val("");
				$(this).hide();
				mContainerFooter.html("<center><img src=\"system.assets/images/loader.gif\" /></center>");
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.comment.php",
					type: "POST",
					dataType: "JSON",
					data: { commentText: mCommentText, containerId: mContainerId },
					success: function(jsonResponse) {
						mContainerFooter.html("<input type=\"text\" class=\"form-control submitCommentEvent\" container-id=\"" + mContainerId + "\" />");
						$("#fancyCommentPosition").html("<input type=\"text\" class=\"form-control submitCommentEvent fancyBoxInput\" container-id=\"" + mContainerId + "\" />");
						$(this).fadeIn();
						
						var mCommentCountContainer = $("#container-comment-count-" + mContainerId);
						mCommentCountContainer.html();
						var mCurrentCount = parseInt(mCommentCountContainer.html());
						mCommentCountContainer.html(mCurrentCount + 1);
						
						$.ajax({
							url: "system.ajax/ajax.handle.timeline.commentload.php",
							type: "POST",
							dataType: "JSON",
							data: { containerId: mContainerId, containerIndex: 0, outputType: false },
							success: function(ajaxResponse) {
								$("#fancyCommentArea").html("");
								$("#fancyCommentArea").html(ajaxResponse.commentHTML);
							}
						});
						systemTimeline.initializeComments(mContainerId);
					}
				});
				return false;
			}
		});
	},
	
	removeComment: function() {
		$("body").on("click", ".removeComment", function() {
			var mCommentId = $(this).attr("comment-id");
			swal({
				title: mLangPack.timeline.areyousure,
				text: mLangPack.timeline.norecovercomment,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: 'btn-warning',
				confirmButtonText: mLangPack.timeline.yesdelete,
				closeOnConfirm: false
			}, function() {
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.commentremove.php",
					type: "POST",
					dataType: "JSON",
					data: { commentId: mCommentId },
					success: function(jsonResponse) {
						if(jsonResponse.isValid == true) {
							var mCommentContainer = $("#container-comment-row-" + mCommentId);
							var mCommentContainerTwo = $("[comment-row-id=\"" + mCommentId + "\"]");
							
							var mContainerId = mCommentContainer.attr("container-id");
							var mContainerIdTwo = mCommentContainerTwo.attr("container-id");
							
							mCommentContainer.fadeOut();
							mCommentContainerTwo.fadeOut();
							
							swal(mLangPack.timeline.deleted, mLangPack.timeline.commentdeleted, "success");
							var mCommentCountContainer = $("#container-comment-count-" + mContainerId);
							mCommentCountContainer.html();
							var mCurrentCount = parseInt(mCommentCountContainer.html());
							mCommentCountContainer.html(mCurrentCount - 1);
						}
					}
				});
			});
		});
	},
	
	commentEvent: function() {
		$("body").on("click", ".timeline-comment-event", function() {
			var mContainerId = $(this).attr("container-id");
			systemTimeline.initializeComments(mContainerId);
		});
	},
	
	bottomScrollEvent: function() {
		$(window).scroll(function() {
			if($(window).scrollTop() + $(window).height() == $(document).height())
				systemTimeline.initializeTimeline(false);
		});
	},
	
	initializeAllComments: function() {
		// alert("k");
	},
	
	likeEvent: function() {
		$("body").on("click", ".timeline-like-event", function () {
			var mSender = $(this);
			var mContainerId = mSender.attr("container-id");
			var mLikeContainer = $("#container-like-count-" + mContainerId);
			var mLikeCount = parseInt(mLikeContainer.html());
			$("#like-event-icon-id-" + mContainerId).fadeIn().fadeOut();
			
			$.ajax({
				url: "system.ajax/ajax.handle.timeline.like.php",
				type: "POST",
				dataType: "JSON",
				data: { containerId: mContainerId },
				success: function(jr) {
					if(jr.isLike == true) {
						mSender.html("<i class=\"glyphicon glyphicon-thumbs-up icon-text\"></i> " + mLangPack.timeline.unlike);
						mLikeContainer.html(mLikeCount + 1);
					}
					else {
						mSender.html("<i class=\"glyphicon glyphicon-thumbs-up icon-text\"></i> " + mLangPack.timeline.like);
						mLikeContainer.html(mLikeCount - 1);
					}
				}
			});
		});
	},
	
	postSubmitA: function() {
		$("body").on("click", "#postSubmitA", function() {
			var mPostText = $("#postText").val();
			var mPostLocation = $("#postLocation").val();
			var mPostPrivacy = $("#postPrivacy").val();
			var mPostHashtags = $("#postHashtags").val();
			var mPostMentions = $("#postMentions").val();
			
			$.ajax({
				url: "system.ajax/ajax.handle.timeline.post.php",
				type: "POST",
				dataType: "JSON",
				data: { postText: mPostText, postLocation: mPostLocation, postPrivacy: mPostPrivacy, postHashtags: mPostHashtags, postMentions: mPostMentions, postLocationUser: $("#profileUserId").val() },
				success: function(jsonResponse) {
					if(jsonResponse.isValid == true) { systemGLOBAL.initializeTimeline(true); }
					else { swal(mLangPack.timeline.error, jsonResponse.isValid, "error"); }
				}
			});
		});
	},
	
	escapeHTML: function (mText) {
		'use strict';
		var mChr = { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' };
		return mText.replace(/[\"&<>]/g, function (a) { return mChr[a]; });
	},
	
	postLocationKeyUp: function() {
		$("#postLocation").keyup(function() {
			$("#postLocationImg").attr("src", "http://maps.googleapis.com/maps/api/staticmap?center=" + systemTimeline.escapeHTML($(this).val()) + "&zoom=13&size=575x100&maptype=roadmap");
		});
	},
	
	postMediaPrepareUpload: function (mEvent) {
		mMediaStorage = mEvent.target.files;
		mImageAppended = true;
		
		$("#postButtonType").html("<input type=\"submit\" class=\"btn btn-success btn-outline-rounded green\" value=\"" + mLangPack.timeline.sharepost + "\" />");
		
		var mReader = new FileReader();
		mReader.onload = function(e) {
			$(".postMediaContainer").attr("src", e.target.result);
		}
		mReader.readAsDataURL(mEvent.target.files[0]);
	},
	
	postMediaLoad: function() {
		$("#fileToUpload").on("change", systemTimeline.postMediaPrepareUpload);
		$("#postImageUpload").on("submit", systemTimeline.uploadFilesEvent);
	},
	
	uploadFilesEvent: function (mEvent) {
		mEvent.stopPropagation();
		mEvent.preventDefault();
		
		var mData = new FormData();
		$.each(mMediaStorage, function(mKey, mValue) {
			mData.append(mKey, mValue);
		});
		
		var mPostText = $("#postText").val();
		var mPostLocation = $("#postLocation").val();
		var mPostPrivacy = $("#postPrivacy").val();
		var mPostHashtags = $("#postHashtags").val();
		var mPostMentions = $("#postMentions").val();
			
		$.ajax({
			url: "system.ajax/ajax.handle.file.upload.php?files",
			type: "POST",
			data: mData,
			cache: false,
			dataType: "JSON",
			processData: false,
			contentType: false,
			success: function(xData, mTextStatus, jsXYZ) {
			var mImageAlbumId = $("#postAlbum option:selected").val();
			var mImageHash = xData.uploadedImageHash;
				$.ajax({
					url: "system.ajax/ajax.handle.timeline.post.php",
					type: "POST",
					dataType: "JSON",
					data: { postText: mPostText, postLocation: mPostLocation, postPrivacy: mPostPrivacy, postHashtags: mPostHashtags, postMentions: mPostMentions, postImageHash: mImageHash, postImageAlbumId: mImageAlbumId, postLocationUser: $("#profileUserId").val() },
					success: function(jsonResponse) {
						if(jsonResponse.isValid == true) {  systemTimeline.initializeTimeline(true); }
						else { swal(mLangPack.timeline.error, jsonResponse.isValid, "error"); }
					}
				});
			}
		});
	}
};

systemTimeline.initializeBase();
$("#containerTimeline").fadeIn();