document.addEventListener('DOMContentLoaded', function () {

	toastr.options = {
		"closeButton": true,
		"debug": false,
		"newestOnTop": false,
		"progressBar": true,
		"positionClass": "toast-top-center",
		"preventDuplicates": false,
		"showDuration": "300",
		"hideDuration": "1000",
		"timeOut": "60000",
		"extendedTimeOut": "0",
		"showEasing": "swing",
		"hideEasing": "linear",
		"showMethod": "fadeIn",
		"hideMethod": "fadeOut"
	}

	var isMobile  = parseInt($('#isMobile').text());
	if ( isMobile == 1 ) {
		var aspectRatio = 1;
		var fadeSpeed = 150;
	} else {
		var aspectRatio = 2;
		var fadeSpeed = 0;
	}

	if ( $('.socialCalendar').length ) {
		var aspectRatio = 1;
	}

    var loader     = '<div class="d-flex"><div class="spinner-border text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';
	var events     = JSON.parse(document.getElementById('events').innerHTML);
	var logDrawer  = new bootstrap.Offcanvas(document.getElementById('logDrawer'));
	var calendarEl = document.getElementById('calendarEl');
	var calendar   = new FullCalendar.Calendar(calendarEl, {
		initialView: 'dayGridMonth',
		events: events,
		aspectRatio: aspectRatio,
		fixedWeekCount: false,
		showNonCurrentDates: false,
		titleFormat: {
			month: 'short',
			year: 'numeric',
		},
		themeSystem: 'bootstrap5',
		dateClick: function (info) {
			var clickedDate = info.dateStr;

			var ids = [];
			for (var i = 0; i < events.length; i++) {
				var eventDate = events[i].start.split(' ')[0];
				if (eventDate == clickedDate) {
					ids.push(events[i].commentId);
				}
			}

			if ( !ids.length ) {
				return;
			}

			var displayDate = new Date(clickedDate);
			displayDate.setDate(displayDate.getDate() + 1); //had to add 1 day to this to make it match the correct date? check console.log above and see https://bobbyhadz.com/blog/javascript-check-if-date-is-today#check-if-a-date-is-tomorrows-date-in-javascript
			$('#logDrawerLabel').text('Logs for '+displayDate.toLocaleString('en-us', {weekday: 'short', month: 'short', day: 'numeric'}));
			logDrawer.show();

			//load logs
			$('#logContainer').html(loader+"<span>Loading logs...</span>");
			$.ajax({
				url: '/clients/project/ajax/daily-log.php',
				method: 'POST',
				data: {
					ids: ids,
					projectId: $('#projectId').val()
				},
				success: function (data) {
					$('#logContainer').html(data);

					initObserver();

					//weather
					$('.dailyLog').each(function() {
						let projectId = $(this).data('project');
						let commentId = $(this).data('id');
						let time      = $(this).data('time');
						$.ajax({
							url: '/clients/project/ajax/daily-log-weather.php',
							method: 'POST',
							data: {
								projectId: projectId,
								commentId: commentId,
								time: time
							},
							success: function (data) {
								$('#'+time).html(data);
							},
							error: function (e) {
								console.log(e);
							}
						});
					});
				},
				error: function (e) {
					var error = e.responseJSON.error;
					console.log(error);
				}
			});
		},
	});

	calendar.render();

	$.ajax({
		url: '/clients/project/ajax/forecast.php',
		method: 'POST',
		data: {
			zip: $('#zip').val(),
			view: $('#view').val()
		},
		success: function (response) {
			// console.log(response);
			var response = JSON.parse(response);
			var data     = JSON.parse(response.data);
			var lat      = data.lat;
			var lon      = data.lon;
			if ( !$(response.html).find('.forecast-day').length ) {
				$('#forecast').html('<div class="m-5">Error loading weather forecast</div>');
			} else {
				$('#forecast').html(response.html);			}
		},
		error: function (e) {
			$('#forecast').html('<div class="m-5">Error loading weather forecast</div>');
		}
	});

	$(document).on('change', 'input[type=radio][name=forecast-btn]', function(e) {
		let trgt = $(this).data('container');

		if ( trgt == 'forecast-8d' ) {
			$('#forecast-48h').addClass('d-none');
			$('#forecast-btn-48h').prop('checked', false);
			$('#forecast-8d').removeClass('d-none');
			$('#forecast-btn-8d').prop('checked', true);
		} else {
			$('#forecast-8d').addClass('d-none');
			$('#forecast-btn-8d').prop('checked', false);
			$('#forecast-48h').removeClass('d-none');
			$('#forecast-btn-48h').prop('checked', true);
		}
	});

	$(document).on('shown.bs.collapse', '#calendar', function(e) {
		calendar.updateSize();
	});

	Fancybox.bind("[data-fancybox]", {
		Toolbar: {
			display: {
				left: ["infobar"],
				middle: [],
				right: ["iterateZoom", "slideshow", "thumbs", "download", "close"],
			},
		},
	});

	$(document).on('click', '.btbLike', function(e) {
		var commentId = $(this).data('comment-id');
		let loader    = '<div class="spinner-border spinner-border-sm text-danger" role="status"></div>';
		$('#btb-post-like-icon-'+commentId).html(loader);

		$.ajax({
			url: '/clients/project/ajax/like.php',
			method: 'POST',
			data: {
				cid: commentId
			},
			success: function (data) {
				// console.log(data);
				var response   = JSON.parse(data);
				var buttonIcon = response.buttonIcon;
				var likeText   = response.likeText;
				var likedBy    = response.likedBy;
				
				$('#btb-post-like-icon-'+commentId).html(buttonIcon);
				$('#btb-post-like-count-'+commentId).text(likeText);

				if ( likedBy.length > 0 ) {
					// console.log('here');
					$('#btb-post-like-count-'+commentId).attr('data-bs-toggle', 'tooltip');
					$('#btb-post-like-count-'+commentId).attr('data-bs-html', 'true');
					$('#btb-post-like-count-'+commentId).attr('data-bs-title', likedBy);
				} else {
					$('#btb-post-like-count-'+commentId).removeAttr('data-bs-toggle');
					$('#btb-post-like-count-'+commentId).removeData('bs-toggle');
					
					$('#btb-post-like-count-'+commentId).removeAttr('data-bs-html');
					$('#btb-post-like-count-'+commentId).removeData('bs-html');
					
					$('#btb-post-like-count-'+commentId).removeAttr('data-bs-title');
					$('#btb-post-like-count-'+commentId).removeData('bs-title');

					var tt = bootstrap.Tooltip.getInstance('#btb-post-like-count-'+commentId);
					// console.log(tt);
					tt.dispose();
				}

				const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
				const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
			},
			error: function (e) {
				$('#btb-post-like-icon-'+commentId).html('<i class="bi bi-hand-thumbs-up"></i>');
				toastr["error"](e.responseText, "Error");
			},
		});
	});

	$(document).on('click', '.btbPostComment', function(e) {
		let loader    = '<div class="spinner-border spinner-border-sm text-danger" role="status"></div>';

		var commentId = $(this).data('comment-id');
		var text      = $('#textarea-'+commentId).val();

		$('#textarea-'+commentId).prop('disabled', true);
		$('#btb-post-reply-btn-'+commentId).html(loader);

		if ( text.trim().length > 0 ) {
			$.ajax({
				url: '/clients/project/ajax/reply.php',
				method: 'POST',
				data: {
					commentId: commentId,
					text: text.trim(),
					projectId: $('#projectId').val()
				},
				success: function (data) {
					// console.log(data);
					let response = JSON.parse(data);
					let commentHtml = response.commentHtml;
					let countHtml   = response.countHtml;
					let replyId     = response.replyId;
					let toggleHtml  = response.toggleHtml;

					if ( $('#btb-reply-collapse-'+commentId).length ) {
						$('#btb-reply-collapse-'+commentId).append(commentHtml);
					} else {
						$('#btb-post-replies-'+commentId).append(commentHtml);	
					}

					$('#textarea-'+commentId).css('height', '50px');
					$('#textarea-'+commentId).val('');
					$('#textarea-'+commentId).prop('disabled', false);
					$('#btb-post-reply-btn-'+commentId).html('<i class="bi bi-send text-danger"></i>');

					$('#btb-post-comment-count-'+commentId).html(countHtml);

					$('#btb-reply-collapse-container-'+commentId).html(toggleHtml);
					$('#btb-reply-collapse-'+commentId).addClass('show');
					// $('#btb-reply-collapse-toggle-'+commentId).text('Hide comments');

					document.getElementById('btb-reply-'+replyId).scrollIntoView({block: 'center'});
				},
				error: function (e) {
					$('#textarea-'+commentId).val('');
					$('#textarea-'+commentId).prop('disabled', false);
					$('#btb-post-reply-btn-'+commentId).html('<i class="bi bi-send text-danger"></i>');
					toastr["error"](e.responseText, "Error");
				}
			});
		} else {
			$('#textarea-'+commentId).prop('disabled', false);
			$('#btb-post-reply-btn-'+commentId).html('<i class="bi bi-send text-danger"></i>');
		}
	});

	$('textarea').on('focus', function(e) {
		autosize(this);
	});
	$('textarea').on('blur', function(e) {
		let h = this.offsetHeight;
		autosize.destroy(this);

		this.style.height       = h + 'px';
		this.style.overflow     = 'hidden';
		this.style.overflow     = 'hidden';
		this.style.overflowWrap = 'break-word';
		this.style.textAlign    = 'start';
	});

	$(document).on('click', '.btbWeather', function(e) {
		let titleLoader  = '<div class="d-flex align-items-center"><div class="spinner-border spinner-border-sm text-danger" role="status"></div></div>';
		let bodyLoader   = '<div class="d-flex align-items-center justify-content-center"><div class="spinner-border text-danger" role="status"></div></div>';
		let date         = $(this).data('date');
		let dDate        = $(this).data('date-display');

		$('#weatherModalTitle').html(titleLoader);
		$('#weatherModalBody').html(bodyLoader);
		$.ajax({
			url: '/clients/project/ajax/weather-social.php',
			method: 'POST',
			data: {
				projectId: $('#projectId').val(),
				date: date
			},
			success: function (data) {
				console.log(data);
				$('#weatherModalTitle').text("Weather for "+dDate);
				$('#weatherModalBody').html(data);
			},
			error: function (e) {
				$('#weatherModalBody').html('<p>Failed to load weather.</p>');
			}
		});
	});

	if ( $('#taskList').length ) {
		var taskListCollapse = new bootstrap.Collapse('#taskList', {'toggle': false});
	}

	if ( window.location.hash ) {
		if ( $('#taskList').length ) {
			taskListCollapse.show();
		}
	}
	$(document).on('hidden.bs.collapse', '#taskList', function(e) {
		$('.taskListToggle').text('Expand');
	});
	$(document).on('shown.bs.collapse', '#taskList', function(e) {
		$('.taskListToggle').text('Collapse');
	});
	$(document).on('click', '.taskNotification', function(e) {
		taskListCollapse.show();
	});

	const dz = new Dropzone("div#updateDropzone", {
		init: function() {
			this.on('addedfile', function(file, response) {
				$('#addImages').hide();
				let ext = file.name.split('.').pop();
				if ( ext == 'pdf' || ext == 'PDF' ) {
					$(file.previewElement).find(".dz-details img").attr("src", "/clients/assets/images/pdf-icon.png").css('width', '120px').css('height', '120px');
				}
			});
			this.on("sendingmultiple", function(file, xhr, formData) {
				let text = $('#textarea-post-update').val();
				if ( !text ) {
					return;
				}
				formData.append('text', text);
				formData.append('projectId', $('#projectId').val());
				// console.log(formData);
			});
			this.on('successmultiple', function(file, response) {
				// console.log(response);
				dz.removeAllFiles();
				$('#textarea-post-update').val('');
				$('#textarea-post-update').prop('disabled', false);
				$('#btb-post-update-btn').html('<i class="bi bi-send text-danger"></i>');
				$('#addImages').show();

				toastr["success"]("Your post was created successfully. Please allow up to 60 seconds for the post to be visible in the portal.", "Post created successfully")
			});
			this.on('errormultiple', function(file, message) {
				console.log(message);
				$('#textarea-post-update').prop('disabled', false);
				$('#btb-post-update-btn').html('<i class="bi bi-send text-danger"></i>');

				toastr["error"](message, "Error");
			});
			this.on('reset', function() {
				$('#addImages').show();
			});
		}, 
		url: "/clients/project/ajax/post.php",
		// addRemoveLinks: true,
		autoProcessQueue: false,
		uploadMultiple: true,
		acceptedFiles: 'image/jpeg,image/png,application/pdf',
		parallelUploads: 12,
		maxFilesize: 30,
		maxFiles: 12,
		previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
	});

	$("#btb-post-update-btn").click(function (e) {
		let loader    = '<div class="spinner-border spinner-border-sm text-danger" role="status"></div>';
		$('#textarea-post-update').prop('disabled', true);
		$('#btb-post-update-btn').html(loader);

		let text = $('#textarea-post-update').val();
		if ( !text ) {
			alert('All posts must contain text.');
			$('#textarea-post-update').prop('disabled', false);
			$('#btb-post-update-btn').html('<i class="bi bi-send text-danger"></i>');

			return;
		}

		dz.getRejectedFiles().forEach((file, i) => dz.removeFile(file));

		if ( dz.files.length > 0 ) {
			dz.processQueue();
		} else {
			// console.log(dz);
			$.ajax({
				url: '/clients/project/ajax/post.php',
				method: 'POST',
				data: {
					projectId: $('#projectId').val(),
					text: text
				},
				success: function (data) {
					// console.log(data);
					$('#textarea-post-update').val('');
					$('#textarea-post-update').prop('disabled', false);
					$('#btb-post-update-btn').html('<i class="bi bi-send text-danger"></i>');
					$('#addImages').show();

					toastr["success"]("Your post was created successfully. Please allow up to 60 seconds for the post to be visible in the portal.", "Post created successfully")
				},
				error: function (e) {
					// console.log(e);
					$('#textarea-post-update').prop('disabled', false);
					$('#btb-post-update-btn').html('<i class="bi bi-send text-danger"></i>');

					toastr["error"]("There was an error creating your post. Response: "+e.responseText, "Post creation failed");
				}
			});
		}
	});

	const pdz = new Dropzone("div#plansDropzone", {
		init: function() {
			let planListHtml = $('#planList').html();

			this.on('addedfile', function(file, response) {
				$('#addPlans').hide();
				let ext = file.name.split('.').pop();
				if ( ext == 'pdf' || ext == 'PDF' ) {
					$(file.previewElement).find(".dz-details img").attr("src", "/clients/assets/images/pdf-icon.png").css('width', '120px').css('height', '120px');
				}
			});
			this.on("sending", function(file, xhr, formData) {
				$('#planList').html(loader);
				formData.append('projectId', $('#projectId').val());
			});
			this.on('success', function(file, response) {
				// console.log(response);
				pdz.removeAllFiles();
				$('#addPlans').show();
				toastr["success"]("File uploaded", "Success");

				$('#planList').html(response);
			});
			this.on('error', function(file, message) {
				// console.log(message);
				toastr["error"](message, "Error");
				$('#planList').html(planListHtml);
			});
			this.on('reset', function() {
				$('#addPlans').show();
			});
		}, 
		url: "/clients/project/ajax/plans.php",
		// addRemoveLinks: true,
		autoProcessQueue: true,
		uploadMultiple: false,
		acceptedFiles: 'application/pdf',
		parallelUploads: 1,
		maxFilesize: 30,
		maxFiles: 11,
		previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-filename"><span data-dz-name></span></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
	});

	$(document).on('click', '.btbDeletePlan', function(e) {
		if ( confirm("Are you sure you want to delete this plan PDF?") == true ) {
			let planListHtml = $('#planList').html();
			$('#planList').html(loader);
	
			$.ajax({
				url: '/clients/project/ajax/delete-plan.php',
				method: 'POST',
				data: {
					planId: $(this).data('id'),
				},
				success: function(data) {
					toastr["success"]("Plan deleted", "Success");
					$('#planList').html(data);
				},
				error: function(e) {
					toastr["error"](message, "Error");
					$('#planList').html(planListHtml);
				},
			});
		}
	});

	$(document).on('click', '#createModel', function(e) {
		let modelListHtml = $('#modelList').html();
		$('#modelList').html(loader);

		let modelId = $('#modelId').val();
		if ( !modelId ) {
			alert('Enter a sketchfab model ID');
			return;
		}

		let smLoader = '<div class="d-flex"><div class="spinner-border spinner-border-sm text-light" role="status"><span class="visually-hidden">Loading...</span></div></div>';
		$('#createModel').html(smLoader);
		$.ajax({
			url: '/clients/project/ajax/models.php',
			method: 'POST',
			data: {
				projectId: $('#projectId').val(),
				// modelId: $('#modelId').val(),
				modelId: modelId
			},
			success: function(data) {
				toastr["success"]("Model added", "Success");
				$('#modelId').val('');
				$('#createModel').text('Go');
				$('#modelList').html(data);
			},
			error: function(e) {
				toastr["error"](e.responseText, "Error");
				$('#createModel').text('Go');
				$('#modelList').html(modelListHtml);
			},
		});
	});

	$(document).on('click', '.btbDeleteModel', function(e) {
		if ( confirm("Are you sure you want to delete this 3D model?") == true ) {
			let modelListHtml = $('#modelList').html();
			$('#modelList').html(loader);
	
			$.ajax({
				url: '/clients/project/ajax/delete-model.php',
				method: 'POST',
				data: {
					modelId: $(this).data('id'),
				},
				success: function(data) {
					toastr["success"]("Model deleted", "Success");
					$('#modelList').html(data);
				},
				error: function(e) {
					toastr["error"](message, "Error");
					$('#modelList').html(modelListHtml);
				},
			});
		}
	});
});