Skip to content

Commit

Permalink
Goodbye world
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidS12321 committed Feb 3, 2024
1 parent 8c25baa commit 71829bf
Show file tree
Hide file tree
Showing 2 changed files with 170 additions and 8 deletions.
171 changes: 166 additions & 5 deletions filter.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,45 @@ document.addEventListener('DOMContentLoaded', function () {
});
});

async function fetchReviews(placeName) {
try {
const response = await fetch(`http://localhost:3000/reviews?place=${placeName}`);
if (!response.ok) {
throw new Error('Failed to fetch reviews');
}
const reviews = await response.json();
return reviews;
} catch (error) {
console.error(error);
return [];
}
}

// Save a review to your backend
async function saveReview(placeName, rating, comment) {
try {
const response = await fetch('http://localhost:3000/reviews', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
place: placeName,
rating: rating,
comment: comment,
}),
});

if (!response.ok) {
throw new Error('Failed to submit review');
}

console.log('Review submitted successfully');
} catch (error) {
console.error(error);
}
}

// Add event listener to the search input
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', applyFilters);
Expand All @@ -31,13 +70,40 @@ document.addEventListener('DOMContentLoaded', function () {
learnMoreButtons.forEach(function (button) {
button.addEventListener('click', handleLearnMoreClick);
});

// Add click event listener to the "Reviews" link
const reviewsLink = document.querySelector('nav a[href="reviews.html"]');
reviewsLink.addEventListener('click', function (event) {
event.preventDefault();

// Fetch the place name dynamically or use a default value
const placeName = 'Starbucks';

// Render reviews for the selected place
renderReviews(placeName);
});

// Display average ratings and reviews when the page is loaded
displayAverageRatings();
renderReviews();

// Additional code for integrating the review changes
const reviewForm = document.getElementById('reviewForm');
const placeSelect = document.getElementById('placeSelect');

// Add event listener to the form
reviewForm.addEventListener('submit', function (event) {
event.preventDefault();
const selectedPlace = placeSelect.value;
submitReview(selectedPlace);
});
});

