var iconBase = "https://www.traveldubuque.com/images/travel-dubuque/global/map/";
var icons = {
	
	shoppingfamily: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	events: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	takeoutguide: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	explore: {
		icon: 'https://www.traveldubuque.com/images/travel-dubuque/global/map/map_icon-explore.png',
	},
	
	casualdiningsweettreats: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	meetings: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	sales: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	taste: {
		icon: 'https://www.traveldubuque.com/images/travel-dubuque/global/map/map_icon-taste.png',
	},
	
	stay: {
		icon: 'https://www.traveldubuque.com/images/travel-dubuque/global/map/map_icon-stay.png',
	},
	
	plan: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	more: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	winter: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	fall: {
		icon: iconBase + 'map_icon-default.png',
	},
	
	heart: '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><g class="nc-icon-wrapper"><path fill="#E86C60" d="M34,2c-3.89551,0-7.54102,1.73389-10,4.69824C21.54102,3.73389,17.89551,2,14,2C6.83203,2,1,7.83154,1,15 c0,12.33203,21.45312,30.02686,22.36719,30.77393C23.55078,45.9248,23.77539,46,24,46s0.44922-0.0752,0.63281-0.22607 C25.54688,45.02686,47,27.33203,47,15C47,7.83154,41.16797,2,34,2z"></path></g></svg>'
}

