/**
 * Google MAP Plugin for Thorium Builder 4
 * framework7 v8.x (https://framework7.io) MIT Licensed
 * Released date: May 2024
 * Copyright 2018-2024 Nymphide Thorium builder. 
*/

var googleMapPlugin = {
	name: "Thorium Builder GoogleMap API Plugin",
	bundleid: "com.thorium.googlemaps",
	version: "4.0",
	initialized: false,
	infoWindowHTML: '<div class="iw-container" >' +
		'	<div class="row">' +
		'		<div class="imgbloc xsmall-30 small-20 medium-20 large-10 xlarge-10 col-3 ">' +
		'			<img class="img-zoom" src="{img}" alt="{title}" >' +
		'		</div>' +
		'		<div class="xsmall-70 small-80 medium-80 large-90 xlarge-90 col-9">' +
		'			<div class="iw-title">{title}&nbsp;<span>{badge}</span></div>' +
		'			<div class="iw-subtitle">{subtitle}</div>' +
		'			<div class="iw-rate">{rating}</div>' +
		'			<div class="iw-subtitle">{address}</div>' +
		'			<div class="flexbox display-flex flex-row align-items-center pt-1" >' +
		'				<a id="gmap_btn" data-tooltip="info" class="button button-round button-fill tooltip-init external link" href="/{target}/?id={uid}&pk={pk}&service={service}&rowindex=0{datablock}" data-transition="f7-cover-v"><i class="fa f7-icons active-state" >info_circle_fill</i></a>' +
		'				<a id="dir_btn" data-tooltip="direction from here" class="button button-round button-fill tooltip-init external link" onclick="window.open(\'https://www.google.com/maps/dir/?api=1&amp;destination={latitude},{longitude}\',\'_parent\');" ><i class="fa f7-icons active-state" >arrow_up_right_diamond_fill</i></a>' +
		'				<a id="dir_btn" data-tooltip="direction to here" class="button button-round button-fill tooltip-init" onclick="window.open(\'https://www.google.com/maps/dir/?api=1&amp;origin={latitude},{longitude}\',\'_parent\');" ><i class="fa f7-icons active-state" >arrow_uturn_left_circle_fill</i></a>' +
		'			</div>' +
		'		</div>' +
		'	</div>' +
		'</div">',
	infoPlacewindow: new google.maps.InfoWindow(),
	radius: null,

	setMapOptions: function (m, s) {
		var mapOptions = {
			styles: eval(s)
		};
		m.setOptions(mapOptions);
	},

	geolocateUser: function (m) {
		thoriumapi.logEvent(0, "[com.thorium.googlemaps] Trying to Geolocate User...");
		if (!(navigator.geolocation)) { return false; }
		navigator.geolocation.getCurrentPosition(function (position) {
			var pos = {
				lat: position.coords.latitude,
				lng: position.coords.longitude
			};
			m.setCenter(pos);
			var inf = new google.maps.InfoWindow({ content: "You are here!" });
			inf.open(m);
			inf.setPosition(m.getCenter());
			googleMapPlugin.drawCircleAtPos(m, pos, 300);
			return true;
		}, function () {
			return false;
		});
	},

	initSearchPlace: function (field, map) {
		thoriumapi.logEvent(0, "[com.thorium.googlemaps] Initializing GoogleMap Search Place");
		var inp = document.getElementById(field.id);
		var input = $('#' + field.id)[0];
		var autocomplete = new google.maps.places.Autocomplete(input);
		var $bm = inp.getAttribute('data-map');
		autocomplete.bindTo('bounds', map);
		var marker2 = new google.maps.Marker({
			map: map,
			anchorPoint: new google.maps.Point(0, -29)
		});
		autocomplete.addListener('place_changed', function () {
			marker2.setVisible(false);
			var place = autocomplete.getPlace();
			if (!place.geometry) {
				window.alert("No details available for input: '" + place.name + "'");
				return;
			}
			if (place.geometry.viewport) {
				map.fitBounds(place.geometry.viewport);
			} else {
				map.setCenter(place.geometry.location);
			}
			marker2.setPosition(place.geometry.location);
			marker2.setVisible(true);
			var address = '';
			if (place.address_components) {
				address = [
					(place.address_components[0] && place.address_components[0].short_name || ''),
					(place.address_components[1] && place.address_components[1].short_name || ''),
					(place.address_components[2] && place.address_components[2].short_name || '')
				].join(' ');
			}

			if (googleMapPlugin.infoPlacewindow !== null) { googleMapPlugin.infoPlacewindow.close(); }
			googleMapPlugin.infoPlacewindow.setContent('<img src="' + place.icon + '" style="height:14px;" > <strong>' + place.name + '</strong><hr>' + address);
			googleMapPlugin.infoPlacewindow.open(map, marker2);
			googleMapPlugin.drawCircleAtPos(map, marker2.getPosition(), 300);
			map.setZoom(16);
			$('.custominfowindow').hide();
		});
	},

	drawCircleAtPos: function (map, pos, size) {
		thoriumapi.logEvent(0, "[com.thorium.googlemaps] Drawing Circle on Map");
		if (googleMapPlugin.radius != null) { googleMapPlugin.radius.setMap(null); }
		map.panTo(pos);
		googleMapPlugin.radius = new google.maps.Circle({
			map: map,
			radius: size,
			center: pos,
			fillColor: '#777',
			fillOpacity: 0.3,
			strokeColor: 'rgba(255,255,255,0.5)',
			strokeOpacity: 0.8,
			strokeWeight: 2,
			draggable: false,
			editable: false
		});
	},

	addMarker: function (map, pos, title, uid, addr, img, desc, subtitle, badge, rating, target, data, pk, service) {
		thoriumapi.logEvent(0, "Adding GoogleMap Marker at position [" + pos.lat() + " | " + pos.lng() + "]");
		thoriumapi.logEvent(0, "Get Map Reference " + map.toString());
		pk = pk || null;
		service = service || null;
		title = title || '';
		uid = encodeURI(uid) || '';
		addr = addr || '';
		img = img || '';
		desc = desc || '';
		subtitle = subtitle || '';
		badge = badge || '';
		rating = rating || 0;
		target = target || '';
		data = data || null;
		var marker = new google.maps.Marker({
			position: pos,
			map: map,
			title: title,
			icon: "./img/map-marker-icon.png"
		});
		var contentString;
		var lat = marker.position.lat();
		var lng = marker.position.lng();
		contentString = googleMapPlugin.infoWindowHTML;
		contentString = contentString.replace(/{title}/g, title);
		contentString = contentString.replace(/{uid}/g, uid);
		contentString = contentString.replace(/{address}/g, addr);
		if ((app.device.cordova == true) || (app.device.capacitor == true)) {
            contentString = contentString.replace(/_parent/g, "_system"); 
        }


		var hasImage = false;
		if (img) {
			if (img.length == 0) {
				img = "./img/defaultimg.png";
				hasImage = false;
			} else if (img.indexOf("http") > -1) {
				img = img;
				hasImage = true;
			}
		} else {
			hasImage = false;
			img = "./img/defaultimg.png";
		}
		if (pk) {
			contentString = contentString.replace(/{pk}/g, pk);
		} else {
			contentString = contentString.replace(/&pk={pk}/g, "");
		}
		if (service) {
			contentString = contentString.replace(/{service}/g, service);
		} else {
			contentString = contentString.replace(/&service={service}/g, "");
		}
		contentString = contentString.replace(/{img}/g, img);
		contentString = contentString.replace(/{description}/g, desc);
		contentString = contentString.replace(/{subtitle}/g, subtitle);
		contentString = contentString.replace(/{badge}/g, badge);
		contentString = contentString.replace(/{target}/g, target);
		contentString = contentString.replace(/{latitude}/g, lat);
		contentString = contentString.replace(/{longitude}/g, lng);
		var $rt = '';
		for (var i = 0; i < rating; i++) {
			$rt = $rt + '<i class="f7-icons">star_fill</i>';
		}
		contentString = contentString.replace(/{rating}/g, $rt);
		if (data) {
			contentString = contentString.replace(/{datablock}/g, "&data=" + encodeURIComponent(JSON.stringify(data)));
		} else {
			contentString = contentString.replace(/{datablock}/g, '');
		}
		var infowindow = new google.maps.InfoWindow();
		infowindow.setContent(contentString);
		app.emit('googleMapsAddMarker', map, marker, pos, data);

		marker.addListener('click', function () {
			app.emit('googleMapsMarkerClick', map, marker, pos, data);
			thoriumapi.logEvent(0, "[com.thorium.googlemaps] GoogleMaps Marker Click");
			$('.custominfowindow').html(contentString);
			$('.custominfowindow').show();
			$('.custominfowindow').css('height', 'auto');
			if (hasImage == false) {
				var m = document.querySelector(".custominfowindow .imgbloc");
				if (m) { m.style.display = "none"; }
			}
			if (target.length == 0) { $('#gmap_btn').hide(); }
		});

		marker.addListener('mouseover', function () {
			app.emit('googleMapsMarkerMouseOver', map, marker, pos, data);
		});
		marker.addListener('mouseout', function () {
			app.emit('googleMapsMarkerMouseOut', map, marker, pos, data);
		});
	},

	getJsonData: function (mapContainer, mapObject) {
		var root = mapContainer.getAttribute("data-json-root") || null;
		var url = mapContainer.getAttribute('data-json-source') || null;
		if (!url) {
			if (app) {
				thoriumapi.logEvent(1, "[com.thorium.googlemaps] Invalid url for JSON Source");
			}
			return;
		}
		if (url == "js/json/none") {
			if (app) {
				thoriumapi.logEvent(1, "[com.thorium.googlemaps] Invalid url for JSON Source");
			}
			return;
		}
		var items = [];
		var options = {};
		var headers = {};
		var hasheader = false;
		options["method"] = "GET";
		if (kMode.length > 0) { options["mode"] = kMode; }
		if (kCache.length > 0) { options["cache"] = kCache; }
		if (kCredentials.length > 0) { options["credentials"] = kCredentials; }
		/* header */
		if (kContenttype.length > 0) { headers["Content-Type"] = kContenttype; hasheader = true; }
		if (kRedirect.length > 0) { headers["redirect"] = kRedirect; hasheader = true; }
		if (kReferrerpolicy.length > 0) { headers["referrerpolicy"] = kReferrerpolicy; hasheader = true; }
		if (kAuthorization.length > 0) { headers["Authorization"] = kAuthorization; hasheader = true; }
		if (hasheader == true) {
			options["headers"] = headers;
		}

		/* -- new callback before call --*/
		var fn = window["callback_repeater_before_load"];
		var fnparams = [options];
		if (typeof fn === "function") {
			options = fn.apply(this, fnparams);
		}
		//Dynamic variables
		var str = url,
			rg = /[^{\}]+(?=})/g,
			match;
		while (match = rg.exec(str)) {// Iterate matches 
			const varname = match[0];
			if ((varname) && (varname.length > 0)) {
				var varValue = "";
				try {
					varValue = window[varname];
				}
				catch (err) {
					app.preloader.hide();
					var m = "[com.thorium.googlemaps] Unable to find variable " + varname + "] " + err;
					app.dialog.alert(m);
					return;
				}
				if (varValue) {
					url = url.replace("{" + varname + "}", encodeURIComponent(varValue));
				} else {
					app.preloader.hide();
					var m = "[com.thorium.googlemaps] variable [" + varname + "] is undefined";
					app.dialog.alert(m);
					return;
				}

			}
		}
		fetch(url, options)
			.then(
				function (response) {
					response.text()
						.then(txt => {
							var data;
							try {
								data = JSON.parse(txt);
							} catch (err) {
								app.emit('jsonDataloadError', $(this), err);
								app.dialog.alert(err.message + " " + txt);
								return;
							}
							var i = -1;
							var item = {};
							var myItems;

							if ((typeof data == "object") && (root)) {
								myItems = jsonApiPlugin.getChildrenProperty(data, root);
							} else {
								if (!(root)) { myItems = data; } else { myItems = data[root]; }
							}


							/*-- Get dynamic Variables --*/
							var limit = mapContainer.getAttribute("data-json-maxrows") || 9999999;
							if (limit == 0) { limit = 9999999; }
							var nameFld = mapContainer.getAttribute("data-json-name") || '';
							var addressFld = mapContainer.getAttribute("data-json-address") || '';
							var imgFld = mapContainer.getAttribute("data-json-img") || '';
							var descFld = mapContainer.getAttribute("data-json-desc") || '';
							var subTitleFld = mapContainer.getAttribute("data-json-subtitle") || '';
							var badgeFld = mapContainer.getAttribute("data-json-badge") || '';
							var ratingFld = mapContainer.getAttribute("data-json-rating") || '';
							var dataTarget = mapContainer.getAttribute("data-target") || '';
							var latFld = mapContainer.getAttribute("data-json-lat") || '';
							var lngFld = mapContainer.getAttribute("data-json-lng") || '';
							var latLngField = mapContainer.getAttribute("data-json-lat-lng") || '';
							var keyField = mapContainer.getAttribute("data-json-key") || '';
							if (myItems) {
								var flatresult = [];
								for (const [item, value] of Object.entries(myItems)) {
									var flatItems = jsonApiPlugin.flattenObj(value);
									flatresult.push(flatItems);
								}
								for (var prop in flatresult) {
									i = i + 1;
									if (i >= limit) { break; }
									item = flatresult[prop];
									item["dataindex"] = i;
									var lat = item[latFld] || 0;
									var lng = item[lngFld] || 0;
									if (((lat == 0) || (lng == 0)) && (latLngField.length > 0)) {
										var fc = item[latLngField];
										if (fc) {
											var res = item[latLngField].split(",");
											if (res.length == 2) {
												lat = res[0];
												lng = res[1];
											}
										}
									}
									var LatLng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
									item.id = item[keyField] || '';
									item.name = item[nameFld] || '';
									item.address = item[addressFld] || '';
									item.img = item[imgFld] || '';
									item.desc = item[descFld] || '';
									item.subtitle = item[subTitleFld] || '';
									item.badge = item[badgeFld] || '';
									item.rating = item[ratingFld] || 0;
									googleMapPlugin.addMarker(mapObject, LatLng, item.name, item.id, item.address, item.img, item.desc, item.subtitle, item.badge, item.rating, dataTarget, item);
								}
							}
							app.emit('jsonDataloadSuccess', $(this), mapObject, items);
						})
						.catch(function (err) {
							app.dialog.alert(err.message);
						});
				}).catch(function (err) {
					app.emit('jsonDataloadError', $(this), err);
					app.dialog.alert(err.message);
				});
	},

	getFirebaseData: function (mapContainer, mapObject) {
		if (typeof firestoredb == 'undefined') {
			app.dialog.alert("Firestore Database not defined");
			return;
		}
		var items = [];
		var limit = mapContainer.getAttribute("data-firebase-maxrows") || 10000;
		if (limit == 0) { limit = 10000; }
		const f = mapContainer.getAttribute('data-filter-field');
		const o = mapContainer.getAttribute('data-filter-operator');
		const v = mapContainer.getAttribute('data-filter-value');
		const f2 = mapContainer.getAttribute('data-filter-field2');
		const o2 = mapContainer.getAttribute('data-filter-operator2');
		const v2 = mapContainer.getAttribute('data-filter-value2');
		const t = mapContainer.getAttribute('data-template');
		const usronly = mapContainer.getAttribute('data-user-data') == "true" || false;
		var collection = mapContainer.getAttribute('data-collection') || null;
		var parentuid = "";

		if (!collection) {
			mapContainer.setAttribute('data-loaded', false);
			app.preloader.hide();
			app.emit('firebaseMapLoadError', $(this), "Collection not Defined");
			app.dialog.alert("Error getting documents, Collection not Defined");
			return;
		}

		var query = firestoredb.collection(collection);
		if (parentuid) {
			try {
				query = query.where('parentuid', '==', parentuid);
			}
			catch (e) {
				mapContainer.setAttribute('data-loaded', false);
				app.preloader.hide();
				app.emit('firebaseMapLoadError', $(this), e.message);
				app.dialog.alert(e.message);
				return;
			}
		}
		if (f) {
			var sv;
			if (v == "false") { sv = false; }
			else if (v == "true") { sv = true; }
			else { sv = v; }
			try {
				query = query.where(f, o, sv);
			}
			catch (e) {
				mapContainer.setAttribute('data-loaded', false);
				app.preloader.hide();
				app.emit('firebaseMapLoadError', $(this), e.message);
				app.dialog.alert(e.message);
				return;
			}
		}
		//Second criteria
		if (f2) {
			var sv;
			if (v2 == "false") { sv = false; }
			else if (v2 == "true") { sv = true; }
			else { sv = v2; }
			try {
				query = query.where(f2, o2, sv);
			}
			catch (e) {
				mapContainer.setAttribute('data-loaded', false);
				app.preloader.hide();
				app.emit('firebaseMapLoadError', $(this), e.message);
				app.dialog.alert(e.message);
				return;
			}
		}

		if (usronly == true) {
			var u = firebase.auth().currentUser;
			if (u != null) {
				try {
					query = query.where('createdby', '==', u.uid);
				}
				catch (e) {
					mapContainer.setAttribute('data-loaded', false);
					app.preloader.hide();
					app.emit('firebaseMapLoadError', $(this), e.message);
					app.dialog.alert(e.message);
					return;
				}
			}
		}
		if ((limit) && (limit > 0)) {
			try {
				query = query.limit(parseInt(limit));
			}
			catch (e) {
				mapContainer.setAttribute('data-loaded', false);
				app.preloader.hide();
				app.emit('firebaseMapLoadError', $(this), e.message);
				app.dialog.alert(e.message);
				return;
			}
		}
		query.get()
			.then(function (querySnapshot) {
				var i = -1;
				/*-- Get dynamic Variables --*/
				var nameFld = mapContainer.getAttribute("data-firebase-name") || '';
				var addressFld = mapContainer.getAttribute("data-firebase-address") || '';
				var imgFld = mapContainer.getAttribute("data-firebase-img") || '';
				var descFld = mapContainer.getAttribute("data-firebase-desc") || '';
				var subTitleFld = mapContainer.getAttribute("data-firebase-subtitle") || '';
				var badgeFld = mapContainer.getAttribute("data-firebase-badge") || '';
				var ratingFld = mapContainer.getAttribute("data-firebase-rating") || '';
				var dataTarget = mapContainer.getAttribute("data-target") || '';
				var latFld = mapContainer.getAttribute("data-firebase-lat") || '';
				var lngFld = mapContainer.getAttribute("data-firebase-lng") || '';
				var latLngField = mapContainer.getAttribute("data-firebase-lat-lng") || '';

				querySnapshot.forEach(function (doc) {
					i = i + 1;
					var item = {};
					item = doc.data();
					item.dataindex = i;
					item.uid = doc.id;
					item.id = doc.id;
					var lat = item[latFld] || 0;
					var lng = item[lngFld] || 0;
					if (((lat == 0) || (lng == 0)) && (latLngField.length > 0)) {
						var fc = item[latLngField];
						if (fc) {
							var res = item[latLngField].split(",");
							if (res.length == 2) {
								lat = res[0];
								lng = res[1];
							}
						}
					}
					var LatLng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
					item.name = item[nameFld] || '';
					item.address = item[addressFld] || '';
					item.img = item[imgFld] || '';
					item.desc = item[descFld] || '';
					item.subtitle = item[subTitleFld] || '';
					item.badge = item[badgeFld] || '';
					item.rating = item[ratingFld] || 0;
					console.log(item);
					googleMapPlugin.addMarker(mapObject, LatLng, item.name, item.id, item.address, item.img, item.desc, item.subtitle, item.badge, item.rating, dataTarget, item);
				});

				setTimeout(function () { app.preloader.hide(); }, 300);
				app.emit('firebaseMapLoadSuccess', $(this), items.length);
			})
			.catch(function (error) {
				mapContainer.setAttribute('data-loaded', false);
				app.preloader.hide();
				app.emit('firebaseMapLoadError', $(this), error);
				app.dialog.alert("Error getting documents: " + error);
				return;
			});
	},


	initializeMap: function (mapID) {
		var mapObject = document.getElementById(mapID);
		if (mapObject) {
			thoriumapi.logEvent(0, "GoogleMap Plugin: Initialize Map with id: [" + mapID + "]");
			var dataLoaded = mapObject.getAttribute("data-loaded") || 'false';
			mapObject.setAttribute("data-loaded", "true");

			var dataZoom = parseInt(mapObject.getAttribute("data-zoom") || 12);
			var dataView = mapObject.getAttribute("data-view") || "terrain";
			var dataLat = parseFloat(mapObject.getAttribute("data-lat") || 0);
			var dataLng = parseFloat(mapObject.getAttribute("data-lng") || 0);
			var dataPos = new google.maps.LatLng(dataLat, dataLng);
			var dataGeolocation = mapObject.getAttribute("data-geolocation") || "false";

			var datazoomControl = mapObject.getAttribute("data-zoomcontrol") === "true";
			var datamapTypeControl = mapObject.getAttribute("data-typecontrol") === "true";
			var datascaleControl = mapObject.getAttribute("data-scalecontrol") === "true";
			var datastreetViewControl = mapObject.getAttribute("data-streetviewcontrol") === "true";
			var datarotateControl = mapObject.getAttribute("data-rotatecontrol") === "true";
			var datafullscreenControl = mapObject.getAttribute("data-fullscreencontrol") === "true";
			var myMap = new google.maps.Map(mapObject, {
				zoom: dataZoom,
				mapTypeId: dataView,
				center: dataPos,
				zoomControl: datazoomControl,
				mapTypeControl: datamapTypeControl,
				streetViewControl: datastreetViewControl,

			});
			mapObject.map = myMap;

			if (dataGeolocation == "true") {
				if (googleMapPlugin.geolocateUser(myMap) == false) { }
			}
			var dataStyletyle = mapObject.getAttribute("data-style") || '';
			if (dataStyletyle.length > 0) {
				thoriumapi.logEvent(0, "[com.thorium.googlemaps] set Map Options");
				var dataStyle = Base64.decode(dataStyletyle);
				googleMapPlugin.setMapOptions(myMap, dataStyle);
			}
			var dataSource = mapObject.getAttribute("data-dbsource") || "static";
			if ((dataSource == "true") || (dataSource == "sqlite")) {
				thoriumapi.logEvent(0, "[com.thorium.googlemaps] Loading Map Data from dbExpress");
				if (typeof dbExpressMaps !== 'undefined') {
					dbExpressMaps.loadPlaces(mapObject, "googlemap"); //f7
				}
			}
			else if (dataSource == "json") {
				thoriumapi.logEvent(0, "[com.thorium.googlemaps] Loading Map Data from API");
				googleMapPlugin.getJsonData(mapObject, myMap);
			}
			else if (dataSource == "firebase") {
				if (typeof firebase !== 'undefined') {
					thoriumapi.logEvent(0, "[com.thorium.googlemaps] Loading Map Data from Cloud Firestore");
					googleMapPlugin.getFirebaseData(mapObject, myMap);
				} else {
					thoriumapi.logEvent(2, "[com.thorium.googlemaps] Map Error: Firebase is not initialized!");
				}

			}

			else {
				var dataMarkers = mapObject.getAttribute("data-markers") || "";
				var dataTarget = mapObject.getAttribute("data-target") || "";
				if (dataMarkers.length > 0) {
					thoriumapi.logEvent(0, "[com.thorium.googlemaps] loading Map Markers");
					var jsonBlock = Base64.decode(dataMarkers);
					var myMarkers = JSON.parse(jsonBlock);
					for (var item of myMarkers) {
						var LatLng = new google.maps.LatLng(parseFloat(item.lat), parseFloat(item.lng));
						var markerImg = item.img || '';
						googleMapPlugin.addMarker(myMap, LatLng, item.name, item.id, item.address, markerImg, item.desc, item.subtitle, item.badge, item.rating, dataTarget, item);
					}
				}
			}
			var infowindow = new google.maps.InfoWindow();
			var geocoder = new google.maps.Geocoder;
			google.maps.event.addListener(myMap, "click", function (event) {
				if (infowindow) { infowindow.close(); }
				$('.custominfowindow').css('height', '0px');
				thoriumapi.logEvent(0, "[com.thorium.googlemaps] Click Event on Map");
				app.emit('googleMapsClick', event, myMap);
			});
			$('.search-place').each(function (inputRef) {
				googleMapPlugin.initSearchPlace(inputRef, myMap);
			});
			mapObject.style.visibility = "visible";
			app.preloader.hide();
			app.emit('googleMapsInitialized', mapObject);
		}
	},

	initializeAllMaps: function () {
		var i = 0;
		thoriumapi.logEvent(0, "[com.thorium.googlemaps] Initializing all Google Maps");
		var x = document.querySelectorAll(".googlemapAPI");
		for (var i = 0; i < x.length; i++) {
			var mapObject = x[i];
			if (mapObject) {
				var dataLoaded = mapObject.getAttribute("data-loaded") || "false";
				if (dataLoaded === "false") {
					googleMapPlugin.initializeMap(mapObject.id);
				}
			}
		}
		return i;
	},

	resetLoadedAttributes: function () {
		var x = document.querySelectorAll(".googlemapAPI");
		for (var i = 0; i < x.length; i++) {
			var mapObject = x[i];
			mapObject.setAttribute("data-loaded", "false");
		}
	},

	initialize: function () {
		googleMapPlugin.initializeAllMaps();
		var inputSearchPlace = document.getElementsByClassName('input-search-place');
		for (var i = 0; i < inputSearchPlace.length; i++) {
			var input = inputSearchPlace.item(i);
			if (typeof google == "object") {
				thoriumapi.logEvent(0, "GoogleMap Plugin: Initialize AutoComplete");
				var autocomplete = new google.maps.places.Autocomplete(input);
			}
		}
	}
};

$(document).on('page:mounted', function (e, page) { //OK
	e.preventDefault;
	googleMapPlugin.initialize();
})