function applyFilters() {
// Get selected values from checkboxes
const selectedMeals = getSelectedValues('meal');
const selectedCuisines = getSelectedValues('cuisine');
const selectedDietaryRestrictions = getSelectedValues('restrictions'); // New line
const selectedDietaryRestrictions = getSelectedValues('restrictions');

// Get all place boxes
const placeBoxes = document.querySelectorAll('.place-box');
Expand All @@ -48,19 +114,19 @@ function applyFilters() {
// Iterate over place boxes to show/hide based on filters and search query
placeBoxes.forEach(function (placeBox) {
const placeMeal = placeBox.getAttribute('data-meal');
const placeCuisine = placeBox.getAttribute('data-cuisine').split(' '); // Split into an array
const placeDietaryRestrictions = placeBox.getAttribute('data-restrictions').split(' '); // New line
const placeCuisine = placeBox.getAttribute('data-cuisine').split(' ');
const placeDietaryRestrictions = placeBox.getAttribute('data-restrictions').split(' ');

const isMealMatch = selectedMeals.length === 0 || selectedMeals.some(meal => placeMeal.includes(meal));
const isCuisineMatch = selectedCuisines.length === 0 || selectedCuisines.every(cuisine => placeCuisine.includes(cuisine));
const isDietaryRestrictionsMatch = selectedDietaryRestrictions.length === 0 || selectedDietaryRestrictions.every(dr => placeDietaryRestrictions.includes(dr)); // New line
const isDietaryRestrictionsMatch = selectedDietaryRestrictions.length === 0 || selectedDietaryRestrictions.every(dr => placeDietaryRestrictions.includes(dr));

// Add search functionality
const placeName = placeBox.querySelector('h3').innerText.toLowerCase();
const isSearchMatch = placeName.includes(searchQuery);

// Show/hide place box based on filters and search query
placeBox.style.display = isMealMatch && isCuisineMatch && isDietaryRestrictionsMatch && isSearchMatch ? 'block' : 'none'; // Updated line
placeBox.style.display = isMealMatch && isCuisineMatch && isDietaryRestrictionsMatch && isSearchMatch ? 'block' : 'none';
});
}

Expand All @@ -84,4 +150,99 @@ function handleButtonClick() {
function handleLearnMoreClick(event) {
// Open the link in a new tab
window.open(event.target.href, '_blank');
}

function displayAverageRatings() {
// Loop through each place and display the average rating
document.querySelectorAll('.place-box').forEach(function (placeBox) {
const placeName = placeBox.querySelector('h3').innerText;
const averageRating = calculateAverageRating(placeName);
const ratingElement = document.getElementById(`${placeName}-rating`);
if (ratingElement) {
ratingElement.innerText = averageRating.toFixed(1);
}
});
}

function calculateAverageRating(placeName) {
const reviews = getReviewsForPlace(placeName);
if (reviews.length === 0) {
return 0;
}

const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0);
return totalRating / reviews.length;
}

function renderReviews(selectedPlace) {
const reviewContainer = document.querySelector('.review-container');

// Fetch reviews for the selected place from storage or a server
const reviews = getReviewsForPlace(selectedPlace);

// Clear the existing reviews
reviewContainer.innerHTML = '';

// Loop through each review and display it
reviews.forEach(function (review) {
const reviewElement = document.createElement('div');
reviewElement.innerHTML = `
<p>Place: ${selectedPlace}</p>
<p>Rating: ${review.rating}</p>
<p>Comment: ${review.comment}</p>
`;
reviewContainer.appendChild(reviewElement);
});
}

// Replace the getReviewsForPlace function
async function getReviewsForPlace(placeName) {
try {
// Assuming you have an API endpoint to fetch reviews based on placeName
const response = await fetch(`https://your-api-endpoint/reviews?place=${placeName}`);
const reviews = await response.json();
return reviews;
} catch (error) {
console.error('Error fetching reviews:', error);
return [];
}
}

function submitReview(placeName) {
const ratingInput = document.getElementById(`${placeName}-rating`);
const commentInput = document.getElementById(`${placeName}-comment`);

if (ratingInput.checkValidity()) {
const rating = parseInt(ratingInput.value, 10);
const comment = commentInput.value;

// You can save the review to storage or a server here
saveReview(placeName, rating, comment);

// Clear the form inputs
ratingInput.value = '';
commentInput.value = '';

// Re-render the reviews on the page for the specific place
renderReviews(placeName);
} else {
alert('Please enter a valid rating (1-5).');
}
}

// Save a review to local storage
function saveReview(placeName, rating, comment) {
// Retrieve existing reviews from local storage
const existingReviews = JSON.parse(localStorage.getItem('reviews')) || [];

// Add the new review
existingReviews.push({ place: placeName, rating: rating, comment: comment });

// Save the updated reviews back to local storage
localStorage.setItem('reviews', JSON.stringify(existingReviews));
}

// Fetch reviews from local storage
function getStoredReviews() {
return JSON.parse(localStorage.getItem('reviews')) || [];
}
7 changes: 4 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="reviews.html">Reviews</a></li>
<li><img src="cppLogo.jpg" alt="Dining Guide Logo" class="logo-image"></li>
<li><a href="#places">Places to Eat</a></li>
<li><a href="https://www.foundation.cpp.edu/dining/hours/current/index.htm" target="_blank">Dining Hours</a></li>
Expand Down Expand Up @@ -80,7 +80,7 @@ <h3>Dietary Restrictions</h3>

<div class="place-container">
<!-- Place boxes will be dynamically added here using JavaScript -->
<div class="place-box" data-meal="breakfast snacks drinks" data-cuisine="american" data-restrictions="vegan gluten-free">
<div class="place-box" data-meal="breakfast snacks drinks" data-cuisine="american" data-restrictions="vegan gluten-free" data-place="Starbucks">
<img src="https://media.designrush.com/inspiration_images/137088/conversions/_1525811908_162_Starbucks-Logo-Full-mobile.jpg" alt="Restaurant 1" width = "300" length = "300">
<h3>Starbucks</h3>
<p>A cozy place offering a variety of delicious meals. Perfect for a quick bite or a leisurely meal.</p>
Expand Down Expand Up @@ -111,6 +111,7 @@ <h3>QDoba</h3>
<div class="place-box" data-meal="lunch_dinner drinks" data-cuisine="asian" data-restrictions="">
<img src="https://foundation.cpp.edu/dining/assets/img/logo/Hibachi-Logo-400w.jpg" alt="Restaurant 5" width = "300" length = "300">
<h3>Hibachi-San</h3>
<p>Where culinary artistry meets a vibrant dining experience. Whether you're a sushi enthusiast or crave the rich flavors of stir-fried delights, our diverse menu caters to every palate!</p>
<a href="https://auxiliarydocs.ucr.edu/dining/hibachi-san-menu.pdf?_gl=1*z8falo*_ga*MjAxNjYwMDE3OC4xNjg5MTA0MTQ3*_ga_S8BZQKWST2*MTY4OTE5NjAyNC40LjEuMTY4OTE5NzI3Ny4wLjAuMA..*_ga_Z1RGSBHBF7*MTY4OTE5NjAyNC40LjEuMTY4OTE5NzI3Ny4wLjAuMA" target="_blank" class="learn-more">Learn More</a>
</div>

Expand Down Expand Up @@ -171,7 +172,7 @@ <h3>FitBites</h3>
<a href="https://www.foundation.cpp.edu/dining/restaurants-fitbites.aspx" target="_blank" class="learn-more">Learn More</a>
</div>
</section>

<footer>
<p>&copy; 2024 CPP On-Campus Dining Guide. All rights reserved.</p>
</footer>
Expand Down

0 comments on commit 71829bf

Please sign in to comment.