Newer
Older
moodlog_web / habit_ui_script.js
function updateHabit(word) {
    // Fetch data from the server
    fetch('/index.php?action=habit_update&habit=' + encodeURIComponent(word))
        .then(response => response.json())
        .then(data => {
            // Update HTML content based on fetched data
            updateHTML(word, data);
        })
        .catch(error => {
            console.error('Error fetching habit data:', error);
        });
}

function updateHTML(word, data) {
    // Update HTML content based on fetched data
    var habitContainer = document.getElementById(word);

    if (habitContainer) {
        // Update button class and text
        const logButton = habitContainer.querySelector('.habit-log-button');
        if (logButton) {
            logButton.className = 'habit-log-button ' + data.buttonClass;
            logButton.innerText = data.buttonText;
        }

        // Update align class
        const habitTitle = habitContainer.querySelector('.habit-title');
        if (habitTitle) {
            habitTitle.className = data.align + ' habit-title';
        }

       // Update other content as needed
        const scoreValue1 = habitContainer.querySelector('.habit-score .result1');
        if (scoreValue1) {
            scoreValue1.innerText = data.result1;
        }

        const scoreValue2 = habitContainer.querySelector('.habit-score .result2');
        if (scoreValue2) {
            scoreValue2.innerText = data.result2;
        }

        const scoreValue3 = habitContainer.querySelector('.habit-score .result3');
        if (scoreValue3) {
            scoreValue3.innerText = data.result3;
        }

        if(data.freq == "d"){
        	// Destroy existing Cal-HeatMap instance
	        //destroyCalHeatMap(word);

	        // Reinitialize Cal-HeatMap with updated data
	        calHeatMapInstances[word] = initializeDailyCalendar('#habit-cal-'+word, {
				data: "/index.php?action=habit_cal_daily&habit="+word,
				id: word,
				legendColors: {
					min: data.calCol,
					max: data.calCol,
				},
			});

        }
        if(data.freq == "w"){
			// Get the current date
			const currentDate = new Date();

			// Calculate year, month, and week number for today
			const year = currentDate.getFullYear();
			const month = currentDate.getMonth() + 1; // Months are zero-indexed
			const weekNo = getWeekNumber(currentDate);

			// Build the "year-month-weekno" string
			const yearMonthWeekNoString = `${year}-${padNumber(month)}-${padNumber(weekNo)}`;

			// Construct the ID of the parent div
			const parentDivId = "habit-cal-" + word; // Replace "your_word_here" with the actual word

			// Get the parent div element
			const parentDiv = document.getElementById(parentDivId);

			// Check if the parent div exists
			if (parentDiv) {
				//console.log('Parent div found:', parentDiv);
			  	// Find the "year-month-weekno" element within the parent div
				const element = parentDiv.querySelector(`[id='${yearMonthWeekNoString}']`);

				// Check if the element exists
				if (element && parentDiv.contains(element)) {
					//console.log('Element found:', element);
				  	// Remove the classes "neut" and "green"
				  	element.classList.remove("neut", "green");

				  	// Set the text content to the value of data.buttonText
				  	element.textContent = data.buttonText;
				  	if( data.weekSoFar > 0 ){
					  	if (data.weekSoFar < data.weekGoal) {
					    	element.classList.add("neut");
					    	element.textContent = data.weekSoFar;
					  	}
					  	if (data.weekSoFar >= data.weekGoal) {
					    	element.classList.add("green");
					  	}
					}
				}
			}
		}
        // Add code to update other elements as needed
    } else {
        console.error('Habit container not found for word:', word);
    }
}

// Function to pad a number with leading zeros (if needed)
function padNumber(number) {
  return number.toString().padStart(2, "0");
}

// Function to get the ISO week number of a date
function getWeekNumber(date) {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() + 4 - (d.getDay() || 7));
  const yearStart = new Date(d.getFullYear(), 0, 1);
  const weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
  return weekNo;
}