var app = new Vue({
	el: '#app',
	data: {
		isLoading: false,
		partners: [],
		category_filter: [],
		details_filter: [],
		location_filter: [],
		favorite_list: [],
		map: null,
		bounds: null,
		markers: [],
		clusters: null,
		infowindow: [],
		show_map: true,
		page_filter: "shopping"
	},
	computed: {favorite_link: function() {
	var link = "https://www.traveldubuque.com/your-favorites?entries="
	this.favorite_list.forEach(function(fav){
		link = link + fav.entry_id + '|';
	});
	return link;
},
mail_favorites: function() {
	var link = "mailto:?";
	var subject = "subject=" + encodeURIComponent("Your Favorites from Travel Dubuque");
	var body = "&body=" + this.favorite_link;
	return link + subject + body;
},
		categories() {
			let categories = [];

			this.filteredList.forEach((partner, index) => {
				if(partner?.categories) {
					partner.categories.forEach(category => {
						if(category != '') {
							if(!categories.includes(category)) categories.push(category);
						}
					})
				}
			});

			return _.sortBy(categories);
		},
		details(){
			let details = [];

			this.filteredList.forEach(partner => {
				partner.details.forEach(detail => {
					if(!details.includes(detail)) details.push(detail);
				})
			});
			
			return _.sortBy(details);
		},
		locations(){
			let locations = [];

			this.filteredList.forEach((partner, index) => {
				if(partner?.locations) {
					partner.locations.forEach(location => {
						if(!locations.includes(location)) locations.push(location);
					})
				}
			});

			return _.sortBy(locations);
		},

		filteredList(){

			let partners = this.partners;

			const category_filter = this.category_filter
			const details_filter = this.details_filter
			const location_filter = this.location_filter
			const self = this;


			partners = _.filter(this.partners, function(partner) {
				// return partner.categories.includes(self.capitalizePageFilter)
				return partner.categories.includes(self.page_filter)
			})


		    if(this.category_filter.length) {
		    	self.category_filter.forEach(category => {
		    		partners = _.filter(partners, function(partner) {
		    			return partner.categories.includes(category)
		    		});
		    	})
		    }

		   if(this.details_filter.length) {
		    	self.details_filter.forEach(detail => {
		    		partners = _.filter(partners, function(partner) {
		    			return partner.details.includes(detail)
		    		});
		    	})
		    }

		    if(this.location_filter.length) {
		    	self.location_filter.forEach(location => {
		    		partners = _.filter(partners, function(partner) {
		    			return partner.locations.includes(location)
		    		});
		    	})
		    }

			let sponsors = [];
			let photos = [];
			let basic = [];


			if(partners.length) {
				sponsors = _.filter(partners, { 'isSponsor': true });
				photos = _.filter(partners, { 'isSponsor': false, 'has_photo': true });
				basic = _.filter(partners, { 'isSponsor': false, 'has_photo': false });
			}

			partners = sponsors.concat(photos).concat(basic);


			return partners			
		},

	},
	watch: {
		favorite_list: {
			handler: function(val) {
				localStorage.setItem("favorites", JSON.stringify(val));
			},
			deep: true
		},

		category_filter: {
			handler: function(val) {
				this.updateMapMarkers();
				this.scrollTopAttractions();
			},
			deep: true
		},

		details_filter: {
			handler: function(val) {
				this.updateMapMarkers();
				this.scrollTopAttractions();
			},
			deep: true
		},

		location_filter: {
			handler: function(val) {
				this.updateMapMarkers();
				this.scrollTopAttractions();
			},
			deep: true
		},

	},
	filters: {formatTime: function(value) {
	value = [value.slice(0, 2), ':', value.slice(2)].join('')+':00';
	if (value !== null && value !== undefined){ //If value is passed in
		if(value.indexOf('AM') > -1 || value.indexOf('PM') > -1){ //If time is already in standard time then don't format.
			return value;
		}
		else {
			var hour = value.substring ( 0,2 ); //Extract hour
			var minutes = value.substring ( 3,5 ); //Extract minutes
			var identifier = 'AM'; //Initialize AM PM identifier

			if(hour == 12){ //If hour is 12 then should set AM PM identifier to PM
				identifier = 'PM';
			}
			if(hour == 0){ //If hour is 0 then set to 12 for standard time 12 AM
				hour=12;
			}
			if(hour > 12){ //If hour is greater than 12 then convert to standard 12 hour format and set the AM PM identifier to PM
				hour = hour - 12;
				identifier='PM';
			}
			/*if(hour < 10) {
				hour = hour.substr(1);
			}*/
			return hour + ':' + minutes + ' ' + identifier; //Return the constructed standard time
		}
	}
},
digitToDay: function(value){
	var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	return days[value];
},
capitalize: function(value) {
	if (!value) return ''
	value = value.toString()
	return value.charAt(0).toUpperCase() + value.slice(1)
},
uppercase: function(value) {
	return _.toUpper(value);
},
round: function(value) {
	var multiplier = Math.pow(10, 1 || 0);
	value = Math.round(value * multiplier) / multiplier;

	// Split the input string into two arrays containing integers/decimals
	var res = value.toString().split(".");     
	// If there is no decimal point or only one decimal place found.
	if(res.length === 1) { 
		value = parseInt(value).toFixed(1);
	}
	return value;
},
decodeHtml: function (html) {
	var txt = document.createElement("textarea");
	txt.innerHTML = html;
	return txt.value;
},
stripHtml: function(html) {
	var temporalDivElement = document.createElement("div");
	temporalDivElement.innerHTML = html;
	return temporalDivElement.textContent || temporalDivElement.innerText || "";
},
stripDoubleQuotes: function(str) {
	return str.replace(/['"]+/g, '');
},
type: function(str) {
	if(str == "pages") {
		str = "articles";
	}
	if(str == "events_cityspark_2022") {
		str = "events";
	}
	return _.toUpper(str);


	
},
dollarSigns: function(value) {
	var price = Math.round(value);
	var signs = '';
	if(price === 1) signs = '$';
	if(price === 2) signs = '$$';
	if(price === 3) signs = '$$$';
	if(price === 4) signs = '$$$$';
	
	return signs;
}
	},
	methods: {		sort: function(list){
			var sponsors = _.filter(list, { 'isSponsor': true });
			var photos = _.filter(list, { 'isSponsor': false, 'has_photo': true });
			var basic = _.filter(list, { 'isSponsor': false, 'has_photo': false });
			return _.concat(sponsors, photos, basic);
		},
				alwaysOpen: function(partner){
			if(partner.hours[0].close.length === 0 && partner.hours[0].open === "0000") {
				return true;
			} else {
				return false;
			}
		},
				isOpen: function(partner){
			if(partner.hours.length > 1) {
				var c_dow = moment().weekday(); // Returns current day of week number.
				var today = partner.hours[c_dow];
				if(today) {
					var open = parseInt(today.open);
					var close = parseInt(today.close);
					var current_time = parseInt(moment().format('HHmm'));

					// If the current time is between the open and close time and the open is before the close time...
					if(current_time >= open && current_time < close && open < close) {
						// console.log(partner.title + " is open! Closes in "+ moment(partner.hours[c_dow].close, 'hhmm').fromNow(true));
						return true;
					} else if(open > close) {
						if(current_time >= open || current_time < close) {
							// console.log(partner.title + " is open. Closes in "+ moment(partner.hours[c_dow].close, 'hhmm').fromNow(true));
							return true;	
						} else {
							// console.log(partner.title + " is closed. Opens in "+ moment(partner.hours[c_dow].open, 'hhmm').toNow(true));
							return false;
						}
						
					} else {
						// console.log(partner.title + " is closed. Opens in "+ moment(partner.hours[c_dow].open, 'hhmm').toNow(true));
						return false;
					}
				} else {
					// console.log(partner.title + " is not open today.");
					return false;
				}
			} else {
				// console.log(partner.title + " is open 24/7.");
				return true;
			}
		},
				has_hours: function(partner){
			if(partner.hours.length) {
				return true;
				// console.log('has hours');
			} else {
				return false;
				// console.log('no hours');
			}
		},

		fetchTier1() {
			// Define the URL of the resource you want to fetch
			const url = 'https://www.traveldubuque.com/data/explore/tier-1-partners.json';

			// Use the fetch function to make a GET request to the specified URL
			fetch(url)
			  .then(response => {
			    // Check if the response status is OK (status code 200-299)
			    if (!response.ok) {
			      throw new Error('Network response was not ok ' + response.statusText);
			    }
			    // Parse the JSON response and return it
			    return response.json();
			  })
			  .then(data => {
			    // Handle the parsed JSON data
			    const partners = data;


			   partners.forEach(partner => {this.partners.push(partner);})
				this.fetchTier2();

				setTimeout(function(){
					app.favorite_list.forEach(function(fav){
						$('main .toggle-heart_' + fav.url_title).prop('checked', true).siblings('label').addClass('checked');
					});	
				}, 1000);
			  })
			  .catch(error => {
			    // Handle any errors that occurred during the fetch
			    console.error('There has been a problem with your fetch operation:', error);
			  });
		},
		fetchTier2() {
			// Define the URL of the resource you want to fetch
			const url = 'https://www.traveldubuque.com/data/explore/tier-2-partners.json';

			// Use the fetch function to make a GET request to the specified URL
			fetch(url)
			  .then(response => {
			    // Check if the response status is OK (status code 200-299)
			    if (!response.ok) {
			      throw new Error('Network response was not ok ' + response.statusText);
			    }
			    // Parse the JSON response and return it
			    return response.json();
			  })
			  .then(data => {
			    // Handle the parsed JSON data
			    const partners = data;

			    partners.forEach(partner => {this.partners.push(partner);})

			    if(app.clusters) {app.clusters.clearMarkers();}					
				app.addMarkers(this.filteredList);
				app.isLoading = false;
				// this.fetchTier3();

				setTimeout(function(){
					app.favorite_list.forEach(function(fav){
						$('main .toggle-heart_' + fav.url_title).prop('checked', true).siblings('label').addClass('checked');
					});	
				}, 1000);
			  })
			  .catch(error => {
			    // Handle any errors that occurred during the fetch
			    console.error('There has been a problem with your fetch operation:', error);
			  });
		},

		initMap: function(){
			//Initialize the map.
			this.map = new google.maps.Map(document.getElementById('map'), {
				zoom: 16,
				gestureHandling: 'cooperative',
				mapId: "47ae81c4096c2b70", // Map ID is required for advanced markers.
			});

			this.addMarkers(this.sort(this.filteredList));
		},

		addMarkers: function(list){

			if(this.markers.length) {
				this.markers.forEach(function(marker, i){marker.setMap(null);});
				this.markers = [];
			}

			this.bounds = new google.maps.LatLngBounds();

			list.forEach(function(partner, i){
				if(partner.location) {

					var ico = {
						url: icons["explore"].icon, // url
						scaledSize: new google.maps.Size(32, 42), // scaled size
						origin: new google.maps.Point(0,0), // origin
						anchor: new google.maps.Point(0, 0) // anchor
					};

					app.markers[i] = new google.maps.marker.AdvancedMarkerElement({
						position: partner.location,
						map: app.map,
						zIndex: 9999, // Forces markers to render above clusters
						title: partner.title, // Optional: Tooltip on hover
						gmpClickable: true // Explicitly make it clickable
					});

					var loc = new google.maps.LatLng(partner.location.lat, partner.location.lng);
					app.bounds.extend(loc);

					// Auto Zoom/Center
					app.map.fitBounds(app.bounds);
					app.map.panToBounds(app.bounds);

					// Set Up Marker Info Window
					app.infowindow[i+1] = new google.maps.InfoWindow({
						content: '<div class="title">'+partner.title+'</div>\n\
								  <div class="address">'+partner.address+'</div>\n\
								  <a href="https://www.google.com/maps/dir/?api=1&origin='+partner.title+partner.address+'" class="btn bg-red" target="_blank">Directions</a>',
					});

					// Initialize event listener on map marker to open map marker
					app.markers[i].addEventListener('gmp-click', function() {
						console.log("clicked")
						// Close all info windows
						app.infowindow.forEach(function(info, i){info.close();});
						// Open the clicked markers info window
						app.infowindow[i+1].open(app.map, app.markers[i]);
					});
				}
				
			});

			// Initialize Marker Clustering
		  	const {MarkerClusterer} = window.markerClusterer;
   		 	this.clusters = new MarkerClusterer({
			    markers: this.markers,
			    map: this.map,
			    minimumClusterSize: 2, // Prevent clustering single markers
			    ignoreHidden: false, // Ensure markers inside clusters are clickable
			});

		},

		addMarker: function(location) {
			var marker = new google.maps.marker.AdvancedMarkerElement({
				position: location,
				map: app.map
			});
			app.markers.push(marker);
		},

		deleteMarkers: function() {
			for (var i = 0; i < this.markers.length; i++) {this.markers[i].setMap(null);}
			this.markers = [];
		},

		clearFavorites: function() {
			this.favorite_list.splice(0, this.favorite_list.length);
		},

		populateCategoryFilterBasedOnSegment: function() {
			// Assuming the URL is something like https://example.com/segment1/segment2/segment3
			const urlPath = window.location.pathname; // Gets the path of the URL
			const segments = urlPath.split('/'); // Splits the path by '/'

			// Access the second segment (array index 1)
			const firstSegment = segments[1];
			const secondSegment = segments[2];
			if(firstSegment !== "" && secondSegment === undefined) {this.category_filter.push(firstSegment);} else {this.category_filter.push(secondSegment);}
		},

		loadMoreArticles: function(catID){
			var limit = 6;
			var offset = $('section.articles a.article').length;

			$.get( "https://www.traveldubuque.com/_inc/more-articles", { catID: catID, limit: limit, offset: offset } )
				.done(function( response ) {
					$('#more-articles').append(response);

					sticky_map.destroy();
					sticky_filter.destroy();
					init_sticky();

					var returned = 0;
					$(response.data).each(function(){
						if($(this).hasClass('article')){
							returned += 1;
						}
					});

					if(returned < limit) {$('a.load-more').fadeOut();}

					setTimeout(function(){
						app.favorite_list.forEach(function(fav){
							$('main .toggle-heart_' + fav.url_title).prop('checked', true).siblings('label').addClass('checked');
						});	
					}, 1000);
				});
		},

		loadMoreArticlesReorder: function(catID){
			var limit = 6;
			var offset = $('section.articles a.article').length;

			$.get( "https://www.traveldubuque.com/_inc/more-articles", { catID: catID, limit: limit, offset: offset } )
				.done(function( response ) {
					$('#more-articles').append(response);

					sticky_map.destroy();
					sticky_filter.destroy();
					init_sticky();

					var returned = 0;
					$(response.data).each(function(){
						if($(this).hasClass('article')){
							returned += 1;
						}
					});

					if(returned < limit) {$('a.load-more').fadeOut();}

					setTimeout(function(){
						app.favorite_list.forEach(function(fav){
							$('main .toggle-heart_' + fav.url_title).prop('checked', true).siblings('label').addClass('checked');
						});	
					}, 1000);
				});
		},

		noResults(){
			let results = false;
			if(this.filteredList !== null) {
				results = this.filteredList.length == 0 && !this.isLoading ? true : false;
			}
			return results;
		},

		updateMapMarkers(){
			if(this.partners) {
				if(this.clusters) {this.clusters.clearMarkers();}					
				this.addMarkers(this.filteredList);
				
			}
		},

		clearFilters() {
			this.details_filter = [];
			this.location_filter = [];
			this.category_filter = [];
			this.scrollTopAttractions();
		},

		scrollTopAttractions(){
			if(!this.isLoading) {
				window.scrollTo({
					left: 0,
					top: document.querySelector('.attractions-contain').offsetTop + 55,
					behavior: 'smooth'
				});	
			}
		},

		categoryTitleLookup(category){
			if(_.filter(this.categories, ['url_title', category]).length)
				return _.filter(this.categories, ['url_title', category])[0].title;
		},

		removeCategory(cat) {
			this.category_filter = this.category_filter.filter(category => category !== cat);
		},
		removeDetail(d) {
			this.details_filter = this.details_filter.filter(detail => detail !== d);
		},
		removeLocation(loc) {
			this.location_filter = this.location_filter.filter(location => location !== loc);
		},
		removeActiveClassFromBody() {
			const body = document.querySelector('body');
			if(body.classList.contains('filter-locations-active') || body.classList.contains('filter-details-active') || body.classList.contains('filter-attr-active')) {
				body.classList.remove('filter-locations-active', 'filter-details-active', 'filter-attr-active')
			}
		}
	},
	mounted: function (){

		if (window.google && window.google.maps) {this.initMap();} else {
	      window.initMap = this.initMap;
	    }

	    this.fetchTier1();

		this.favorite_list = localStorage.getItem("favorites") ? JSON.parse(localStorage.getItem("favorites")) : [];

		setTimeout(function(){
			app.favorite_list.forEach(function(fav){
				$('main .toggle-heart_' + fav.url_title).prop('checked', true).siblings('label').addClass('checked');
			});	
		}, 1000);

		this.populateCategoryFilterBasedOnSegment();
	}
});


$(function(){

	if(window.outerWidth >= 640) {
		$('#map-toggle').prop('checked', 'checked');

	} else {
		$('#map-toggle').prop('checked', '');
		$('body').removeClass('map-active');
	}

	$(window).on('resize', function(){
		if(window.outerWidth >= 640) {
			$('#map-toggle').prop('checked', 'checked');
		} else {
			$('#map-toggle').prop('checked', '');
		}
	});

	$('.filter-icon-contain.filter-attr').click(function(event) {$('body').toggleClass('filter-attr-active');});

	$('.filter-icon-contain.filter-details').click(function(event) {
		console.log("clicked")
		$('body').toggleClass('filter-details-active');
	});

	$('.filter-icon-contain.filter-locations').click(function(event) {$('body').toggleClass('filter-locations-active');});

	$('.categories-contain').on('mouseleave', function(){
		$('body').removeClass('filter-attr-active filter-details-active filter-locations-active')
	});

	$('#map-toggle').on('change', function(){$('body').toggleClass('map-active')});

	$('#app').on('click', '.js_explore_nearby', function(){app.exploreNearby();});

	$('.categories [checked="checked"]').trigger('click');

});