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

var mLangPack = "";

var systemProfile = {
	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");
					}
				}
				
				systemProfile.imageLikeEffects();
				systemProfile.postLocationKeyUp();
				systemProfile.postMediaLoad();
				systemProfile.postSubmitA();
				
				systemProfile.bottomScrollEvent();
				systemProfile.likeEvent();
				systemProfile.commentEvent();
				systemProfile.submitCommentEvent();
				systemProfile.removeComment();
				systemProfile.displayLikes();
				
				systemProfile.initializeSwitchableController();
			}
		});
	},
	
	deplaceSwitchableController: function () {
		$("#timelinePosition").hide().html("").show();
	},
	
	initializeSwitchableController: function() {
		systemProfile.deplaceSwitchableController();
		$("#timelinePosition").append("<ul class=\"timeline\" id=\"containerTimeline\" style=\"width: 100%; min-height: 250px; z-index: 3; margin-top: -50px\"></ul>");
		
		$("body").on("click", "#initTimeline", function() {
			$(".current").removeClass("activeWell");
			$(this).addClass("activeWell");
		
			systemProfile.deplaceSwitchableController();
			$("#timelinePosition").append("<ul class=\"timeline\" id=\"containerTimeline\" style=\"width: 100%; min-height: 250px; z-index: 3; margin-top: -50px\"></ul>");
			$("#upperRow").show();
			
			$("#profileInformation").hide();
			$("#profileGallery").hide();
			$("#profileFriends").hide();
			systemProfile.initializeTimeline(true);
		});
		
		$("body").on("click", "#initInfo", function() {
			$(".current").removeClass("activeWell");
			$(this).addClass("activeWell");
		
			systemProfile.deplaceSwitchableController();
			$("#profileInformation").show();
			
			$("#upperRow").hide();
			$("#profileGallery").hide();
			$("#profileFriends").hide();
		});
		
		$("body").on("click", "#initGallery", function() {
			$(".current").removeClass("activeWell");
			$(this).addClass("activeWell");
		
			systemProfile.deplaceSwitchableController();
			$("#profileGallery").show();
			
			$("#upperRow").hide();
			$("#profileInformation").hide();
			$("#profileFriends").hide();
		});
		
		$("body").on("click", "#initFriends", function() {
			$(".current").removeClass("activeWell");
			$(this).addClass("activeWell");
		
			systemProfile.deplaceSwitchableController();
			$("#profileFriends").show();
			
			$("#upperRow").hide();
			$("#profileInformation").hide();
			$("#profileGallery").hide();
		});
	},
	
	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.profile.unlike);
						mLikeContainer.html(mLikeCount + 1);
					}
					else {
						mSender.html("<i class=\"glyphicon glyphicon-thumbs-up icon-text\"></i> " + mLangPack.profile.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(mLangPack.profile.likedsofar, 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);
							}
						});
						
						systemProfile.initializeComments(mContainerId);
					}
				});
				return false;
			}
		});
	},
	
	removeComment: function() {
		$("body").on("click", ".removeComment", function() {
			var mCommentId = $(this).attr("comment-id");
			
			swal({
				title: mLangPack.profile.areyousure,
				text: mLangPack.profile.norecovercomment,
				type: "warning",
				showCancelButton: true,
				confirmButtonClass: 'btn-warning',
				confirmButtonText: mLangPack.profile.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.profile.deleted, mLangPack.profile.deletedtextcomment, "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");
			systemProfile.initializeComments(mContainerId);
		});
	},
	
	bottomScrollEvent: function() {
		$(window).scroll(function() {
			if($(window).scrollTop() + $(window).height() == $(document).height())
				systemProfile.initializeTimeline(false);
		});
	},
	
	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: $("#profileUserId").val() },
			success: function(jsonResponse) {
				if(mRefresh == true) {
					var mPreviousHTML = $("#postButtonType").html();
					$("#postButtonType").fadeOut(function() {
						$(this).html("<center><h4>" + mLangPack.profile.postsubmitted + "</h4></center>");
					}).fadeIn().delay(1000).fadeOut(function() {
						$(this).html(mPreviousHTML);
					}).fadeIn();
					
					$(".clearfix").remove();
					$("#containerTimeline").html(jsonResponse.containerHTML);
					
					systemProfile.initializeAllComments();
				} else {
					$(".clearfix").remove();
					$("#containerTimeline").html($("#containerTimeline").html() + jsonResponse.containerHTML);
				}
				
				mCurrentPosition = mCurrentPosition + 15;
			},
			error: function() { $("#containerTimeline").html("timeline.load.error"); }
		});
	},
	
	initializeAllComments: function() {
		
	},
	
	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.profile.unlike);
						mLikeContainer.html(mLikeCount + 1);
					}
					else {
						mSender.html("<i class=\"glyphicon glyphicon-thumbs-up icon-text\"></i> " + mLangPack.profile.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) { systemProfile.initializeTimeline(true); }
					else { swal(mLangPack.profile.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=" + systemProfile.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.profile.sharethis + "\" />");
		
		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", systemProfile.postMediaPrepareUpload);
		$("#postImageUpload").on("submit", systemProfile.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) { systemProfile.initializeTimeline(true); }
						else { swal(mLangPack.profile.error, jsonResponse.isValid, "error"); }
					}
				});
			}
		});
	}
};

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