· 7 years ago · Jan 24, 2019, 06:32 AM
1var _affilImages;
2var wrenchPushed = 0;
3
4function _defineProperty(obj, key, value) {
5 if (key in obj) {
6 Object.defineProperty(obj, key, {
7 value: value,
8 enumerable: true,
9 configurable: true,
10 writable: true
11 });
12 } else {
13 obj[key] = value;
14 }
15 return obj;
16}
17
18var lockMapService = new lockMapService();
19var manyTripDirections;
20var fetchRouteRequest;
21var initialLoad = true;
22var fullpolyline;
23
24var ElevationController = new ElevationController();
25var HighchartService = new HighchartService();
26var ElevationSection = new ElevationSection();
27var TripOptionsPopover = new TripOptionsPopover();
28var MapsController = new MapsController();
29var RouteTable = new RouteTable();
30var ElevationServiceHelper = new ElevationServiceHelper();
31var GeocoderServiceHelper = new GeocoderServiceHelper();
32var LocationServiceHelper = new LocationServiceHelper();
33var HERELocationServiceHelper = new HERELocationServiceHelper();
34var AutocompleteServiceHelper = new AutocompleteServiceHelper();
35var NewTripModal = new NewTripModal();
36var SettingsModal = new SettingsModal();
37var AddToTripComponent = new AddToTripComponent();
38var PrintHelper = new PrintHelper();
39var PostFacebookModal = new PostFacebookModal();
40var HelpModal = new HelpModal();
41var NewsModal = new NewsModal();
42var OpenTripModal = new OpenTripModal();
43var EditTripModal = new EditTripModal();
44var EditProfileModal = new EditProfileModal();
45var EditTripNameModal = new EditTripNameModal();
46var SendGPSModal = new SendGPSModal();
47var CopyTripModal = new CopyTripModal();
48var DeleteTripModal = new DeleteTripModal();
49var RoundTripModal = new RoundTripModal();
50var SendFriendModal = new SendFriendModal();
51var PoiMarkerModal = new PoiMarkerModal();
52var ArchiveTripModal = new ArchiveTripModal();
53
54var beforeSaveName = null;
55var debug = false;
56var progressBarService = new progressBarService();
57var notificationService = new notificationService();
58var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) {
59 return p.toString() === "[object SafariRemoteNotification]";
60})(!window.safari || (typeof safari !== 'undefined' && safari.pushNotification));
61var gettingDistance = false;
62var gettingMileDistance = {};
63var gettingMileDistanceFilter = {};
64var gettingPoi = false;
65var nonCgPoiCache = {};
66var googlePlaces = {};
67var poiDistance = {};
68var searchLookups = {};
69var searchLookupStack = new objectStack(searchLookups);
70var pointerInInfobox = false;
71var pointerInMarker = false;
72var loadingDetails = true;
73var isDragging = false;
74var isDragEnabled = false;
75var searchResult = false;
76var highlightPoi = 0;
77var highlightedPoiObject;
78var showFullRoute = false;
79var searchTimeout = null;
80var prefParkSearch = null;
81var globalSelectedPoi = null;
82var fusionData = null;
83var userProfile = null;
84var bicycleLayer = null;
85var arrMarkers = {};
86var cachedParks = [];
87var cachedPois = [];
88var nonCgPois = {};
89var curRoute = null;
90var curUserPoi = null;
91var curUserPoiMarker = null;
92var curBasicPoi = null;
93var directionsService = void 0;
94var curSelItemIndex = null;
95var curCustomPoi = null;
96var parksInView = [];
97var poisInView = [];
98var tableClicked = 0;
99var filterOptions = null;
100var filteredParks = [];
101var activeFilters = {
102 rating: [],
103 price: [],
104 types: [],
105 clubs: [],
106 hookups: [],
107 amenities: [],
108 features: [],
109 recreation: []
110};
111var seenFilter = 0;
112var filterMapped = false;
113var filterSortKey = 'rating desc';
114var reviewCache = {};
115var updatingPois = [];
116var PoiCat = {
117 BASIC: 0,
118 USER: 1,
119 HCLR: 3
120};
121var PoiDetailsClickSource = {
122 MAP: 1,
123 TRIP_POI_LIST: 2
124};
125
126var clusterImageName = _global.clusterImageName;
127//var customImageName = _global.customImageName;
128var customImageName = function (poi) {
129 if (!poi || !poi.poi_map_icon) return _global.customImageName;
130 return "/app/images/marker_img/" + poi.poi_map_icon + ".png";
131};
132var markerImagePath = _global.markerImagePath;
133var startImageName = _global.startImageName;
134var markerImageExt = _global.markerImageExt;
135var ajaxRegGetPoi = null;
136var ajaxPoiDetails = null;
137var selectedState = "-1";
138var disableCgPoiLoading = $('#hide').is(':checked') ? true : false;
139var infoBox = new InfoBox();
140var temStopCost = {
141 poi: null,
142 customCost: null
143};
144
145if ($('#api_source').val() == 'api-docker') {
146 var apiUrl = '//' + $('#api_source').val() + '.rvparkreviews.com/';
147} else {
148 var apiUrl = '//' + $('#api_source').val() + '.rvparkreviews.com/';
149}
150
151var blockUICount = 0;
152var fuelWarningMarkers = [];
153var newTripGps = false;
154var poiSorting = "distanceFromRefPoi";
155var affilImages = (_affilImages = {
156 "ACN": "ACN",
157 "All CGs For Less": "All_CGs_For_Less",
158 "AOR": "AOR",
159 "Best Holiday": "Best_Holiday",
160 "Best Parks": "Best_Parks",
161 "BLM CG": "BLM_CG",
162 "Canadian Provincial Park": "Canadian_Provincial_Park",
163 "C2C-BPA": "C2C_BPA",
164 "C2C-Classic": "C2C_Classic",
165 "C2C-Deluxe": "C2C_Deluxe",
166 "C2C-Encore Elite": "C2C_Encore_Elite",
167 "C2C-Encore": "C2C_Encore",
168 "C2C-GNP": "C2C_GNP",
169 "CampClub USA": "CampClub_USA",
170 "Canadian National Park": "Canadian_National_Park",
171 "Default": -1,
172 "COE CG": "COE_CG",
173 "Enjoy America!": "Enjoy_America!",
174 "FMCA": "FMCA",
175 "Good Sam": "Good_Sam",
176 "Happy Camper": "Happy_Camper",
177 "KOA": "KOA",
178 "Local CG": "Local_CG",
179 "Military": "Military",
180 "NACC": "NACC",
181 "National Forest": "National_Forest",
182 "National Monument": "National_Monument",
183 "National Park": "National_Park",
184 "National Recreation Area": "National_Recreation_Area",
185 "National Seashore": "National_Seashore",
186 "National Wildlife Refuge": "National_Wildlife_Refuge",
187 "Outdoor Resorts": "Outdoor_Resorts",
188 "Passport America": "Passport_America",
189 "Provincial Park": -1,
190 "Provincial Preserve": -1,
191 "Rec USA": "Rec_USA",
192 "ROD": "ROD",
193 "RPI Preferred": "RPI_Preferred",
194 "RPI": "RPI",
195 "SKP Co-Op": "SKP_Co_Op",
196 "SKP Discount": "SKP_Discount",
197 "SKP Rainbow": "SKP_Rainbow",
198 "State Beach": "State_Beach",
199 "State CG": "State_CG",
200 "State Conservation Area": "State_Conservation_Area",
201 "State Forest": "State_Forest",
202 "State Park": "State_Park",
203 "State Preserve": "State_Preserve",
204 "State Rec Area": "State_Rec_Area",
205 "TT-Encore": "TT_Encore",
206 "TT-Leisure Time": "TT_Leisure_Time",
207 "TT-Mid Atlantic": "TT_Mid_Atlantic",
208 "TT-NACO": "TT_NACO",
209 "TT-Outdoor World": "TT_Outdoor_World",
210 "TT-Thousand Trails": "TT_Thousand_Trails",
211 "TVA CG": "TVA_CG",
212 "Western Horizon": "Western_Horizon",
213 "Wildlife Management Area": "Wildlife_Management_Area",
214 "Yogi Bear": "Yogi_Bear",
215 "Bass Pro Shops-No Park": -1,
216 "Bass Pro Shops Overnite Parking OK": -1,
217 "Bass Pro Shops-Park OK": -1,
218 "BJs": -1,
219 "Bob Evans No Parking": -1,
220 "Bob Evans Parking OK": -1,
221 "Camping World": -1,
222 "Casino with Campground": -1,
223 "Casino with Overnight Parking": -1,
224 "Costco": -1,
225 "Cracker Barrel (No Parking)": -1,
226 "Cracker Barrel (Parking OK)": -1,
227 "Fuel Bosselman": -1,
228 "Fuel Flying J": -1,
229 "Fuel Kangaroo Express": -1,
230 "Fuel Loves": -1,
231 "Fuel Other Truck Stops": -1,
232 "Fuel Petro": -1,
233 "Fuel Pilot": -1,
234 "Fuel Road Ranger": -1,
235 "Fuel Town Pump": -1,
236 "Fuel Travel America": -1,
237 "Kmart": -1,
238 "Pet Hospital": -1,
239 "Rest Stop no Dump Station": -1,
240 "Rest Stop - RV Dump": -1,
241 "Super Walmart-No Park": -1,
242 "Super Walmart-Park OK": -1,
243 "Walmart-No Park": -1,
244 "Walmart-Park OK": -1,
245 "Bridges Under 10 ft": -1,
246 "Bridges 10 ft to 11 ft": -1,
247 "Bridges 11 ft to 12 ft": -1,
248 "Bridges 12 ft to 13 ft": -1,
249 "Bridges 13 ft to 14 ft": -1,
250 "Bridges 14 ft to 15 ft": -1,
251 "Sams Club": -1,
252 "Canadian Provincial Preserve": "Canadian_Provincial_Preserve"
253}, _defineProperty(_affilImages, "Casino with Overnight Parking", -1), _defineProperty(_affilImages, "Fuel", -1), _defineProperty(_affilImages, "AAA", "AAA"), _defineProperty(_affilImages, "Freedom Resorts", "Freedom_Resorts"), _defineProperty(_affilImages, "City Park", "City_Park"), _defineProperty(_affilImages, "Encore", "Encore"), _defineProperty(_affilImages, "Escapees", "Escapees"), _defineProperty(_affilImages, "County Park", "County_Park"), _defineProperty(_affilImages, "Golf Course", -1), _defineProperty(_affilImages, "Ocean Canyon Properties", "Ocean_Canyon_Properties"), _defineProperty(_affilImages, "Coast to Coast-Premier", "Coast_to_Coast_Premier"), _defineProperty(_affilImages, "Ready Camp GO!", "Ready_Camp_GO!"), _affilImages);
254$.ajaxSetup({
255 timeout: _global.globalAjaxTimeout,
256 data: {
257 rnd: _global.utils.rnd
258 },
259 beforeSend: function beforeSend(xhr, options) {
260 if (!options.noblock) {
261 callBlockUI();
262 }
263 if (options.ws) {
264 var params = options.url ? "?" + options.url.split("?")[1] : false;
265 options.url = "/app/ws/" + options.ws + ".php" + (params ? params : "");
266 }
267 }
268});
269$(document).ajaxComplete(function (event, xhr, options) {
270 if (!options.noblock) {
271 callUnBlockUI();
272 }
273});
274
275
276$("#close-research-modal").on('change', function () {
277 if ($(this).is(":checked")) {
278 seenFilter = 1;
279 } else {
280 seenFilter = 0;
281 }
282});
283
284$(function () {
285 progressBarService.start();
286
287 /* No sidebar = print mode */
288 if ($("#sidebar").length > 0) {
289 $('.rv-search-empty-container').hide();
290 getTrips().then(function () {
291 loadUserProfile()
292 .then(progressBarService.stop);
293 });
294 initGmap();
295 } else {
296 userProfile = {
297 id: 0
298 };
299 showFullRoute = true;
300 initGmap(true);
301 loadSelectedTrip($("#trip_id").val())
302 .then(progressBarService.stop);
303 }
304});
305
306
307
308var scaleInterval = setInterval(function () {
309 var spn = $(".gm-style-cc");
310 var pattern = /\d+\s+(m|km)/i;
311 for (var i in spn) {
312 if (pattern.test(spn[i].innerHTML)) {
313 spn[i].click();
314 clearInterval(scaleInterval);
315 }
316 }
317}, 500);
318setTimeout(function () {
319 clearInterval(scaleInterval);
320}, 20000);
321
322var resetSession = setInterval(function () {
323 $.ajax({
324 type: "POST",
325 ws: "update_session",
326 data: {},
327 success: function success(res) {
328 if (!handleAjaxError(res)) {
329 clearInterval(resetSession);
330 return;
331 }
332 }
333 });
334}, 300000);
335
336
337function currentLocationControl(map, zoom) {
338 var controlContainer = document.createElement('div');
339 controlContainer.className = 'default-map-button current-position-button';
340
341 var control = document.createElement('div');
342 controlContainer.appendChild(control);
343
344
345 var currentPosition;
346
347 controlContainer.addEventListener('click', function () {
348 function showLocation(position, map, controlContainer) {
349 if (!position || !map) {
350 return;
351 }
352
353 map.setCenter(position);
354 map.setZoom(zoom);
355
356 var userMarker = new google.maps.Marker({
357 position: currentPosition,
358 map: map,
359 icon: 'https://www.robotwoods.com/dev/misc/bluecircle.png'
360 });
361
362 controlContainer.className += ' active';
363 }
364
365 if (controlContainer.className.indexOf('blocked') > -1) {
366 return;
367 }
368
369 if (currentPosition) {
370 showLocation(currentPosition, map, controlContainer);
371 return;
372 }
373
374 var changeIconInterval = setInterval(function () {
375 if (controlContainer.className.indexOf('loading-blank') === -1) {
376 controlContainer.className += ' loading-blank';
377 } else {
378 controlContainer.className = controlContainer.className.replace('loading-blank', '');
379 }
380 }, 500);
381
382 if (navigator.geolocation) {
383 navigator.geolocation.getCurrentPosition(function (pos) {
384 currentPosition = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
385 showLocation(currentPosition, map, controlContainer);
386
387 clearInterval(changeIconInterval);
388
389 controlContainer.className = controlContainer.className.replace('loading-blank', '');
390 }, function (error) {
391 controlContainer.className = controlContainer.className.replace('loading-blank', '');
392 setUserLocationMapFailMsg();
393
394 clearInterval(changeIconInterval);
395 });
396
397 }
398 });
399
400 return controlContainer;
401}
402
403var showBigIcon = function () {
404 $.each(arrMarkers, function (key, arrMarker) {
405 if (arrMarker.icon && arrMarker.icon.size && arrMarker.icon.size.height > 30) {
406 arrMarker.search = "yes";
407 arrMarker.setMap(map);
408 }
409 });
410};
411
412function initGmap(nocontrols) {
413 var options = {
414 mapTypeControl: true,
415 panControl: true,
416 gestureHandling: 'greedy',
417 zoomControl: true,
418 zoomControlOptions: {
419 position: google.maps.ControlPosition.RIGHT_TOP
420 },
421 scaleControl: true,
422 scrollwheel: true,
423 mapTypeControlOptions: {
424 mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN],
425 position: google.maps.ControlPosition.RIGHT_BOTTOM
426 },
427 streetViewControl: true,
428 streetViewControlOptions: {
429 position: google.maps.ControlPosition.RIGHT_TOP
430 },
431 mapTypeId: google.maps.MapTypeId.ROADMAP
432 };
433 if (nocontrols) {
434 options.disableDefaultUI = true;
435 options.streetViewControl = false;
436 options.mapTypeControl = false;
437 options.zoomControl = false;
438 }
439
440 map = new google.maps.Map(document.getElementById("divMap"), options);
441 LocationServiceHelper.initializeLocationServices();
442
443 var control = new currentLocationControl(map, _global.map.zoom.end);
444 control.index = 2;
445 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(control);
446
447 directionsService = new google.maps.DirectionsService();
448 map.setCenter(new google.maps.LatLng(_global.map.center.lat, _global.map.center.lon));
449 _global.map.zoom.default = _global.map.zoom.default < _global.map.zoom.min ? _global.map.zoom.min : _global.map.zoom.default;
450 map.setZoom(_global.map.zoom.default);
451 // Binding Google Maps events
452 google.maps.event.addListener(map, "idle", function () {
453
454 if (!showFullRoute) {
455 if (disableCgPoiLoading == true) {
456 doSearch(showBigIcon);
457 }
458 callDoSearch();
459 }
460 });
461
462 google.maps.event.addListener(map, "rightclick", function (e) {
463 ShowCustomStopModal(e);
464 });
465
466 var showCStop;
467 google.maps.event.addListener(map, "mousedown", function (e) {
468 if ($(".dropdown-poi").hasClass("open")) {
469 saveTopPois();
470 }
471 if (rvTripHelper.isDevice()) {
472 if (showCStop) {
473 clearTimeout(showCStop);
474 }
475 showCStop = setTimeout(function () {
476 ShowCustomStopModal(e);
477 }, 1250);
478 }
479 });
480
481 google.maps.event.addListener(map, "dragend", function (e) {
482 revertOpacitySearch();
483 revertFullRouteMarkers();
484 closeMarkerInfoBox();
485 isDragging = false;
486 $('.current-position-button.active').removeClass('active');
487 });
488
489 google.maps.event.addListener(map, "dragstart", function (e) {
490 isDragging = true;
491 clearTimeout(showCStop);
492 });
493
494 $("#divMap").mouseup(function () {
495 clearTimeout(showCStop);
496 });
497
498 google.maps.event.addListener(map, "click", function () {
499 closeMarkerInfoBox();
500 });
501
502 google.maps.event.addListener(map, "zoom_changed", function () {
503 clearTimeout(showCStop);
504 $('.current-position-button.active').removeClass('active');
505
506 var currZoom = map.getZoom();
507 if (currZoom < _global.map.zoom.min) {
508 map.setZoom(_global.map.zoom.min);
509 }
510
511 if (currZoom < _global.map.zoom.end) {
512 placesNearBy.clearPlacesMarker();
513 if (Object.keys(nonCgPois).length > 0) {
514 resetNonOverNightPoiList();
515 }
516 }
517 });
518
519 // Binding DOM events
520 $(".btnExpand").on("click", showRouteFullExent);
521 $(".sel-extra-layer").on("click", function () {
522 if (lockMapService.isLocked()) {
523 return;
524 }
525
526 overlayExtraLayer($(this).children("i").hasClass("fa-bicycle"));
527 });
528 $(".tbt-close").on("click", function () {
529 tbT.panelHide();
530 printManager.clearPrint();
531 });
532 $(".tbt-print").on("click", function () {
533 var bounds = rvTripHelper.getRouteExtend();
534 RouteTable.prepareForPrint();
535 callBlockUI();
536 printTBTTrip();
537 callUnBlockUI();
538 });
539 $(".map-header-btn-drag-route").on("click", function () {
540 isDragEnabled = !isDragEnabled;
541 RouteTable.toggleDragRoute();
542 //dragRoute.toggleDragRoute();
543 });
544
545 $("#routeList").on("mouseleave", function (event) {
546
547 event.preventDefault();
548 markerAnimation.stopAllBounceMarker();
549 });
550
551 //unused button for gradient viewer
552
553 // var customControlDiv = document.createElement('div');
554 // var customControl = new CustomControl(customControlDiv, map);
555 //
556 // customControlDiv.index = 1;
557 // map.controls[google.maps.ControlPosition.LEFT_TOP].push(customControlDiv);
558 //
559 // function CustomControl(controlDiv, map) {
560 //
561 // // Set CSS for the control border
562 // var controlUI = document.createElement('div');
563 // controlUI.style.backgroundColor = '#fff';
564 // controlUI.style.borderStyle = '2px solid #fff';
565 // controlUI.style.borderWidth = '1px';
566 // controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
567 // controlUI.style.marginTop = '5px';
568 // controlUI.style.cursor = 'pointer';
569 // controlUI.style.marginBottom = '22px';
570 // controlUI.style.textAlign = 'center';
571 // controlUI.title = 'Click to set the map to Home';
572 // controlDiv.appendChild(controlUI);
573 //
574 // // Set CSS for the control interior
575 // var controlText = document.createElement('div');
576 // controlText.style.color = 'rgb(25,25,25)';
577 // controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
578 // controlText.style.fontSize = '16px';
579 // controlText.style.lineHeight = '38px';
580 // controlText.style.paddingLeft = '5px';
581 // controlText.style.paddingRight = '5px';
582 // controlText.innerHTML = 'Elevation';
583 // controlUI.appendChild(controlText);
584 //
585 // // Setup the click event listeners
586 // google.maps.event.addDomListener(controlUI, 'click', function () {
587 // showElevationProfile();
588 // });
589 // }
590 // var customControlDiv = document.createElement('div');
591 // var customControl = new CustomControl(customControlDiv, map);
592 //
593 // customControlDiv.index = 1;
594 // map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(customControlDiv);
595 //
596 // function CustomControl(controlDiv, map) {
597 //
598 // // Set CSS for the control border
599 // var controlUI = document.createElement('div');
600 // controlUI.style.backgroundColor = '#18B6B4';
601 // controlUI.style.borderStyle = '2px solid #fff';
602 // controlUI.style.borderWidth = '1px';
603 // controlUI.style.borderRadius= '4px';
604 // controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
605 // controlUI.style.marginTop = '5px';
606 // controlUI.style.cursor = 'pointer';
607 // controlUI.style.marginBottom = '22px';
608 // //controlUI.style.bottom = '62px';
609 // controlUI.style.textAlign = 'center';
610 // controlUI.title = 'Click to show the trip elevation profile';
611 // controlDiv.appendChild(controlUI);
612 //
613 //
614 // // Set CSS for the control interior
615 // var controlText = document.createElement('div');
616 // controlText.id='ElevationBtnText';
617 // controlText.style.color = '#F5F5F5';
618 // controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
619 // controlText.style.fontSize = '16px';
620 // controlText.style.lineHeight = '30px';
621 // controlText.style.paddingLeft = '5px';
622 // controlText.style.paddingRight = '5px';
623 // controlText.classList.add("hidden-md");
624 // controlText.classList.add("hidden-sm");
625 // controlText.classList.add("hidden-xs");
626 // controlText.classList.add("btn");
627 // controlText.innerHTML = 'Elevation (BETA) \u21e7';
628 // controlUI.appendChild(controlText);
629
630
631
632 // Setup the click event listeners
633 // google.maps.event.addDomListener(controlUI, 'click', function (e) {
634 // if($(this).children().hasClass("disabled")){
635 // e.preventDefault();
636 // e.stopPropagation();
637 // notificationService.show(_global.msg.elevation);
638 // }
639 // else{
640 //
641 // if($('#elevation_chart').is(":hidden")){
642 // var mapheight = $("#mapContainer").parent().height()
643 // debug && console.log(mapheight);
644 // // animates sidebar toggle to go up and out of way of the chart
645 // $('.nav-pills').animate({
646 // bottom: mapheight * .50
647 // }, 750, function() {
648 // // Animation complete.
649 // })
650 // }
651 // else{
652 // if(gradientVisible){
653 // $("#showGradeBtn").trigger("click");
654 // }
655 // $('.nav-pills').animate({
656 // bottom: "100px"
657 // }, 750, function() {
658 //
659 // })
660 // }
661 //
662 // showElevationProfile();
663 // }
664 // });
665 //}
666}
667// resizes the chart when the sidebar comes in and out on desktop version
668
669$(".nav-pills-filter").click(function () {
670 if ($(".aside-right").hasClass("desk-visible-right")) {
671 $(".nav-right").removeClass("initial-hidden");
672 }
673});
674$(".nav-pills, .nav-pills-filter").click(function () {
675 if (!HighchartService.chart) {
676 return;
677 }
678
679 // ElevationSection.recalculateElevationSize();
680
681});
682
683
684$.ajax({
685 url: apiUrl + 'options/all',
686 headers: {
687 Accept: 'application/x.rvparkreviews.v2+json'
688 },
689 accepts: {
690 rvprv1: 'application/x.rvparkreviews.v2+json'
691 },
692 converters: {
693 'text rvprv1': function (result) {
694 return $.parseJSON(result);
695 }
696 },
697 type: 'GET',
698 success: function success(res) {
699 filterOptions = res;
700 initFilters();
701 }
702});
703
704function ShowCustomStopModal(e) {
705 if (map.getZoom() < _global.map.zoom.end || isDragging) {
706 notificationService.show(_global.msg.ZoomInForCustomStop);
707 return;
708 }
709 addCustomStop(e.latLng);
710}
711
712function addCustomStop(currentCenter, poi) {
713 if (!currentCenter || !curRoute) {
714 return;
715 }
716
717 var service = new geoService();
718 curBasicPoi = null;
719 service.getNearestCityByLocation(
720 currentCenter.lat(),
721 currentCenter.lng(),
722 function (city) {
723 showCustomStop(currentCenter.lat(), currentCenter.lng(), 'Near ' + city);
724 });
725}
726
727function lowerToUpper(str) {
728 str = str.replace(/_/g, ' ');
729 return str.replace(/\w\S*/g, function (txt) {
730 return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
731 });
732}
733
734function showCustomStop(lat, lng, title, extraData) {
735 // curBasicPoi = null;
736 var customStop = $('#custom-poi-info-modal');
737 $('#name-custom').val(title);
738 $('#lat-custom').val(lat);
739 $('#lon-custom').val(lng);
740 $('#street-custom').val(extraData ? extraData.street : '');
741 $(".follow-trip").empty();
742
743 var disableStopToFollow = !curRoute || !curRoute.routeLegs || curRoute.routeLegs.length < 1;
744
745 if (disableStopToFollow) {
746 $(".stop-select input, .stop-select select").prop("disabled", "true");
747 } else {
748 $(".stop-select input, .stop-select select").removeProp("disabled");
749 }
750
751 $(".stop-select select").attr("disabled", function () {
752 return !$(this).siblings("input[type=radio]")[0].checked;
753 });
754 var customPoiInfo = customStop.find('#poi-type-custom');
755 customPoiInfo.val('');
756
757 if (extraData && extraData.poi_type_image) {
758 customPoiInfo.val(extraData.poi_type_image);
759 }
760
761 if (extraData && extraData.imageName) {
762 customPoiInfo.val(extraData.imageName);
763 }
764
765 setRouteCombo(null);
766 customStop.modal('show');
767}
768
769function overlayExtraLayer(bicycling) {
770 if (bicycling) {
771 bicycleLayer = new google.maps.BicyclingLayer();
772 bicycleLayer.setMap(map);
773 } else {
774 if (bicycleLayer) {
775 bicycleLayer.setMap(null);
776 }
777 }
778}
779
780function checkTripName(name) {
781 for (var i = 0; i < OpenTripModal.getTripsListLength(); i++) {
782 if (OpenTripModal.getTripsList()[i].name.toLowerCase() == name.toLowerCase()) {
783 return name;
784 }
785 }
786
787 return false;
788}
789
790function tryCloseInfobox() {
791 clearTimeout(infoBoxDistanceTimeOut);
792 if (infoBox) {
793 infoBox.close();
794 }
795}
796var topNav = $('#top-nav');
797topNav.on('click', tryCloseInfobox);
798topNav.on('mouseover', tryCloseInfobox);
799
800
801
802
803function printTBTTrip() {
804 PrintHelper.setCurRoute(curRoute);
805 PrintHelper.printTurnByTurn();
806}
807
808function printTrip(printType) {
809 PrintHelper.setCurRoute(curRoute);
810 PrintHelper.printMap(printType);
811}
812
813function routesForIE11(routes) {
814 var processedRoutes = $.map(routes, function (val, i) {
815
816 var clonedPoi = jQuery.extend(true, {}, val.poi);
817 var marker = {
818 'lat': clonedPoi.marker.getPosition().lat(),
819 'lng': clonedPoi.marker.getPosition().lng()
820 };
821 clonedPoi.marker = marker;
822
823 return {
824 'poi': clonedPoi
825 };
826 });
827
828 return processedRoutes;
829}
830
831function routeMarkersForIE11(routeMarkers) {
832 var processedRouteMarkers = $.map(routeMarkers, function (val, i) {
833 var marker = {
834 'url': val.getIcon().url,
835 'lat': val.getPosition().lat(),
836 'lng': val.getPosition().lng()
837 };
838 return marker;
839 });
840 return processedRouteMarkers;
841}
842$("#edit-trip-notes-modal-form").find("#btnRmNotes").on("click", function (event) {
843 event.preventDefault();
844 curRoute.notes = "";
845 genRouteListing();
846 SaveTrip();
847 $("#edit-trip-notes-modal").modal("hide");
848});
849$("#edit-trip-notes-modal-form").on("submit", function (event) {
850 event.preventDefault();
851 curRoute.notes = $("#txteditTripNotesPop").val();
852 //$(".rv-search").val(curRoute.name);
853 //$("#trip-select option:contains(\"" + prevName + "\")").text(curRoute.name);
854 //genRouteListing();
855 SaveTrip();
856 $("#edit-trip-notes-modal").modal("hide");
857});
858
859//$("#edit-trip-notes-modal-form").find("btnRmNotes").on("click", function (event) {
860
861$(".btn-elevation").click(function (e) {
862 if ($(this).hasClass("disabled")) {
863 e.preventDefault();
864 e.stopPropagation();
865 notificationService.show(_global.msg.elevation);
866 } else {
867 showElevationProfile();
868 if ($(this).hasClass("active")) {
869 $("img[name=elevation-img]").attr("src", "/app/images/elevation-icon.svg");
870
871 } else {
872 $("img[name=elevation-img]").attr("src", "/app/images/elevation-icon-white.svg");
873 }
874
875 }
876});
877
878function clearMap() {
879 clearRoutesOverlays();
880 rvTripHelper.clearDriveCircle();
881 rvTripLC.clearOverlayLC();
882 rvTripLC.clearHeightDataOverlayOnly();
883 fuelCalculator.clearFuelWarningMarker();
884}
885
886
887
888function initRoute() {
889 $("#hdnTripId").val("-1");
890 $("#routeList").html("");
891 curSelItemIndex = null;
892
893 curRoute = {
894 "name": null,
895 "routeLegs": [],
896 "status": false,
897 "startDate": null
898 };
899
900 if (curUserPoiMarker) {
901 curUserPoiMarker.setMap(null);
902 }
903
904 clearStartMarker();
905
906}
907//reset the page like initial stage. Clear all display data
908function resetTripWizard() {
909 $('.rv-search-empty-container').show();
910 $(".rv-search").val("");
911 // $(".trips-count").text(OpenTripModal.getTripsListLength() - 1 >= 0 ? OpenTripModal.getTripsListLength() - 1 : 0);
912 $("#trip-select option:contains(\"" + curRoute.name + "\")").remove();
913 $(".totDistance span, .totDistance div, .totNights span, .totNights div, .totCost span, .totCost div").text("");
914 $(".rv-trip tfoot").addClass("hidden");
915 $("#trip-options").addClass("hidden");
916 clearRoutesOverlays();
917 curRoute = null;
918 resetNonOverNightPoiList();
919 $("#hdnTripId").val("-1");
920 $("#routeList").empty();
921 curSelItemIndex = null;
922 clearFindPointMarker();
923 clearStartMarker();
924 closeMarkerInfoBox();
925 rvTripHelper.clearDriveCircle();
926 fuelCalculator.clearFuelWarningMarker();
927 lockMapService.tryLockIfNoRoutes(curRoute);
928}
929
930
931
932function showRouteFullExent() {
933 if (curRoute !== null && curRoute.routeLegs.length > 1) {
934 revertOpacitySearch();
935 setMapBoundToTrip(curRoute.routeLegs);
936 }
937}
938
939function loadUserProfile() {
940 progressBarService.start();
941
942 return $.ajax({
943 ws: "get_data",
944 data: {
945 action: "getUserProfile",
946 trip_user_id: $("#trip_user_id").val()
947 },
948 success: function success(res) {
949 if (!handleAjaxError(res)) {
950 return;
951 }
952
953 userProfile = res.data;
954 Object.assign(userProfile, {
955 id: parseInt(userProfile.id, 10),
956 mpg: parseFloat(userProfile.mpg),
957 cpg: parseFloat(userProfile.cpg),
958 fuel_capacity: parseInt(userProfile.fuel_capacity, 10),
959 fuel_reserve: parseInt(userProfile.fuel_reserve, 10),
960 camping: parseFloat(userProfile.camping),
961 meals: parseFloat(userProfile.meals),
962 misc: parseFloat(userProfile.misc),
963 gas_type: userProfile.gas_type,
964 height_ff: parseInt(userProfile.height_ff, 10),
965 height_nn: parseInt(userProfile.height_nn, 10),
966 emp_user_id: parseInt(userProfile.emp_user_id, 10),
967 set_preference: parseInt(userProfile.set_preference, 10),
968 miles_per_day: parseFloat(userProfile.miles_per_day),
969 driving_inner_radius: myParseFloat(userProfile.driving_inner_radius),
970 driving_middle_radius: myParseFloat(userProfile.driving_middle_radius),
971 trip_count: parseFloat(userProfile.trip_count),
972 is_drag_route: userProfile.is_drag_route === "1",
973 is_load_last_trip: userProfile.is_load_last_trip === "1",
974 click_to_view_info_on_map: userProfile.click_to_view_info_on_map === "1",
975 show_parks: userProfile.show_parks === "1",
976 seen_filter: userProfile.seen_filter === "1",
977 driving_pref: userProfile.driving_pref ? userProfile.driving_pref : 'hpd',
978 open_trips_sort_field: userProfile.open_trips_sort_field ? parseInt(userProfile.open_trips_sort_field) : null,
979 open_trips_sort_order: userProfile.open_trips_sort_order ? parseInt(userProfile.open_trips_sort_order) : null,
980 archived_trips_sort_field: userProfile.archived_trips_sort_field ? parseInt(userProfile.archived_trips_sort_field) : null,
981 archived_trips_sort_order: userProfile.archived_trips_sort_order ? parseInt(userProfile.archived_trips_sort_order) : null
982 });
983
984
985 if ($('#is_demo_user').val() == 'true') {
986 demouUserService.init();
987 } else {
988
989 // get pageState
990 var pState = PageState.getState();
991
992 if (!userProfile.is_load_last_trip) {
993 $('.rv-search-empty-container').show();
994 }
995
996 if (userProfile.is_load_last_trip && pState && pState.tripId) {
997 loadSelectedTrip(pState.tripId);
998 }
999
1000 lockMapService.tryLockIfNoRoutes(curRoute);
1001 }
1002
1003 OpenTripModal.loadAllSavedOptions(userProfile);
1004
1005 },
1006 complete: function () {
1007 progressBarService.stop();
1008 },
1009 error: function (x, y, z) {
1010 console.log(x, y, z);
1011 }
1012 });
1013}
1014
1015
1016
1017function myParseFloat(value) {
1018 if (value) {
1019 if (value != "" && value != "0") {
1020 return parseFloat(value);
1021 }
1022 }
1023
1024 return null;
1025}
1026
1027function clickPoiChkBox(chk, id) {
1028 if (map.getZoom() < _global.map.zoom.end) {
1029 notificationService.show(_global.msg.zoomInToShowPoi);
1030 $(chk).removeClass("selected");
1031 return;
1032 }
1033 var $filteredPoi = $('.poi-container .green-background');
1034 if ($filteredPoi.length > 0 && !$filteredPoi.hasClass('selected')) {
1035 if (filterValues.fuel || filterValues.dump || filterValues.overnight) {
1036 $(".poi-container-filter button").prop("disabled", true);
1037 $filteredPoi.each(function (index, item) {
1038 //filterpoi load here
1039 $(item).attr("disabled", true);
1040 loadNonPoi($(item).val(), function (index) {
1041 return function () {
1042 $(item).attr("disabled", false);
1043 if (index == $filteredPoi.length - 1) {
1044 $(".poi-container-filter button").prop("disabled", false);
1045 }
1046 };
1047 }(index));
1048 });
1049 }
1050 }
1051 if ($filteredPoi.hasClass('selected')) {
1052 $filteredPoi.each(function (index, item) {
1053
1054 if (!$(item).hasClass('selected')) {
1055
1056 clearNonOvernightPoi($(item).val());
1057 } else {}
1058 });
1059 }
1060 if ($(chk).hasClass('selected') == false) {
1061 // clear map all line overlays
1062 clearNonOvernightPoi(id);
1063 return;
1064 }
1065
1066 $(chk).attr("disabled", true);
1067
1068 loadNonPoi(id, function (status) {
1069 $(chk).prop("disabled", false);
1070 });
1071
1072}
1073
1074function loadNonPoi(id, callback) {
1075 updatingPois.push(true);
1076 var bound = map.getBounds();
1077 if (!bound) {
1078 return;
1079 }
1080 var leftBottom = bound.getSouthWest();
1081 var rightTop = bound.getNorthEast();
1082 rvTripHelper.disableRightSideChks();
1083 $.ajax({
1084 ws: "search_poi",
1085 noblock: true,
1086 tryCount: 0,
1087 retryLimit: 3,
1088 data: {
1089 filter: JSON.stringify(filterValues),
1090 id: id,
1091 lon_min: _global.utils.round(leftBottom.lng(), 4),
1092 lat_min: _global.utils.round(leftBottom.lat(), 4),
1093 lon_max: _global.utils.round(rightTop.lng(), 4),
1094 lat_max: _global.utils.round(rightTop.lat(), 4),
1095 trip_user_id: $("#trip_user_id").val()
1096 },
1097 success: function success(res) {
1098 if (debug) console.log(res);
1099 rvTripHelper.enableRightSideChks();
1100 var flag = false;
1101
1102 if (!handleAjaxError(res)) {
1103 return;
1104 }
1105
1106 var myPois = res.poi;
1107 poisInView = res.poi;
1108 if (myPois.length > 0) {
1109 //clearNonOvernightPoi(id);
1110 // display Map
1111 readNonOvernightPoi(myPois, id, res.poi_img_name);
1112 flag = true;
1113 }
1114 var poiTotal = 0;
1115 $.each(nonCgPois, function (index, item) {
1116
1117 $.each(item, function (index2, item2) {
1118 poiTotal += 1;
1119 });
1120 });
1121 $(".poi-filter-count").text(poiTotal + " ");
1122
1123 if (callback) {
1124 callback(flag);
1125 }
1126 updatingPois.pop();
1127 },
1128 error: function error(x, y, z) {
1129 if (y == "timeout") {
1130 this.tryCount++;
1131 if (this.tryCount <= this.retryLimit) {
1132 $.ajax(this);
1133 return;
1134 }
1135 }
1136 rvTripHelper.enableRightSideChks();
1137 if (callback) {
1138 callback(false);
1139 }
1140 }
1141 });
1142}
1143
1144function readNonOvernightPoi(pois, id, imgName) {
1145 tempMarkers = {};
1146 if (pois.length > 0) {
1147 (function () {
1148 if (!nonCgPois.hasOwnProperty(id)) {
1149 nonCgPois[id] = {};
1150 }
1151
1152 $.each(pois, function (key, poi) {
1153 tempMarkers[poi.id] = true;
1154 if (!nonCgPois[id].hasOwnProperty(poi.id)) {
1155 poi.poiCat = PoiCat.BASIC;
1156 if (id == 17 && poi.dump == 0) {
1157 poi.imageName = "Rest_Stop_no_Dump_Station.png";
1158 }
1159 nonCgPois[id][poi.id] = createMarker(poi, 3, imgName);
1160 // Does this poi override another poi? If so, hide those pois
1161 $.each(poi.overrides, function (cat, state) {
1162 if (cat != id && nonCgPois[cat] && nonCgPois[cat].hasOwnProperty(poi.id)) {
1163 nonCgPois[cat][poi.id].setVisible(false);
1164 }
1165 });
1166
1167 // Does this poi underride another poi? If so, hide this poi
1168 $.each(poi.underrides, function (cat, state) {
1169 if (cat != id && nonCgPois[cat] && nonCgPois[cat].hasOwnProperty(poi.id)) {
1170 nonCgPois[id][poi.id].setVisible(false);
1171 }
1172 });
1173 }
1174 });
1175 })();
1176 }
1177
1178 $.each(nonCgPois[id], function (key, marker) {
1179 if (!tempMarkers.hasOwnProperty(key)) {
1180 // Check if this marker hid another
1181 $.each(marker.overrides, function (cat, state) {
1182 if (nonCgPois[cat] && nonCgPois[cat].hasOwnProperty(key)) {
1183 nonCgPois[cat][key].setVisible(true);
1184 }
1185 });
1186
1187 nonCgPois[id][key].setMap(null);
1188 nonCgPois[id][key] = null;
1189 delete nonCgPois[id][key];
1190 }
1191 });
1192}
1193
1194function clearNonOvernightPoi(id) {
1195 var poiTotal = 0;
1196 if (nonCgPois) {
1197 if (nonCgPois.hasOwnProperty(id)) {
1198 $.each(nonCgPois[id], function (id2, marker) {
1199 // Check if this marker hid another
1200 if (!marker.inRoute) {
1201 $.each(marker.overrides, function (cat, state) {
1202 if (nonCgPois[cat] && nonCgPois[cat].hasOwnProperty(id2)) {
1203 nonCgPois[cat][id2].setVisible(true);
1204 }
1205 });
1206 nonCgPois[id][id2].setMap(null);
1207 nonCgPois[id][id2] = null;
1208 }
1209 });
1210
1211 delete nonCgPois[id];
1212 $.each(nonCgPois, function (index, item) {
1213
1214 $.each(item, function (index2, item2) {
1215 poiTotal += 1;
1216 });
1217 if (debug) console.log(item.length);
1218 });
1219 }
1220 $(".poi-filter-count").text(poiTotal + " ");
1221 }
1222
1223 function resetNonOverNightPoiList() {
1224 // clear all non cg poi overlay and reset the collection
1225 if (nonCgPois) {
1226 $.each(nonCgPois, function (id, poi) {
1227 $.each(nonCgPois[id], function (id2, marker) {
1228 nonCgPois[id][id2].setMap(null);
1229 nonCgPois[id][id2] = null;
1230 delete nonCgPois[id][id2];
1231 });
1232 delete nonCgPois[id];
1233 });
1234 nonCgPois = {};
1235 }
1236 }
1237
1238 function callDoSearch(callback) {
1239 if (!disableCgPoiLoading) {
1240 if (callback) {
1241 doSearch(callback);
1242 } else {
1243 doSearch();
1244 }
1245
1246 }
1247 }
1248
1249 function doSearch(callback) {
1250 if (ajaxRegGetPoi && ajaxRegGetPoi.readyState && ajaxRegGetPoi.readyState < 4) {
1251 ajaxRegGetPoi.abort();
1252 }
1253 clearTimeout(searchTimeout);
1254 searchTimeout = setTimeout(function () {
1255 reallyDoSearch(callback);
1256 }, 500);
1257 }
1258
1259 function reallyDoSearch(callback) {
1260 $("#fifth-load-item").removeClass("not-loading").addClass("loading");
1261 if (disableCgPoiLoading) {
1262 $("#fifth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1263 checkLoadingModal();
1264 }
1265 // get map bound data
1266 var bound = map.getBounds();
1267 if (bound == null || bound == "undefined") {
1268 return;
1269 }
1270
1271 // rvTripLC.clearHeightData();
1272 if (map.getZoom() >= _global.heightClearenceViewZoom) {
1273 rvTripLC.loadHeightPoi();
1274 } else {
1275 rvTripLC.clearHeightData();
1276 }
1277 var leftBottom = bound.getSouthWest();
1278 var rightTop = bound.getNorthEast();
1279 var regType = 1;
1280 if (selectedState != "-1") {
1281 regType = 2;
1282 } else {
1283 regType = map.getZoom() < _global.map.zoom.end ? 1 : 2;
1284 }
1285
1286 var affiliationIds = [];
1287 $('#affiliations-fav li').each(function () {
1288 affiliationIds.push($(this).data('id'));
1289 });
1290
1291 var rating = $('[name=filter-rating]:checked').data('rating');
1292 var featuresIds = [];
1293 $('.filter-features input:checked').each(function () {
1294 featuresIds.push($(this).data('id'));
1295 });
1296 tryRefreshPOI();
1297
1298 //callBlockUI();
1299
1300 var data = {
1301 longitude_min: _global.utils.round(leftBottom.lng(), 4),
1302 latitude_min: _global.utils.round(leftBottom.lat(), 4),
1303 longitude_max: _global.utils.round(rightTop.lng(), 4),
1304 latitude_max: _global.utils.round(rightTop.lat(), 4),
1305 zoom: map.getZoom(),
1306 preferred_only: $('#show_only_pref_park').attr('checked') ? 1 : 0,
1307 include: 'photos_lite'
1308 };
1309
1310 /* At zooms less than 10, we won't load park_info with the parks. We will do that on park hover */
1311 if (map.getZoom() < 10) {
1312 // data.exclude = 'park_info';
1313 }
1314
1315 if (selectedState != -1) {
1316 data.region = selectedState;
1317 }
1318
1319 if ($('#filter-area-near').is(':checked')) {
1320 data.distance = parseInt($('#filter-area-range').val());
1321 data.source_longitude = map.getCenter().lng();
1322 data.source_latitude = map.getCenter().lat();
1323 }
1324
1325 if (rating !== '-1') {
1326 data.rating = rating;
1327 }
1328
1329 if (featuresIds.indexOf(-1) === -1) {
1330 data.featuresIds = featuresIds;
1331 }
1332
1333 if (affiliationIds.indexOf(-1) === -1) {
1334 data.affiliation_ids = affiliationIds;
1335 }
1336
1337 //closeMarkerInfoBox();
1338 var target;
1339 if (regType == 1) {
1340 target = apiUrl + '/parks/search/cluster';
1341 } else {
1342 target = apiUrl + '/parks/search';
1343 }
1344
1345 ajaxRegGetPoi = $.ajax({
1346 url: target,
1347 headers: {
1348 Accept: 'application/x.rvparkreviews.v2+json'
1349 },
1350 accepts: {
1351 rvprv1: 'application/x.rvparkreviews.v2+json'
1352 },
1353 converters: {
1354 'text rvprv1': function (result) {
1355 return $.parseJSON(result);
1356 }
1357 },
1358 dataType: 'rvprv1',
1359 noblock: true,
1360 data: data,
1361 type: 'GET',
1362 success: function success(res) {
1363 if (debug) console.log("API");
1364 if (!handleApiAjaxError(res)) {
1365 return;
1366 }
1367 // display Map
1368 parksInView = res.parks;
1369
1370 if (filterMapped == false) {
1371 if (debug) console.log('parksInView', parksInView);
1372 updateParksFiltering();
1373 } else {
1374 if (map.getZoom() < 8) {
1375 var noParks = document.createElement("span");
1376 noParks.classList.add('no-parks-filter-text');
1377 noParks.innerHTML = "Please Zoom In To View Parks";
1378 $("#parks-filter-body").empty();
1379 $("#parks-filter-body").append(noParks);
1380 $('.parks-filter-count').html("0");
1381 if ($('.filter-show-filters').text() == "Show Parks List") {
1382 $('.filter-show-filters').click();
1383 }
1384 }
1385 filterMapped = false;
1386 }
1387 readData(res.parks, false, callback, regType);
1388 },
1389 complete: function () {
1390 $("#fifth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1391 checkLoadingModal();
1392 },
1393 error: function (x, y, z) {
1394
1395 }
1396 });
1397 return ajaxRegGetPoi;
1398 }
1399
1400 function checkLoadingModal() {
1401 if (!$(".load-item").hasClass("loading") && !$(".load-item").hasClass("not-loading")) {
1402 $('#loader-modal').modal("hide");
1403 if (rvTripHelper.isDevice() && $("#sidebar").hasClass("visible")) {
1404 if (tableClicked == 1) {
1405 tableClicked = 0;
1406 } else {
1407 // $('#toggle-map-view-tiny').click();
1408 }
1409 }
1410 }
1411 }
1412 var showPois = true;
1413
1414 function tryRefreshPOI() {
1415 $("#fourth-load-item").removeClass("not-loading").addClass("loading");
1416 if (map.getZoom() < _global.map.zoom.end) {
1417 if (
1418 !lockMapService.isLocked() &&
1419 $('#poi-form').find('input[type=checkbox]:checked').length > 0 &&
1420 showPois // popup must be shown once
1421 ) {
1422 // protects first load from displaying msg if top half poi was saved
1423 if (curRoute) {
1424 notificationService.show(_global.msg.reZoomInToShowPoi);
1425 }
1426 }
1427
1428 showPois = false;
1429 placesNearBy.removePOIs();
1430 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1431 checkLoadingModal();
1432 return;
1433 }
1434
1435 showPois = true;
1436 placesNearBy.overlaySelectedAreaAttractionsByMapCenter();
1437 var poiFilterRest = $('.poi-container-filter button[name=rest-area-filter]');
1438 var id;
1439 var count;
1440 var currentCount;
1441 if ($('.poi-container button').hasClass('selected')) {
1442 count = $('.poi-container button[class*=selected]').length;
1443 if (count == 0) {
1444 if (currentCount == count) {
1445 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1446 checkLoadingModal();
1447 }
1448 }
1449 currentCount = 0;
1450 $('.poi-container button[class*=selected]').each(function (k, input) {
1451
1452 id = $(input).val();
1453 if (!id) {
1454 return false;
1455 }
1456 loadNonPoi(id, function () {
1457 currentCount += 1;
1458 if (currentCount == count) {
1459 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1460 checkLoadingModal();
1461 }
1462 });
1463 });
1464 } else if ($('.poi-container-filter button').not(poiFilterRest).hasClass('selected')) {
1465 count = $('.poi-container .green-background').length;
1466 if (count == 0) {
1467 if (currentCount == count) {
1468 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1469 checkLoadingModal();
1470 }
1471 }
1472 currentCount = 0;
1473 $('.poi-container .green-background').each(function (index, input) {
1474 id = $(input).val();
1475 if (!id) {
1476 return false;
1477 }
1478
1479 loadNonPoi(id, function () {
1480 currentCount += 1;
1481 if (currentCount == count) {
1482 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1483 checkLoadingModal();
1484 }
1485 });
1486 });
1487 } else {
1488 if (!initialLoad) {
1489 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
1490 checkLoadingModal();
1491 }
1492
1493 }
1494 if (poiFilterRest.hasClass('selected')) {
1495 loadNonPoi(17);
1496 }
1497 }
1498
1499 function readData(pois, setMapBound, callback, type) {
1500 var found = false;
1501 var looping = false;
1502 var pref = false;
1503 var i;
1504 if (curRoute) {
1505 if (curRoute.routeLegs && curRoute.routeLegs.length > 0 && highlightPoi != 0) {
1506 looping = true;
1507 for (i = 0; i < pois.length; i++) {
1508 if (pois[i].park_id + '-' + 1 == highlightPoi) {
1509 found = true;
1510 break;
1511 }
1512 }
1513 }
1514 if (!found && $('#show_only_pref_park').is(':checked') && prefParkSearch != null) {
1515 pref = true;
1516 found = true;
1517 $.ajax({
1518 url: apiUrl + 'parks/' + prefParkSearch.park_id,
1519 headers: {
1520 Accept: 'application/x.rvparkreviews.v2+json'
1521 },
1522 accepts: {
1523 rvprv1: 'application/x.rvparkreviews.v2+json'
1524 },
1525 dataType: 'rvprv1',
1526 noblock: true,
1527 type: 'GET',
1528 converters: {
1529 'text rvprv1': function (result) {
1530 return $.parseJSON(result);
1531 }
1532 },
1533 success: function success(res) {
1534 pois.push(res);
1535
1536 //read data cg=yes poi
1537 var i = 0;
1538 var bounds = new google.maps.LatLngBounds();
1539 // clear map all line overlays
1540 //clearMarkerOverlays();
1541
1542 if (pois.length < 1) {
1543 if (callback) {
1544 callback(pois);
1545 }
1546 }
1547
1548 if (type === 2) {
1549 createMarkersAndSetInMap(pois, bounds, setMapBound, type);
1550 if (callback) {
1551 callback(pois);
1552 }
1553 return;
1554 }
1555 createMarkersAndSetInMap(pois, bounds, setMapBound, type);
1556 }
1557 });
1558 }
1559 if (!found && looping) {
1560 alert('Invalid park, please contact us for help or create a custom stop');
1561 highlightPoi = 0;
1562 $("#search-location").val("");
1563 return;
1564 }
1565 }
1566 if (!pref) {
1567 //read data cg=yes poi
1568 i = 0;
1569 var bounds = new google.maps.LatLngBounds();
1570 // clear map all line overlays
1571 //clearMarkerOverlays();
1572
1573 if (pois.length < 1) {
1574 if (callback) {
1575 callback(pois);
1576 }
1577 }
1578
1579 if (type === 2) {
1580 createMarkersAndSetInMap(pois, bounds, setMapBound, type);
1581 if (callback) {
1582 callback(pois);
1583 }
1584 return;
1585 }
1586 createMarkersAndSetInMap(pois, bounds, setMapBound, type);
1587 }
1588 }
1589
1590 function getImages(pois, bounds, setMapBound, block, callback) {
1591 var parksIds = [];
1592 $(pois).each(function (k, poi) {
1593 if (poi.poitype_id == 1 && poi.id && parksIds.indexOf(poi.id) === -1) {
1594 parksIds.push(poi.id);
1595 }
1596 });
1597 var pageSize = 10;
1598 var parsedParksIds = parksIds.join(',');
1599 if (parksIds.length < 100) {
1600 $.ajax({
1601 url: apiUrl + 'parksindex',
1602 data: 'include=photos_lite&park_ids=' + parsedParksIds,
1603 noblock: !block,
1604 type: 'POST',
1605 dataType: 'rvprv1',
1606 accepts: {
1607 rvprv1: 'application/x.rvparkreviews.v1+json'
1608 },
1609 converters: {
1610 'text rvprv1': function (result) {
1611 return $.parseJSON(result);
1612 }
1613 },
1614 success: function (r) {
1615 var parks = r.parks;
1616 var currentPark;
1617 $(pois).each(function (k, poi) {
1618 // This needs to do the same thing for parks that we do when panning the map
1619 var curParkNights = poi.nights;
1620 var curParkComments = poi.comments;
1621 var curCostCamping = poi.costCamping;
1622 var curCostMeals = poi.costMeals;
1623 var curCostMisc = poi.costMisc;
1624 if (poi.poitype_id == 1) {
1625 currentPark = parks.filter(function (p) {
1626 return p.park_id === poi.id;
1627 });
1628
1629 if (currentPark.length) {
1630 pois[k] = $.extend(true, {}, formatParkObject(currentPark[0], pois[k]));
1631 pois[k].nights = curParkNights;
1632 pois[k].costCamping = curCostCamping;
1633 pois[k].costMeals = curCostMeals;
1634 pois[k].costMisc = curCostMisc;
1635 pois[k].comments = curParkComments;
1636 }
1637 }
1638 });
1639 if (callback) {
1640 callback(pois, bounds, setMapBound);
1641 }
1642
1643 }
1644 });
1645 } else {
1646 //run ajax call more twice once if > 100 parks
1647 var iterations = 0;
1648 var calledBack = false;
1649 while (iterations < 2) {
1650 parsedParksIds = parksIds.join(',');
1651
1652 var splitIds = parksIds.slice(0, 99).join(',');
1653 if (iterations == 1) {
1654 splitIds = parksIds.slice(99).join(',');
1655 }
1656 var parksResponse = [];
1657 $.ajax({
1658 url: apiUrl + 'parksindex',
1659 data: 'include=photos_lite&park_ids=' + splitIds,
1660 noblock: !block,
1661 type: 'POST',
1662 dataType: 'rvprv1',
1663 accepts: {
1664 rvprv1: 'application/x.rvparkreviews.v1+json'
1665 },
1666 converters: {
1667 'text rvprv1': function (result) {
1668 return $.parseJSON(result);
1669 }
1670 },
1671 success: function (r) {
1672 parksResponse = parksResponse.concat(r.parks);
1673
1674 if (iterations >= 1) {
1675 var currentPark;
1676 $(pois).each(function (k, poi) {
1677
1678 // This needs to do the same thing for parks that we do when panning the map
1679 var curParkNights = poi.nights;
1680 var curParkComments = poi.comments;
1681 if (poi.poitype_id == 1) {
1682 currentPark = parksResponse.filter(function (p) {
1683 return p.park_id === poi.id;
1684 });
1685
1686 if (currentPark.length) {
1687 pois[k] = $.extend(true, {}, formatParkObject(currentPark[0], pois[k]));
1688 pois[k].nights = curParkNights;
1689 pois[k].comments = curParkComments;
1690 }
1691 }
1692 });
1693
1694
1695 }
1696 if (callback && iterations >= 2 && !calledBack) {
1697 calledBack = true;
1698 callback(pois, bounds, setMapBound);
1699 }
1700 }
1701 });
1702
1703 iterations++;
1704 }
1705 }
1706 }
1707
1708 function clearMarkers(currentMarkers) {
1709 var routeMarkers = [];
1710 if (curRoute && curRoute.routeLegs) {
1711 routeMarkers = curRoute.routeLegs.map(function (leg) {
1712 return leg.poi.marker;
1713 });
1714 }
1715 $.each(arrMarkers, function (id, arrMarker) {
1716 if (
1717 !currentMarkers.hasOwnProperty(id) &&
1718 routeMarkers.indexOf(arrMarkers[id]) === -1
1719 // do not remove markers for trips
1720 ) {
1721 var del;
1722 if (arrMarker.poiType == 'height' || arrMarker.poiType == 'noncg') {
1723 del = false;
1724 } else {
1725 del = true;
1726 }
1727
1728 if (del) {
1729 arrMarkers[id].setMap(null);
1730 arrMarkers[id] = null;
1731 delete arrMarkers[id];
1732 }
1733 }
1734 });
1735
1736 }
1737
1738 function formatParkObject(park, existing) {
1739 if (!park.park_id) {
1740 return park;
1741 }
1742
1743 if (debug) {
1744 if (debug) console.log('Format Park Object - ' + park.park_id);
1745 }
1746
1747 var id = park.park_id;
1748 park.id = park.park_id;
1749 park.poitype_id = 1;
1750 park.poiCat = PoiCat.BASIC;
1751
1752 if (existing) {
1753 $.each(existing, function (key, item) {
1754 if (typeof park[key] == 'undefined') {
1755 park[key] = item;
1756 }
1757 });
1758 }
1759
1760 // Cycle through user affiliations
1761 $('#affiliations-fav li').each(function () {
1762 var this_id = $(this).data('id');
1763 $.each(park.affiliations, function (index, affiliation) {
1764 if (affiliation.affiliation_id == this_id && !park.imageName) {
1765 park.imageName = affiliation.image_name;
1766 return false;
1767 }
1768 });
1769 });
1770
1771 if (park.coordinates) {
1772 park.lat = park.coordinates.latitude;
1773 park.lon = park.coordinates.longitude;
1774 delete(park.coordinates);
1775 }
1776
1777 if (park.rating_avg) {
1778 park.rating = Math.round(park.rating_avg) / 2;
1779 }
1780
1781 if (park.photos_lite) {
1782 park.photos = park.photos_lite;
1783 delete(park.photos_lite);
1784 }
1785
1786 if (!park.imageName) {
1787 park.imageName = 'Default.png';
1788 }
1789
1790 if (park.waypoints) {
1791 park.waypoints = existing.waypoints;
1792 }
1793
1794
1795 return park;
1796 }
1797
1798 function createMarkersAndSetInMap(parks, bounds, setMapBound, type) {
1799 var tempMarkers = {};
1800
1801 parks.forEach(function (park) {
1802 var searchedPark;
1803 parkExists = false;
1804 if (!park.cenlat) {
1805 filteredParks.forEach(function (filterPark) {
1806 if (!park.park_id) {
1807 parkExists = true;
1808 return;
1809 }
1810 if (filterPark.park_id == park.park_id) {
1811 parkExists = true;
1812 return;
1813 }
1814 });
1815 searchedPark = false;
1816 if (parkSearchResult == park.name) {
1817 searchedPark = true;
1818 }
1819 if (!searchedPark) {
1820 if (!parkExists || disableCgPoiLoading) {
1821 return;
1822 }
1823 }
1824 }
1825
1826 if (type == 2) {
1827 park = formatParkObject(park);
1828 }
1829 var id;
1830 if (park.hasOwnProperty('park_id')) {
1831 id = park.park_id;
1832 } else if (!park.hasOwnProperty('id')) {
1833 id = park.cenlat + "|" + park.cenlon;
1834 }
1835
1836 var marker_id = id + '-' + park.poitype_id;
1837
1838 tempMarkers[marker_id] = true;
1839 if (!arrMarkers.hasOwnProperty(marker_id)) {
1840 park.poiCat = PoiCat.BASIC;
1841 park.marker = createMarker(park, type, "");
1842 if (disableCgPoiLoading) {
1843 park.marker.setMap(null);
1844 }
1845 if (searchedPark == true) {
1846 park.marker.search = "yes";
1847 }
1848 arrMarkers[marker_id] = park.marker;
1849 } else {
1850 if (searchedPark == true) {
1851 arrMarkers[marker_id].search = "yes";
1852 }
1853 }
1854
1855 bounds.extend(new google.maps.LatLng(park.lat, park.lon));
1856 });
1857
1858 if (searchResult == true) {
1859 searchResult = false;
1860 if (highlightPoi && arrMarkers[highlightPoi]) {
1861 var park = arrMarkers[highlightPoi];
1862 park.setOpacity(1);
1863 var icon = park.getIcon();
1864 icon.size = new google.maps.Size(48, 56);
1865 delete(icon.scaledSize);
1866 park.setIcon(icon);
1867 }
1868 highlightPoi = 0;
1869 }
1870
1871 clearMarkers(tempMarkers);
1872
1873 if (setMapBound) {
1874 map.fitBounds(bounds);
1875 }
1876
1877 }
1878
1879 function revertOpacitySearch() {
1880 $.each(arrMarkers, function (key, arrMarker) {
1881 arrMarker.setOpacity(1);
1882 });
1883 }
1884
1885 function revertFullRouteMarkers() {
1886 if (showFullRoute == true) {
1887 $.each(arrMarkers, function (key, arrMarker) {
1888 arrMarker.setVisible(true);
1889 });
1890
1891 showFullRoute = false;
1892 }
1893 }
1894
1895 // Marker Cat 1=cluseter 2=detail 3=nonovernight 4=height clearence
1896 function createCustomLegMarker(poi, markerCat, imgName) {
1897 var strIcon, zIndex, markerPoiType;
1898
1899 var positionLat = poi.cenlat || poi.lat;
1900 var positionLon = poi.cenlon || poi.lon;
1901 var position = new google.maps.LatLng(positionLat, positionLon);
1902
1903 var mouseoutCallback = function () {
1904 if (loadingDetails) {
1905 return;
1906 }
1907
1908 pointerInMarker = false;
1909 setTimeout(function () {
1910 if (!pointerInMarker && !pointerInInfobox) {
1911 closeMarkerInfoBox();
1912 }
1913 }, 100);
1914 };
1915
1916 switch (markerCat) {
1917 case 1:
1918 //cluster
1919 strIcon = clusterImageName;
1920 var clickCallback = function (position) {
1921 updateMapCenter(position, _global.map.zoom.end);
1922 };
1923 mouseoutCallback = markerType = false;
1924 break;
1925 case 2:
1926 //cluster detail
1927 zIndex = 200001;
1928 strIcon = getMarkerImage(poi);
1929 break;
1930 case 3:
1931 // non over night
1932 zIndex = 200002;
1933 strIcon = getMarkerImage(poi);
1934 markerPoiType = 'noncg';
1935 break;
1936 case 4:
1937 // height clerance
1938 strIcon = markerImagePath + "/" + poi.imageName;
1939 markerPoiType = 'height';
1940 break;
1941 }
1942 var marker = createCustomMarker(poi, {
1943 markerIcon: strIcon,
1944 position: position,
1945 clickMouseOutHandler: mouseoutCallback,
1946 forceCreate: true
1947 });
1948
1949 if (markerPoiType) {
1950 marker.poiType = markerPoiType;
1951 }
1952
1953 if (searchResult) {
1954 marker.setOpacity(0.5);
1955 }
1956
1957 var marker_id = getMarkerId(poi);
1958 //arrMarkers[marker_id] = marker;
1959
1960 return marker;
1961 }
1962
1963 // Same as the method above, but for route markers
1964 function createMarker(poi, markerCat, imgName) {
1965 var strIcon = "";
1966 var markerPos;
1967 var id;
1968 var marker = new google.maps.Marker({
1969 map: map,
1970 optimized: true
1971 });
1972 switch (markerCat) {
1973 case 1:
1974 //cluster
1975 markerPos = new google.maps.LatLng(poi.cenlat, poi.cenlon);
1976 marker.setPosition(markerPos);
1977 strIcon = clusterImageName;
1978 google.maps.event.addListener(marker, "click", function () {
1979 updateMapCenter(markerPos, _global.map.zoom.end);
1980 });
1981 id = poi.cenlat + "|" + poi.cenlon;
1982 break;
1983 case 2:
1984 //cluster details
1985 markerPos = new google.maps.LatLng(poi.lat, poi.lon);
1986 marker.setPosition(markerPos);
1987 marker.setZIndex(200001);
1988 strIcon = getMarkerImage(poi);
1989 addMarkerEvent(poi, marker, "mouseover");
1990 addMarkerEvent(poi, marker, "click");
1991 attachEventTryHideInfoBox(marker);
1992 id = poi.id;
1993 break;
1994 case 3:
1995 // non over night
1996 markerPos = new google.maps.LatLng(poi.lat, poi.lon);
1997 marker.setPosition(markerPos);
1998 marker.setZIndex(200002);
1999 strIcon = getMarkerImage(poi);
2000 addMarkerEvent(poi, marker, "mouseover");
2001 addMarkerEvent(poi, marker, "click");
2002 attachEventTryHideInfoBox(marker);
2003 marker.poiType = 'noncg';
2004 marker.overrides = poi.overrides;
2005 marker.propane = poi.propane;
2006 marker.dump = poi.dump;
2007 id = poi.id;
2008 break;
2009 case 4:
2010 // height clearance
2011 markerPos = new google.maps.LatLng(poi.lat, poi.lon);
2012 marker.setPosition(markerPos);
2013 strIcon = markerImagePath + "/" + poi.imageName;
2014 // addMarkerEvent(poi, marker, "mouseover");
2015 addMarkerEvent(poi, marker, "click");
2016 attachEventTryHideInfoBox(marker);
2017 marker.poiType = 'height';
2018 id = poi.id;
2019 break;
2020 }
2021
2022 if (strIcon.length > 1) {
2023 if (debug) console.log('SetIcon - ' + strIcon);
2024 marker.setIcon({
2025 url: strIcon,
2026 scaledSize: new google.maps.Size(24, 30)
2027 });
2028 } else {
2029 if (debug) console.log('No Icon Set');
2030 }
2031
2032 if (searchResult == true) {
2033 marker.setOpacity(0.5);
2034 }
2035
2036 var marker_id = id + '-' + poi.poitype_id;
2037 //arrMarkers[marker_id] = marker;
2038 if (debug) console.log('Marker ID - ' + marker_id);
2039 return marker;
2040 }
2041
2042 function attachEventTryHideInfoBox(marker) {
2043 google.maps.event.addListener(marker, 'mouseout', function () {
2044 // if (loadingDetails) {
2045 // return;
2046 // }
2047 pointerInMarker = false;
2048 setTimeout(function () {
2049 if (!pointerInMarker && !pointerInInfobox) {
2050 closeMarkerInfoBox();
2051 }
2052 }, 100);
2053 });
2054 }
2055
2056
2057 function addMarkerEvent(poi, marker, event) {
2058 if (debug) console.log('Add Marker Event - ' + poi.id);
2059 google.maps.event.addListener(marker, event, function () {
2060 if (event === 'mouseover') {
2061 pointerInMarker = true;
2062 }
2063 loadingDetails = true;
2064 poi.place_id = poi.poi_place_id;
2065 genPoiDetails(poi, PoiDetailsClickSource.MAP, function (response) {
2066 poi.rating = response.rating;
2067 poi.dump = response.dump;
2068 poi.propane = response.propane;
2069 poi.overnight = response.overnight;
2070 var url = response.url;
2071 url = formatUrl(url);
2072
2073 if (response.hours && response.hours.length > 0) {
2074 poi.opening_hours = {
2075 weekday_text: response.hours.split(',')
2076 };
2077 }
2078 poi.poi_type = response.poitype_title;
2079 getDistanceAndShowInInfoBox(poi);
2080 });
2081
2082
2083 if ($("input[name=click_to_view_info_on_map]:checked").val() == 0 && event === "mouseover") {} else {
2084 showMarkerInfoBox(poi, marker, poi.id === 0 || poi.id === undefined);
2085 }
2086 });
2087 }
2088
2089 var infoBoxDistanceTimeOut;
2090
2091 function getDistanceAndShowInInfoBox(poi) {
2092 // Don't need distance in low height clearances
2093 if (poi && poi.poi_type && poi.poi_type == "LC") {
2094 return;
2095 }
2096 if (curRoute && curRoute.routeLegs && curRoute.routeLegs.length > 0) {
2097 for (var i = 0; i < curRoute.routeLegs.length; i++) {
2098 if (
2099 (poi.id > 0 && curRoute.routeLegs[i].poi.id === poi.id) ||
2100 (!poi.id && curRoute.routeLegs[i].poi.place_id === poi.place_id)
2101 ) {
2102 return;
2103 }
2104 }
2105 var selectedPoi = getSelectedPoiStopOrDefault();
2106 if (!selectedPoi) {
2107 selectedPoi = curRoute.routeLegs.slice(-1).pop().poi;
2108 }
2109 var key = selectedPoi.lat + "-" + selectedPoi.lon + "-" + poi.lat + "-" + poi.lon;
2110 infoBox.id = poi.id;
2111 clearTimeout(infoBoxDistanceTimeOut);
2112 if (poiDistance[key]) {
2113 if (infoBox && infoBox.setDistance) {
2114 infoBox.setDistance(poiDistance[key]);
2115 }
2116 } else {
2117 if (!gettingMileDistance[poi.id]) {
2118 infoBoxDistanceTimeOut = setTimeout(function () {
2119 gettingMileDistance[poi.id] = true;
2120 var currentId = poi.id;
2121 gettingDistances = getDistanceBetweenPois(selectedPoi, poi)
2122 .then(function (distance) {
2123 poiDistance[key] = distance;
2124 if (currentId == infoBox.id) {
2125 if (infoBox && infoBox.setDistance) {
2126 infoBox.setDistance(distance);
2127 }
2128 }
2129 gettingMileDistance[poi.id] = false;
2130 });
2131 }, 500);
2132
2133 }
2134 }
2135 }
2136 }
2137
2138
2139 function getDistanceBetweenPois(originPoi, destinationPoi) {
2140 return fetchLocationMiles(originPoi, destinationPoi)
2141 .then(function (response) {
2142 if (!response || !response.data || !response.data.routes || !response.data.routes.length) {
2143 return;
2144 }
2145
2146 var route = response.data.routes[0];
2147 if (!route) {
2148 return;
2149 }
2150
2151 var legs = route.legs;
2152 if (!legs || !legs.length) {
2153 return;
2154 }
2155 var distance = legs[0].distance.text;
2156 return parseInt(distance.split('.')[0].replace(' mi', '').replace(',', ''));
2157 });
2158 }
2159
2160 function fetchLocationMiles(originPoi, destinationPoi) {
2161 var requestData = {
2162 prevlat: originPoi.lat,
2163 prevlon: originPoi.lon,
2164 lat: destinationPoi.lat,
2165 lon: destinationPoi.lon,
2166 avoidHighways: userProfile.avoid_major_highways === "1",
2167 avoidTolls: userProfile.avoid_tolls === "1",
2168 avoidFerries: userProfile.avoid_ferries === "1"
2169 };
2170 if (curRoute && curRoute.startDate) {
2171 var startDate = moment(curRoute.startDate);
2172 for (var i = 0; i < curRoute.routeLegs.length; i++) {
2173 if (originPoi.lat === curRoute.routeLegs[i].poi.lat && originPoi.lon === curRoute.routeLegs[i].poi.lon) {
2174 break;
2175 }
2176 if (curRoute.routeLegs[i].poi.nights && curRoute.routeLegs[i].poi.nights > 0) {
2177 startDate.add(parseInt(curRoute.routeLegs[i].poi.nights), 'days');
2178 }
2179 }
2180 if (startDate.isSameOrAfter(moment())) {
2181 requestData.departure_time = Math.round(startDate.utc().valueOf() / 1000);
2182 }
2183 }
2184 return $.ajax({
2185 type: "GET",
2186 ws: "fetch_location",
2187 dataType: "json",
2188 noblock: true,
2189 data: requestData,
2190 success: function success(res) {
2191 if (res && res.data && res.data.status && res.data.status == "OK") {
2192 if (res.used_google) {
2193 console.log("this one 3");
2194 MapsController.incrementRoutingDirectionsCounter();
2195 }
2196 return res;
2197 } else {
2198 return;
2199 }
2200 },
2201 error: function (x, y, z) {
2202 console.log(x, y, z);
2203 }
2204 });
2205 }
2206
2207 function updateMapCenter(position, zoom) {
2208 map.setCenter(position);
2209 if (zoom != null) map.setZoom(zoom);
2210 }
2211
2212 function updateMapCenter2(lat, lon, zoom) {
2213 var pos = new google.maps.LatLng(lat, lon);
2214 map.setCenter(pos);
2215 if (zoom != null) map.setZoom(zoom);
2216 }
2217 /* user start position */
2218 function setUserLoc() {
2219 var searchValue = $("#search-location").val();
2220 if (searchValue !== "" && curUserPoiMarker) {
2221 setUserLocationByAddress(searchValue, true);
2222 return;
2223 }
2224
2225 if (!navigator.geolocation) {
2226 setUserLocByGoogle();
2227 return;
2228 }
2229
2230 navigator.geolocation.getCurrentPosition(function (position) {
2231 var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
2232 var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
2233 MapsController.geocode({
2234 latLng: latLng
2235 }, function (results, status) {
2236 if (status !== google.maps.GeocoderStatus.OK || !results[1]) {
2237 setUserLocByGoogle();
2238 return;
2239 }
2240 AddToRoute({
2241 id: -1,
2242 lat: parseFloat(position.coords.latitude),
2243 lon: parseFloat(position.coords.longitude),
2244 point: latLng,
2245 address: results[1].formatted_address,
2246 name: results[1].formatted_address,
2247 status: true,
2248 nights: 0,
2249 imageName: customImageName(),
2250 cost: 0,
2251 poiCat: PoiCat.USER
2252 }, true, false, 0);
2253
2254
2255
2256 successUserLoc();
2257
2258 });
2259
2260 }, setUserLocByGoogle);
2261 }
2262
2263 function setUserLocByGoogle() {
2264 // If ClientLocation was filled in by the loader, use that info instead
2265 if (!google.loader || !google.loader.ClientLocation) {
2266 var searchValue = $("#search-location").val();
2267 if (!searchValue || searchValue.trim().length === 0) {
2268 setUserLocationFailMsg();
2269 $("body > main > aside").removeClass("visible");
2270 document.querySelector("#search-location").focus();
2271
2272 return;
2273 }
2274
2275 setUserLocationByAddress(searchValue, true);
2276 return;
2277 }
2278
2279
2280 successUserLoc();
2281 }
2282
2283 function getFormattedLocation() {
2284 if (google.loader.ClientLocation.address.country_code == "US" && google.loader.ClientLocation.address.region) {
2285 return google.loader.ClientLocation.address.city + ", " + google.loader.ClientLocation.address.region.toUpperCase();
2286 } else {
2287 return google.loader.ClientLocation.address.city + ", " + google.loader.ClientLocation.address.country_code;
2288 }
2289 }
2290
2291 function setUserLocationByPlace(place) {
2292 map.setCenter(place.geometry.location);
2293 curUserPoi = {
2294 id: -1,
2295 placeReference: place,
2296 lat: place.geometry.location.lat(),
2297 lon: place.geometry.location.lng(),
2298 point: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
2299 address: place.formatted_address,
2300 nights: 0,
2301 name: place.name,
2302 imageName: customImageName(),
2303 poiCat: PoiCat.USER,
2304 poi_type: place.types[0]
2305 };
2306 if (place.formatted_address) {
2307 curUserPoi.name = jQuery(place.formatted_address);
2308 }
2309 if (place.rating) {
2310 curUserPoi.rating = place.rating;
2311 }
2312
2313 if (place.photos) {
2314 curUserPoi.photos = place.photos;
2315 }
2316
2317 if (place.price_level) {
2318 curUserPoi.price_level = place.price_level;
2319 }
2320
2321 searchResult = true;
2322 $.each(arrMarkers, function (key, arrMarker) {
2323 arrMarker.setOpacity(0.5);
2324 });
2325
2326 revertFullRouteMarkers();
2327
2328 updateMapCenter(place.geometry.location, _global.numberMarkerZoom);
2329 setFindPointMarker(curUserPoi);
2330 if (curRoute) {
2331 genUserPoiDetails();
2332 }
2333
2334 }
2335
2336 function setUserLocationByAddress(address, setAsStartPoint) {
2337 callBlockUI();
2338 MapsController.geocode({
2339 address: address
2340 }, function (results, status) {
2341 if (status == google.maps.GeocoderStatus.OK) {
2342 callUnBlockUI();
2343
2344 map.setCenter(results[0].geometry.location);
2345 var lat = parseFloat(results[0].geometry.location.lat());
2346 var lon = parseFloat(results[0].geometry.location.lng());
2347 curUserPoi = {
2348 id: -1,
2349 lat: lat,
2350 lon: lon,
2351 point: new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()),
2352 address: results[0].formatted_address,
2353 nights: 0,
2354 name: address,
2355 imageName: customImageName(),
2356 poiCat: PoiCat.USER
2357 };
2358
2359 curBasicPoi = _global.utils.extend(curUserPoi);
2360
2361 searchResult = true;
2362 $.each(arrMarkers, function (key, arrMarker) {
2363 arrMarker.setOpacity(0.5);
2364 });
2365
2366 revertFullRouteMarkers();
2367
2368 if (setAsStartPoint) {
2369 successUserLoc();
2370 } else {
2371 updateMapCenter(new google.maps.LatLng(lat, lon), _global.numberMarkerZoom);
2372 setFindPointMarker(curUserPoi);
2373 if (curRoute) {
2374 genUserPoiDetails();
2375 }
2376 }
2377 } else {
2378 callUnBlockUI();
2379 alert(_global.msg.invalidLoc.replace(/~msg1~/g, address));
2380 }
2381 });
2382 }
2383
2384 function setUserLocationByLocation(data, setAsStartPoint) {
2385 map.setCenter(new google.maps.LatLng(data.lat, data.lon));
2386 curUserPoi = {
2387 id: -1,
2388 lat: data.lat,
2389 lon: data.lon,
2390 point: new google.maps.LatLng(data.lat, data.lon),
2391 address: data.address,
2392 nights: 0,
2393 name: data.name,
2394 imageName: customImageName(),
2395 poiCat: PoiCat.USER
2396 };
2397
2398 searchResult = true;
2399
2400 $.each(arrMarkers, function (key, arrMarker) {
2401 arrMarker.setOpacity(0.5);
2402 });
2403
2404 revertFullRouteMarkers();
2405
2406 if (setAsStartPoint) {
2407 successUserLoc();
2408 } else {
2409 updateMapCenter(new google.maps.LatLng(data.lat, data.lon), _global.numberMarkerZoom);
2410 setFindPointMarker(curUserPoi);
2411 if (curRoute) {
2412 genUserPoiDetails();
2413 }
2414 }
2415 }
2416
2417 function setUserLocationFailMsg() {
2418 alert(_global.msg.notGetCurrLoc);
2419 }
2420
2421 function setUserLocationMapFailMsg() {
2422 alert(_global.msg.notGetCurrLocMap);
2423 }
2424
2425 function setFindPointMarker(uPoi) {
2426 if (debug) console.log('Set Find Point Marker - ' + uPoi.id);
2427 var latlon = new google.maps.LatLng(uPoi.lat, uPoi.lon);
2428 if (curUserPoiMarker) curUserPoiMarker.setMap(null);
2429
2430 var icon = {
2431 url: uPoi.imageName,
2432 scaledSize: new google.maps.Size(40, 48)
2433 };
2434
2435 curUserPoiMarker = new google.maps.Marker({
2436 map: map,
2437 position: latlon,
2438 icon: icon,
2439 scaledSize: new google.maps.Size(24, 30),
2440 zIndex: 100010
2441 });
2442 addMarkerEvent(uPoi, curUserPoiMarker, "mouseover");
2443 addMarkerEvent(uPoi, curUserPoiMarker, "click");
2444 attachEventTryHideInfoBox(curUserPoiMarker);
2445 }
2446
2447 function clearFindPointMarker() {
2448 if (curUserPoiMarker) {
2449 curUserPoiMarker.setMap(null);
2450 }
2451 }
2452
2453 function clearStartMarker() {
2454 // if (curRoute && curRoute.routelegs && curRoute.routeLegs[0] && curRoute.routeLegs[0]..marker) {
2455 // startPositionInfo.marker.setMap(null);
2456 // }
2457 }
2458
2459 function closeMarkerInfoBox() {
2460 clearTimeout(infoBoxDistanceTimeOut);
2461 if (infoBox) {
2462 infoBox.close();
2463 }
2464 }
2465
2466 function getMarker(poi, legMarker) {
2467 if (debug) console.log('Get Marker - ' + poi.name);
2468 legMarker = legMarker || false; //If this marker is part of the current trip
2469
2470 var marker = null;
2471 var markerId = getMarkerId(poi);
2472 if (debug) console.log('Marker ID - ' + markerId);
2473 if (arrMarkers[markerId]) {
2474 if (debug) console.log('Returning Cached Marker');
2475 return arrMarkers[markerId];
2476 }
2477
2478 if (legMarker) {
2479 marker = createCustomMarker(poi);
2480 } else {
2481 if (debug) console.log('Create Non Loeg Marker');
2482 var latlon = new google.maps.LatLng(poi.lat, poi.lon);
2483 marker = new google.maps.Marker({
2484 map: map,
2485 position: latlon,
2486 icon: getMarkerIcon(poi),
2487 zIndex: 100001
2488 });
2489 addMarkerEvent(poi, marker, "mouseover");
2490 addMarkerEvent(poi, marker, "click");
2491 }
2492
2493 arrMarkers[markerId] = marker;
2494
2495 return marker;
2496 }
2497
2498
2499 // will need to take this apart to build our route markers.
2500 function createCustomMarker(poi, overrides) {
2501 var markerId = getMarkerId(poi);
2502 if (debug) console.log('Create Custom Marker - ' + poi.name + ' (Marker ID: ' + markerId + ')');
2503
2504 if ((!overrides || !overrides.forceCreate) && arrMarkers && arrMarkers[markerId]) {
2505 if (debug) console.log('Returned Cached Marker');
2506 return arrMarkers[markerId];
2507 }
2508
2509 var myLatlng = new google.maps.LatLng(poi.lat, poi.lon);
2510 var markerIcon = getMarkerIcon(poi);
2511
2512 //NEW
2513 var marker;
2514 // User image, no custom place image and missing image path, fix it.
2515 // TODO: Simplify all of this! Why are there so many variants?!
2516 marker = new google.maps.Marker({
2517 map: map,
2518 optimized: true
2519 });
2520 markerPos = new google.maps.LatLng(poi.cenlat, poi.cenlon);
2521 marker.setPosition(myLatlng);
2522
2523 marker.setIcon({
2524 url: markerIcon.url,
2525 scaledSize: new google.maps.Size(24, 30)
2526 });
2527 if (debug) console.log('Marker ID - ' + markerId);
2528 addMarkerEvent(poi, marker, "mouseover");
2529 addMarkerEvent(poi, marker, "click");
2530 attachEventTryHideInfoBox(marker);
2531 //NEW
2532
2533
2534 //ENDNEW
2535
2536 var customCallback = function (marker, event) {
2537 // if (event.type === 'mouseover') {
2538 // debug && console.log("in2");
2539 // pointerInMarker = true;
2540 // }
2541 //
2542 // loadingDetails = true;
2543 // genPoiDetails(poi, PoiDetailsClickSource.MAP);
2544 //
2545 // if($("input[name=click_to_view_info_on_map]:checked").val() == 0 && event.type ==="mouseover"){
2546 //
2547 //
2548 // }
2549 // else{
2550 // showMarkerInfoBox(poi, marker, poi.id === 0 || poi.id === undefined);
2551 // }
2552 // if (poi.distance && infoBox && infoBox.setDistance) {
2553 // infoBox.setDistance(Math.floor(poi.distance));
2554 // }
2555 };
2556
2557 var options = {
2558 marker_id: markerId,
2559 markerIcon: markerIcon,
2560 clickHandler: customCallback,
2561 clickMouseOverHandler: customCallback
2562 };
2563
2564 if (overrides && overrides.forceCreate) {
2565 delete overrides.forceCreate;
2566 }
2567
2568 if (overrides) {
2569 options = $.extend(options, overrides);
2570 }
2571
2572 var customMarker = new CustomMarker(
2573 myLatlng,
2574 map,
2575 options
2576 );
2577 // addMarkerEvent(poi, marker, "mouseover");
2578 // addMarkerEvent(poi, marker, "click");
2579 // attachEventTryHideInfoBox(marker);
2580 customMarker.backgroundMarker = marker;
2581 return customMarker;
2582 }
2583
2584 function successUserLoc() {
2585 if (debug) console.log('Success User Location');
2586 updateMapCenter(new google.maps.LatLng(curRoute.routeLegs[0].start.lat(), curRoute.routeLegs[0].start.lng()));
2587 map.setZoom(11);
2588 genRouteListing();
2589 SaveTrip(function () {
2590 loadSelectedTrip($("#hdnTripId").val());
2591
2592 $('#new-trip-modal').modal('hide');
2593 });
2594 }
2595
2596
2597 function addUserPoi() {
2598 var nights = parseInt($(".txt-add-poi-nights").val(), 10),
2599 poi = {
2600 lat: curUserPoi.lat,
2601 lon: curUserPoi.lon,
2602 name: curUserPoi.name,
2603 id: -1,
2604 nights: !isNaN(nights) ? nights : 0,
2605 comments: $(".poi-details-poi-comment").val() || "",
2606 poiCat: PoiCat.USER,
2607 imageName: curUserPoi.imageName,
2608 waypoints: [],
2609 cost: null
2610 };
2611 // added starting point poi to collection
2612 callBlockUI();
2613 if (debug) console.log("adr 5");
2614 AddToRoute(poi, true, function () {
2615 callUnBlockUI();
2616 rvTripHelper.drawDriveCircle(poi);
2617 rvTripLC.showOverlayLC();
2618 });
2619 }
2620 // wapoints: route waypoints.[optional]
2621 function getDirectionsServiceRequest(origin, destination, waypoints) {
2622 var drivingOptions = null;
2623 if (curRoute && curRoute.startDate && curRoute.startDate.valueOf() > Date.now()) {
2624 drivingOptions = {
2625 departureTime: curRoute.startDate
2626 };
2627 }
2628 return _global.utils.extend({
2629 origin: origin,
2630 destination: destination,
2631 travelMode: google.maps.DirectionsTravelMode.DRIVING,
2632 avoidHighways: userProfile.avoid_major_highways === "1",
2633 avoidTolls: userProfile.avoid_tolls === "1",
2634 avoidFerries: userProfile.avoid_ferries === "1",
2635 drivingOptions: drivingOptions
2636 }, waypoints && waypoints.length > 0 ? {
2637 waypoints: dragRoute.LatlonsToGmapWaypoints(waypoints)
2638 } : {});
2639 }
2640 // result: dirrection request result. optional parameter
2641 // Binding directions_changed event
2642
2643 function getStrokeWeight() {
2644 var polyWeight;
2645 var mapZoom = map.getZoom();
2646 if (mapZoom <= 4) {
2647 polyWeight = 3;
2648 } else if (mapZoom <= 8) {
2649 polyWeight = 4;
2650 } else if (mapZoom <= 12) {
2651 polyWeight = 5;
2652 } else if (mapZoom <= 14) {
2653 polyWeight = 6;
2654 } else {
2655 polyWeight = 7;
2656 }
2657 return polyWeight;
2658 }
2659 var polyLineOpt = {
2660 strokeColor: _global.map.style.tripLineClr,
2661 strokeOpacity: _global.map.style.tripLineOpacity,
2662 strokeWeight: _global.map.style.tripLineStrokeWeight,
2663 polylineOptions: _global.map.style.tripLineClr
2664 };
2665
2666 var renderMarkerOption = {
2667 visible: false
2668 };
2669
2670 var renderOption = {
2671 preserveViewport: true,
2672 markerOptions: renderMarkerOption,
2673 polylineOptions: polyLineOpt
2674 };
2675
2676
2677 $(".btnTripPreferences, .btnTripPref").click(function () {
2678 SettingsModal.showModal();
2679 });
2680
2681 var plotZoom;
2682
2683 var invisLines = [];
2684
2685 function highlightRoute() {
2686 //disabling highlight route
2687 if (invisLines) {
2688 clearHighlightedRoute();
2689 }
2690 invisLines = [];
2691 var enableClick = false;
2692 if (curRoute !== null) {
2693 if (curRoute.dragEnable) {
2694 return;
2695 }
2696 for (var i = 0; i <= curRoute.routeLegs.length; i++) {
2697
2698 if (typeof curRoute.routeLegs[i] !== "undefined" && curRoute.routeLegs[i].directionsDisplay !== null) {
2699 var routeLeg = curRoute.routeLegs[i].directionsDisplay.directions.routes[0].legs;
2700 var legPath = [];
2701 for (j = 0; j < routeLeg.length; j++) {
2702 var legSteps = routeLeg[j].steps;
2703 for (k = 0; k < legSteps.length; k++) {
2704 var toAddToPath = legSteps[k].path;
2705 legPath = legPath.concat(toAddToPath);
2706 }
2707 }
2708 var invisPolyline = new google.maps.Polyline({
2709 path: legPath,
2710 strokeColor: '#FF0000',
2711 strokeOpacity: 0,
2712 strokeWeight: 15,
2713 zIndex: 2,
2714 map: map
2715 });
2716 invisLines.push(invisPolyline);
2717 }
2718 }
2719 }
2720 invisLines.forEach(function (line) {
2721 google.maps.event.addListener(line, "click", function () {
2722 if (!enableClick) {
2723 this.setOptions({
2724 strokeOpacity: 0.3
2725 });
2726 enableClick = true;
2727 } else if (enableClick && this.strokeOpacity == 0) {
2728 invisLines.forEach(function (line) {
2729 line.setOptions({
2730 strokeOpacity: 0
2731 });
2732 });
2733 this.setOptions({
2734 strokeOpacity: 0.3
2735 });
2736 } else {
2737 this.setOptions({
2738 strokeOpacity: 0
2739 });
2740 enableClick = false;
2741 }
2742 });
2743
2744 google.maps.event.addListener(line, "mouseover", function () {
2745 if (!enableClick) {
2746 this.setOptions({
2747 strokeOpacity: 0.3
2748 });
2749 }
2750 });
2751 google.maps.event.addListener(line, "mouseout", function () {
2752 if (!enableClick) {
2753 this.setOptions({
2754 strokeOpacity: 0
2755 });
2756 }
2757 });
2758 });
2759 }
2760
2761 function clearHighlightedRoute() {
2762 invisLines.forEach(function (line) {
2763 line.setMap(null);
2764 });
2765 }
2766
2767 function getLegPoiMarker(poi, first) {
2768 var marker = null;
2769 switch (poi.poiCat) {
2770 case PoiCat.USER:
2771 marker = createCustomLegMarker(poi, markerLegType, "");
2772 marker.setMap(map);
2773 break;
2774 case PoiCat.BASIC:
2775 var markerLegType = poi.poitype_id != _global.poiTypeCampground ? 3 : 2;
2776
2777 // for (var m in arrMarkers) {
2778 // var marker_id = getMarkerId(poi);
2779 // if (m == marker_id) {
2780 // // Override map marker with custom one
2781 // var markerOverride = createCustomLegMarker(poi, markerLegType, "");
2782 // test = createMarker(poi, false)
2783 // console.log(test);
2784 // markerOverride.normalPoi = test;
2785
2786 // if (poi.marker) {
2787 // poi.marker.setMap(null);
2788 // }
2789 // poi.marker = markerOverride;
2790 // markerOverride.setMap(map);
2791 // return markerOverride;
2792 // }
2793 // }
2794 marker = createCustomLegMarker(poi, markerLegType, "");
2795 marker.setMap(map);
2796
2797 break;
2798 default:
2799 marker = null;
2800 break;
2801 }
2802
2803 if (poi.poiCat === undefined && poi.marker) {
2804 return getMarker(poi, true);
2805 }
2806
2807 if (poi.poiCat === undefined && poi.isCustomSearchedPlace) {
2808 return getMarker(poi, true);
2809 }
2810
2811 return marker;
2812 }
2813
2814 function clearAfterAddToRoute() {
2815 closeMarkerInfoBox();
2816 curSelItemIndex = null;
2817 tbT.panelHide(); // hide turn by turn pannel.
2818 fuelCalculator.overlayFuelWarning();
2819 fuelCalculator.recalculateAllFuelRemaining();
2820 }
2821
2822 function typecastRoutes(routes) {
2823
2824 $.each(routes, function (key, route) {
2825 routes[key].bounds = asBounds(route.bounds);
2826 // I don't think `overview_path` is used but it exists on the
2827 // response of DirectionsService.route()
2828 routes[key].overview_path = asPath(route.overview_polyline);
2829 routes[key].overview_polyline = routes[key].overview_polyline.points;
2830
2831 $.each(route.legs, function (key2, leg) {
2832 routes[key].legs[key2].start_location = asLatLng(leg.start_location);
2833 routes[key].legs[key2].end_location = asLatLng(leg.end_location);
2834
2835 $.each(leg.steps, function (key3, step) {
2836 routes[key].legs[key2].steps[key3].start_location = asLatLng(step.start_location);
2837 routes[key].legs[key2].steps[key3].end_location = asLatLng(step.end_location);
2838 routes[key].legs[key2].steps[key3].path = asPath(step.polyline);
2839 });
2840 });
2841 });
2842
2843 return routes;
2844 }
2845
2846 function asBounds(boundsObject) {
2847 return new google.maps.LatLngBounds(asLatLng(boundsObject.southwest),
2848 asLatLng(boundsObject.northeast));
2849 }
2850
2851 function asLatLng(latLngObject) {
2852 return new google.maps.LatLng(latLngObject.lat, latLngObject.lng);
2853 }
2854
2855 function asPath(encodedPolyObject) {
2856 return google.maps.geometry.encoding.decodePath(encodedPolyObject.points);
2857 }
2858
2859 /* dirrectory service
2860 call during add new trip and also during redraw route
2861 */
2862 function AddToRoute(poi, needToSave, callback, index) {
2863 if (curRoute.routeLegs.length > 0) {
2864 if (!index) {
2865 index = curRoute.routeLegs.length;
2866 }
2867
2868 (function () {
2869 var prevPoi = curRoute.routeLegs[index - 1].poi,
2870 start = new google.maps.LatLng(prevPoi.lat, prevPoi.lon),
2871 end = new google.maps.LatLng(poi.lat, poi.lon);
2872
2873 var request = getDirectionsServiceRequest(start, end, poi.waypoints);
2874 var tempID;
2875 if (poi.park_id) {
2876 tempID = poi.park_id;
2877 } else {
2878 if (poi.id) {
2879 tempID = poi.park_id;
2880 } else {
2881 tempID = -324;
2882 }
2883
2884 }
2885 if (debug) console.log(poi.waypoints);
2886 if (poi.name.selector) {
2887 poi.name = poi.name.selector;
2888 }
2889 var requestData = {
2890 city: poi.city,
2891 name: poi.name,
2892 poiId: tempID,
2893 prevlat: prevPoi.lat,
2894 prevlon: prevPoi.lon,
2895 lat: poi.lat,
2896 lon: poi.lon,
2897 avoidHighways: userProfile.avoid_major_highways === "1",
2898 avoidTolls: userProfile.avoid_tolls === "1",
2899 avoidFerries: userProfile.avoid_ferries === "1",
2900 waypoints: poi.waypoints
2901 };
2902
2903 if (curRoute && curRoute.startDate) {
2904 // calculate start date of poi
2905 var startDate = moment(curRoute.startDate);
2906 for (var i = 0; i < curRoute.routeLegs.length; i++) {
2907 if (poi.lat === curRoute.routeLegs[i].poi.lat && poi.lon === curRoute.routeLegs[i].poi.lon) {
2908 break;
2909 }
2910 if (curRoute.routeLegs[i].poi.nights && curRoute.routeLegs[i].poi.nights > 0) {
2911 startDate.add(parseInt(curRoute.routeLegs[i].poi.nights), 'days');
2912 }
2913 }
2914 if (startDate.isSameOrAfter(moment())) {
2915 requestData.departure_time = Math.round(startDate.utc().valueOf() / 1000);
2916 }
2917 }
2918 progressBarService.start();
2919 $.ajax({
2920 type: "GET",
2921 ws: "fetch_location",
2922 dataType: "json",
2923 data: requestData,
2924 success: function success(res) {
2925 if (debug) console.log(res);
2926 if (!handleAjaxError(res) || !res.data) {
2927 if (tempID == -324) {
2928 // Capture why this happened so we can debug
2929 if (RavenHelper.isDefined()) {
2930
2931 if (res.errMsg) {
2932 requestData.errMsg = res.errMsg;
2933 }
2934
2935 if (res.status) {
2936 requestData.status = res.status;
2937 }
2938
2939 RavenHelper.setCurrentUserContext();
2940 Raven.captureMessage('Error retriving fetch_location data', {
2941 extra: requestData
2942 });
2943 }
2944 alert('Unroutable custom stop, please retry closer to a road.');
2945 } else {
2946 alert('Unroutable POI detected, this is our fault, the development team has been notified.');
2947 }
2948
2949 if (needToSave) {
2950 SaveTrip();
2951 } else {
2952 progressBarService.stop();
2953 }
2954 // Don't redraw route on add stop
2955 //redrawPoiRoute(false);
2956 genRouteListing();
2957
2958 clearAfterAddToRoute();
2959 callback(true);
2960
2961 return;
2962 }
2963
2964 if (res.used_google) {
2965 console.log("this one");
2966 MapsController.incrementRoutingDirectionsCounter();
2967 }
2968
2969 var directions = {
2970 geocoded_waypoints: res.data.geocoded_waypoints,
2971 routes: typecastRoutes(res.data.routes),
2972 request: request
2973 };
2974 if (debug) console.log(directions);
2975 var directionsToDisplay = MapsController.getDirectionsRenderer(directions);
2976 if (debug) console.log(directionsToDisplay);
2977 poi.distance = rvTripHelper.routeDistance(res.data);
2978 poi.time = rvTripHelper.routeTime(res.data);
2979
2980 if (_global.utils.nullOrUndefined(poi.cost)) {
2981 // during new trip cost properties is undefined.
2982 // plz note that for getStopCpg(curRoute.routeLegs.length-1) curRoute.routeLegs.length refering current
2983 // stop index. Current poi is not yet added, acutally it is reffering prev poi.
2984 poi.cost = routeCostHelper.routeCost(poi.distance, parseInt(poi.nights), poi.poiCat, parseFloat(userProfile.cpg), parseInt(userProfile.camping), parseInt(userProfile.meals), parseInt(userProfile.misc));
2985 poi.fuelCpg = parseFloat(userProfile.cpg);
2986 } else {
2987 if (poi.cost === -1) {
2988 // poi cost setted to -1 for old trip.
2989 poi.cost = parseInt(routeCostHelper.getStopFuelCost(poi.distance)) + ( // fuel cost
2990 parseInt(poi.costCamping) + parseInt(poi.costMeals) + parseInt(poi.costMisc)); // usefull for old custom cost
2991 }
2992 }
2993
2994 rvTripHelper.setPoiExtendedProperties(poi);
2995
2996
2997 poi.marker = getLegPoiMarker(poi);
2998
2999
3000 if (curUserPoiMarker) {
3001 curUserPoiMarker.setMap(null);
3002 }
3003
3004 var newPoi = $.extend(true, {}, poi); //for both cg and noncg poi but not user poi
3005 curRoute.routeLegs.splice(index, 0, {
3006 poi: newPoi,
3007 start: start,
3008 end: end,
3009 directionsDisplay: directionsToDisplay,
3010 directionsServiceResult: res.data
3011 });
3012 //newPoi.marker = getLegPoiMarker(poi);
3013 newPoi.marker.inRoute = true;
3014 if (!fetchRouteRequest) {
3015 generateFetchRouteRequest([]);
3016 }
3017
3018 if (fetchRouteRequest && fetchRouteRequest.pois) {
3019 fetchRouteRequest.pois.splice(index, 0, {
3020 lat: newPoi.lat,
3021 lon: newPoi.lon,
3022 prevlat: prevPoi.lat,
3023 prevlon: prevPoi.lon,
3024 waypoints: newPoi.waypoints
3025 });
3026
3027 if (fetchRouteRequest.pois[index + 1]) {
3028 fetchRouteRequest.pois[index + 1].prevlat = newPoi.lat;
3029 fetchRouteRequest.pois[index + 1].prevlon = newPoi.lon;
3030 }
3031 }
3032 recalculateDates(curRoute);
3033
3034 if (needToSave) {
3035 SaveTrip();
3036 } else {
3037 progressBarService.stop();
3038 }
3039 // Don't redraw route on add stop
3040 //redrawPoiRoute(false);
3041 genRouteListing();
3042
3043 clearAfterAddToRoute();
3044 highlightRoute();
3045 callback(true);
3046
3047 },
3048 error: function error(x, y, z) {
3049 console.log(x);
3050 console.log(y);
3051 console.log(z);
3052 alert("FAILED TO LOAD");
3053 }
3054 });
3055
3056 })();
3057 } else {
3058 poi.distance = 0;
3059 poi.time = 0;
3060 end = new google.maps.LatLng(poi.lat, poi.lon);
3061 curRoute.routeLegs.splice(index, 0, {
3062 poi: poi,
3063 start: new google.maps.LatLng(poi.lat, poi.lon),
3064 end: new google.maps.LatLng(poi.lat, poi.lon),
3065 directionsDisplay: null,
3066 });
3067 poi.marker = getLegPoiMarker(poi);
3068 poi.marker.setMap(map);
3069 poi.marker.first = true;
3070 genRouteListing();
3071 //SaveTrip();
3072 callUnBlockUI();
3073 }
3074 }
3075
3076 $("#add-to-trip-form-custom, #add-to-trip-form-poi-detailed").on("submit", function (event) {
3077 event.preventDefault();
3078 var $form = $(this);
3079 var formData = $form.serializeArray().reduce(function (o, a) {
3080 return Object.assign(o, _defineProperty({}, a.name, a.value));
3081 }, Object.create(null));
3082 var _self = this;
3083 if (_self.debug) console.log("AddToTripComponent *** Submit Function Called ***");
3084 closeElevation();
3085 Object.assign(formData, {
3086 nights: $form.find(".txt-add-poi-nights").val() || 0,
3087 comment: $form.find(".poi-details-poi-comment").val()
3088 });
3089
3090 if ($form.find('#lat-custom').length > 0 && $form.find('#lon-custom').length > 0) {
3091 formData.lat = parseFloat($form.find('#lat-custom').val());
3092 formData.lon = parseFloat($form.find('#lon-custom').val());
3093 }
3094
3095 if ($form.find('#poi-type-custom').length) {
3096 formData.poi_type_image = $form.find('#poi-type-custom').val();
3097 }
3098
3099 if ($form.find('#street-custom').length) {
3100 formData.street = $form.find('#street-custom').val();
3101 }
3102 if (formData.follow === "-1") {
3103 btnAddToTripEndClick(formData.poiId, formData.poiCg, formData.poiCat, formData);
3104 } else {
3105 if (curRoute) {
3106 if (curRoute.routeLegs) {
3107 if (curRoute.routeLegs.length - 1 == formData.follow) {
3108 btnAddToTripEndClick(formData.poiId, formData.poiCg, formData.poiCat, formData);
3109 } else {
3110 AddToTripInDefineIndex(formData.poiId, formData.poiCg, formData.poiCat, parseInt(formData.follow, 10) + 1, formData);
3111 }
3112 } else {
3113 AddToTripInDefineIndex(formData.poiId, formData.poiCg, formData.poiCat, parseInt(formData.follow, 10) + 1, formData);
3114 }
3115 } else {
3116 AddToTripInDefineIndex(formData.poiId, formData.poiCg, formData.poiCat, parseInt(formData.follow, 10) + 1, formData);
3117 }
3118 }
3119 $("#marker-info-modal, #custom-poi-info-modal").modal("hide");
3120
3121 // Hide the custom poi details form
3122 PoiMarkerModal.hideModal();
3123
3124 // Reset form
3125 $(".txt-add-poi-nights").val(null);
3126 $(".txt-add-poi-camping-total").val(null);
3127 $(".poi-details-poi-comment").val(null);
3128 var followTrip = $('.follow-trip');
3129 followTrip.val(followTrip.children().length - 1);
3130 $("[name=stop][value=end]").attr("checked", true);
3131 });
3132
3133 function clearRoutesOverlays() {
3134 if (curRoute && curRoute.routeLegs) {
3135 curRoute.routeLegs.forEach(function (routeLeg) {
3136 if (routeLeg.directionsDisplay) {
3137 routeLeg.directionsDisplay.setMap(null);
3138 }
3139 if (routeLeg.poi.marker) {
3140 routeLeg.poi.marker.setMap(null);
3141 }
3142 });
3143 clearHighlightedRoute();
3144 }
3145 }
3146
3147 function getSelectedPoiStopOrDefault() {
3148 if (!curRoute || !curRoute.routeLegs || !curRoute.routeLegs.length) {
3149 return;
3150 }
3151 var routeList = $('#routeList');
3152 var index = routeList.find('tr[data-index] .stop').length - 1;
3153 var selectedRow = routeList.find('tr.selected');
3154 if (selectedRow.length) {
3155 index = RouteTable.getCurrentlySelected();
3156 }
3157 if (index < 0) {
3158 return;
3159 }
3160 return curRoute.routeLegs[index].poi;
3161 }
3162
3163 function genRouteListing() {
3164 if (curRoute) {
3165 RouteTable.generateTable();
3166
3167 /* Do calculations but exit here if there is no sidebar */
3168 if (routeList.length == 0) {
3169 $("div.totDistance").text(RouteTable.getTotalDistance());
3170 return;
3171 }
3172
3173 // This should be moved to the table as it is part of it.
3174 if (curRoute.routeLegs.length > 1) {
3175 var returnToStart = {
3176 button: document.createElement("button"),
3177 icon: document.createElement("i"),
3178 text: document.createTextNode(" Round Trip Options"),
3179 row: document.createElement("tr")
3180 };
3181 returnToStart.button.classList.add("btn", "btn-rv-outline-gray", "btn-sm");
3182 returnToStart.button.addEventListener("click", function () {
3183 createTripOptionsModal();
3184 });
3185 returnToStart.icon.classList.add("fa", "fa-flag-checkered");
3186 returnToStart.button.appendChild(returnToStart.icon);
3187 returnToStart.button.appendChild(returnToStart.text);
3188 returnToStart.row.innerHTML = $("#routeList").find("tr[data-index]:not([data-index='-1']):first-child td").clone().empty().toArray().reduce(function (h, e) {
3189 return h + e.outerHTML;
3190 }, "");
3191
3192 returnToStart.row.dataset.index = "-1";
3193 returnToStart.row.firstChild.appendChild(returnToStart.button);
3194 routeList.append(returnToStart.row);
3195
3196 $('#routeList').find('tr[data-index=-1] td:first-child').attr('colspan', 10);
3197 $('#routeList').find('tr[data-index=-1] td:not(:first-child)').remove();
3198 }
3199 var rvFoot = $('.rv-trip tfoot');
3200 if (rvFoot.hasClass("hidden")) {
3201 rvFoot.removeClass("hidden");
3202 }
3203
3204
3205 rvTripHelper.adjustWidthRvTripTable();
3206
3207 $("#trip-options").removeClass("hidden");
3208 }
3209
3210 //This will be added to the sidebar class, not the route-table class
3211 // if there is only 1 stop then make sure to not let the elevation appear
3212 if (curRoute.routeLegs.length <= 1) {
3213 $(".btn-elevation").addClass("disabled");
3214 $("#elevationBtn").addClass("disabled");
3215 } else {
3216 $(".btn-elevation").removeClass("disabled");
3217 if ($('#sidebar').hasClass('desk-visible')) {
3218 //adjust highcharts btns
3219 $("#elevationBtn").removeClass("disabled");
3220 var newLeft = $("#sidebar").css("width");
3221 $('#desktopChartbtns').animate({
3222 'margin-Left': newLeft
3223 }, 100);
3224 notificationService.addMargin();
3225 }
3226
3227 $(".grade-button-container, #showGradeBtn").removeClass("disabled");
3228
3229
3230 }
3231 }
3232
3233
3234 function createTripOptionsModal() {
3235 RoundTripModal.showModal();
3236 }
3237
3238
3239 $(window).resize(function () {
3240 rvTripHelper.adjustWidthRvTripTable();
3241 closeElevation();
3242 });
3243
3244 var tripOptions = $("#trip-options");
3245 tripOptions.on("click", function (event) {
3246 wrenchPushed = 2;
3247 closeElevation();
3248 $(".trip-popover").remove();
3249 event.preventDefault();
3250 event.stopPropagation();
3251 TripOptionsPopover.open();
3252 });
3253
3254
3255 function getFormattedTrip(rptRoute) {
3256 var tempRoute = {
3257 name: rptRoute.name,
3258 startDate: _global.getReportDateFull(rptRoute.startDate),
3259 userName: userProfile.name,
3260 notes: rptRoute.notes,
3261 pois: []
3262 };
3263 var tripDate = {};
3264 var totDistance = 0;
3265 var totNights = 0;
3266 var totCost = 0;
3267 rptRoute.routeLegs.forEach(function (leg, index) {
3268 if (index == 0) {
3269 tripDate = new Date(rptRoute.startDate.getTime());
3270 }
3271 var rptPoi = {};
3272 rptPoi.imageName = getMarkerImage(leg.poi);
3273 rptPoi.name = leg.poi.name;
3274 rptPoi.distance = leg.poi.distance;
3275 rptPoi.cost = leg.poi.cost;
3276 rptPoi.costCamping = leg.poi.costCamping ? leg.poi.costCamping : 0;
3277 rptPoi.costMeals = leg.poi.costMeals ? leg.poi.costMeals : 0;
3278 rptPoi.costMisc = leg.poi.costMisc ? leg.poi.costMisc : 0;
3279 //routeCostHelper.getStopFuelCost(leg.poi.distance); does not work but seems like better option
3280 //Gives in correct fuel cost which does not add up to total
3281 rptPoi.costFuel = leg.poi.fuelCpg * fuelCalculator.getFuelUsed(leg.poi);
3282 rptPoi.nights = parseInt(leg.poi.nights, 10);
3283 rptPoi.address = rvTripHelper.getStopAddress(leg.poi);
3284 rptPoi.phone = leg.poi.phone ? leg.poi.phone : "";
3285 rptPoi.email = leg.poi.email ? leg.poi.email : "";
3286 rptPoi.url = leg.poi.url ? leg.poi.url : "";
3287 rptPoi.features = leg.poi.features;
3288 rptPoi.site_info = leg.poi.site_info;
3289 rptPoi.comments = leg.poi.comments;
3290 rptPoi.reservationNum = leg.poi.reservationNum;
3291 rptPoi.lat = leg.poi.lat.toFixed(5);
3292 rptPoi.lon = leg.poi.lon.toFixed(5);
3293 rptPoi.poiCat = leg.poi.poiCat;
3294 rptPoi.waypoints = leg.poi.waypoints;
3295 totCost += rptPoi.cost;
3296 totNights += rptPoi.nights;
3297 totDistance += rptPoi.distance;
3298 rptPoi.cumulativeDistance = _global.utils.round(totDistance, 1);
3299 var depDate = new Date(tripDate.getTime());
3300 depDate.setDate(depDate.getDate() + rptPoi.nights);
3301 rptPoi.arive = _global.getReportDateFull(tripDate);
3302 rptPoi.depart = _global.getReportDateFull(depDate);
3303 tempRoute.pois.push(rptPoi);
3304 tripDate.setDate(tripDate.getDate() + rptPoi.nights);
3305 });
3306 if (rptRoute.routeLegs.length > 0) {
3307 var summary = {};
3308 summary.miles = Math.floor(totDistance);
3309 summary.stops = rptRoute.routeLegs.length;
3310 summary.nights = totNights;
3311 summary.totalCost = totCost;
3312 summary.perDay = parseInt(totNights ? totCost / totNights : totCost, 10);
3313 tempRoute.summary = summary;
3314 }
3315 return tempRoute;
3316 }
3317
3318
3319 // converts all poi durations back to seconds
3320 function mappedDurations() {
3321 var durations = {};
3322 for (var i = 1; i < curRoute.routeLegs.length; i++) {
3323 var durationId = Math.floor(Math.abs(curRoute.routeLegs[i].poi.lat * 10000)).toString() +
3324 Math.floor(Math.abs(curRoute.routeLegs[i].poi.lon * 10000)).toString();
3325 if (debug) console.log(durationId);
3326 durations[durationId] = rvTripHelper.getDurationInMinutes(curRoute.routeLegs[i]);
3327 }
3328 if (debug) console.log(durations);
3329 return durations;
3330 }
3331
3332 //REMOVE THIS BEFORE PUSHING
3333 function getDurations() {
3334 for (var i = 0; i < curRoute.routeLegs.length; i++) {
3335 if (debug) console.log(rvTripHelper.getDurationInMinutes(curRoute.routeLegs[i]));
3336 }
3337 var userId = $("#trip_user_id").val();
3338 var routeId = $("#hdnTripId").val();
3339 if (debug) console.log(userId);
3340 if (debug) console.log(routeId);
3341 }
3342
3343
3344 var shareMap;
3345 var routeShareMarkers = [];
3346 var isConnected = false;
3347
3348 function sendFacebook() {
3349 callBlockUI();
3350 tbT.panelHide();
3351 TripOptionsPopover.close();
3352 PostFacebookModal.establishConnection();
3353 PostFacebookModal.shareFacebook();
3354
3355 callUnBlockUI();
3356 }
3357
3358 function fetchTripKey(trip_id) {
3359
3360 return $.ajax({
3361 url: "/app/ws/fetch_trip_image_url.php",
3362 dataType: 'json',
3363 type: "GET",
3364 data: {
3365 trip_id: trip_id
3366 },
3367 success: function success(res) {
3368 if (!handleAjaxError(res)) {
3369 return;
3370 }
3371 },
3372 error: function error(x, y, z) {
3373 $("#generate-screenshot").modal("hide");
3374 alert("Please Try Again : Failed to load trip");
3375 }
3376 });
3377 }
3378
3379 function fetchTripImageUrl(trip_id, key) {
3380
3381 return $.ajax({
3382 url: apiUrl + 'screenshot',
3383 noblock: false,
3384 dataType: 'json',
3385 headers: {
3386 Accept: 'application/x.rvparkreviews.v1+json'
3387 },
3388 type: "GET",
3389 timeout: 40000,
3390 data: {
3391 host: location.protocol + '//' + location.host + '/app/print.php',
3392 trip_id: trip_id,
3393 key: key
3394 },
3395 success: function success(res) {
3396 if (!handleAjaxError(res)) {
3397 return;
3398 }
3399 },
3400 error: function error() {
3401 $("#generate-screenshot").modal("hide");
3402 alert("Please Try Again : Failed to generate screenshot");
3403 }
3404 });
3405 }
3406 /* Appears to be duplicate of 2769 */
3407 /*
3408 function typecastRoutes(routes) {
3409 $.each(routes, function(key, route) {
3410 routes[key].bounds = asBounds(route.bounds);
3411 // I don't think `overview_path` is used but it exists on the
3412 // response of DirectionsService.route()
3413 routes[key].overview_path = asPath(route.overview_polyline);
3414 routes[key].overview_polyline = routes[key].overview_polyline.points;
3415
3416 $.each(route.legs, function (key2, leg) {
3417 routes[key].legs[key2].start_location = asLatLng(leg.start_location);
3418 routes[key].legs[key2].end_location = asLatLng(leg.end_location);
3419
3420 $.each(leg.steps, function (key3, step) {
3421 routes[key].legs[key2].steps[key3].start_location = asLatLng(step.start_location);
3422 routes[key].legs[key2].steps[key3].end_location = asLatLng(step.end_location);
3423 routes[key].legs[key2].steps[key3].path = asPath(step.polyline);
3424 });
3425 });
3426 });
3427
3428 return routes;
3429 }
3430
3431
3432 function asBounds(boundsObject){
3433 return new google.maps.LatLngBounds(asLatLng(boundsObject.southwest),
3434 asLatLng(boundsObject.northeast));
3435 }
3436
3437 function asLatLng(latLngObject){
3438 return new google.maps.LatLng(latLngObject.lat, latLngObject.lng);
3439 }
3440
3441 function asPath(encodedPolyObject){
3442 return google.maps.geometry.encoding.decodePath( encodedPolyObject.points );
3443 }
3444
3445 */
3446
3447
3448 var bodyAside = $("body>main>aside");
3449 bodyAside.delegate(".popover .fa-pencil", "click touchend", function (event) {
3450 $(".popover").popover("hide");
3451 tripItemEdit(RouteTable.getCurrentlySelected(), event);
3452 });
3453
3454 bodyAside.delegate(".popover .fa-info-circle", "click touchend", function (event) {
3455 $(".popover").popover("hide");
3456 var leg = curRoute.routeLegs[RouteTable.getCurrentlySelected()];
3457 showDescription(leg.poi);
3458 });
3459
3460 function showDescription(poi) {
3461 genPoiDetails(poi, PoiDetailsClickSource.MAP, function (response) {
3462 if (poi.region_abbr && !poi.state) {
3463 poi.state = poi.region_abbr;
3464 }
3465 poi.dump = response.dump;
3466 poi.propane = response.propane;
3467 poi.overnight = response.overnight;
3468 if (
3469 (poi.poitype_id && poi.poitype_id > 1 && poi.id) ||
3470 poi.place_id ||
3471 poi.poi_place_id ||
3472 poi.reference
3473 ) {
3474 // Google POI or custom poi
3475
3476 if (!poi.placeId && !poi.reference) {
3477 poi.placeId = poi.poi_place_id || poi.place_id;
3478 }
3479 PoiMarkerModal.initializePoiMarkerModal(poi);
3480 return;
3481 }
3482
3483 $('#marker-info-modal').modal('show');
3484 if (debug) console.log("gallery 2");
3485 markerModalHelper.populateModal(poi);
3486 if (debug) console.log(poi.photos);
3487 // $("#marker-info-modal").addClass("ipadFix")
3488 // setTimeout(function(){
3489 // $("#marker-info-modal").removeClass("ipadFix");
3490 // $(".poi-photo-section").trigger("resize");
3491 if (poi.photos && poi.photos.length > 0) {
3492 startGallery(poi.photos);
3493 }
3494
3495 // },10)
3496
3497
3498 });
3499 }
3500 bodyAside = $("body>main>aside");
3501 bodyAside.delegate(".popover .fa-trash", "click touchend", function (event) {
3502 $(".popover").popover("hide");
3503 RouteTable.deleteStop(RouteTable.getCurrentlySelected());
3504 //recalculateDates(curRoute);
3505 });
3506
3507 $(function () {
3508 $('[data-toggle="popover"]').popover();
3509 });
3510
3511 bodyAside.delegate("[data-title]", "mouseenter touchend", function (event) {
3512 $(event.target).tooltip({
3513 container: "body > main > aside"
3514 }).tooltip("show");
3515 });
3516 bodyAside.delegate("[data-title]", "mouseleave", function (event) {
3517 $(event.target).tooltip({
3518 container: "body > main > aside"
3519 }).tooltip("hide");
3520 });
3521
3522
3523 function tripItemEdit(indx, event) {
3524 event.preventDefault();
3525 event.stopPropagation();
3526 curSelItemIndex = indx;
3527 EditTripModal.initializeEditPoiModal(indx);
3528 }
3529
3530 $(".news-button").click(function () {
3531 NewsModal.showModal();
3532 });
3533
3534 $('#btn-show-description').on('click', function () {
3535 if (curSelItemIndex === undefined || curSelItemIndex === null) {
3536 return;
3537 }
3538
3539 var leg = curRoute.routeLegs[curSelItemIndex];
3540 showDescription(leg.poi);
3541 });
3542
3543
3544 function genPoiDetails(poi, clickSource, callback) {
3545 if (debug) console.log('Gen Poi Details', poi);
3546 var cached;
3547
3548 if (ajaxPoiDetails) {
3549 ajaxPoiDetails.abort();
3550 }
3551
3552 if (poi.poitype_id == 1) {
3553 loadingDetails = false;
3554 curBasicPoi = poi;
3555
3556 // Does the park have the park_info object?
3557 if (!poi.park_info) {
3558 $.ajax({
3559 url: apiUrl + 'parks/' + poi.id + '?include=photos_lite',
3560 //data: 'park_ids=' + parsedParksIds,
3561 noblock: true,
3562 type: 'GET',
3563 dataType: 'rvprv1',
3564 accepts: {
3565 rvprv1: 'application/x.rvparkreviews.v1+json'
3566 },
3567 converters: {
3568 'text rvprv1': function (result) {
3569 return $.parseJSON(result);
3570 }
3571 },
3572 success: function (r) {
3573 if (debug) console.log(r);
3574 //debug && console.log(JSON.stringify(poi));
3575 //debug && console.log(JSON.stringify((r)));
3576 poi = formatParkObject(poi, r);
3577 //debug && console.log(JSON.stringify((poi)))
3578 if (debug) console.log("1st");
3579 showPoiDetailsHTML(poi, poi, clickSource);
3580
3581 if (callback) {
3582 callback(poi);
3583 }
3584 }
3585 });
3586 } else {
3587 if (debug) console.log("2nd");
3588 showPoiDetailsHTML(poi, poi, clickSource);
3589
3590 if (callback) {
3591 callback(poi);
3592 }
3593 }
3594 } else {
3595 cached = cachedPois.filter(function (p) {
3596 if (poi.id == p.id) {
3597 return p;
3598 }
3599 });
3600
3601 if (cached && cached.length > 0) {
3602 loadingDetails = false;
3603 curBasicPoi = poi;
3604 if (debug) console.log("3rd");
3605 showPoiDetailsHTML(cached[0], cached[0], clickSource);
3606
3607 if (callback) {
3608 callback(cached[0]);
3609 }
3610
3611 return;
3612 }
3613
3614 ajaxPoiDetails = $.ajax({
3615 ws: "poi_details",
3616 noblock: true,
3617 data: {
3618 id: poi.id,
3619 trip_user_id: $("#trip_user_id").val()
3620 },
3621 success: function success(res) {
3622 if (!handleAjaxError(res)) {
3623 return;
3624 }
3625
3626 loadingDetails = false;
3627
3628 res.poi.poiCat = poi.poiCat;
3629 cachedPois.push(res.poi);
3630 curBasicPoi = poi;
3631 if (debug) console.log("4th");
3632 if (debug) console.log("4th res", res);
3633 showPoiDetailsHTML(poi, res.poi, clickSource);
3634 //if the custom modal is open at time of the ajax response, refresh the modal info
3635 if ($('#custom-poi-detailed-modal').css('display') != 'none') {
3636 PoiMarkerModal.hideModal();
3637 PoiMarkerModal.initializePoiMarkerModal(res.poi);
3638 }
3639
3640 if (cachedPois.length > 40) {
3641 cachedPois.splice(0, 1);
3642 }
3643
3644 if (callback) {
3645 callback(res.poi);
3646 }
3647 },
3648 complete: function () {
3649 ajaxPoiDetails = null;
3650 }
3651 });
3652 }
3653 }
3654
3655
3656
3657 function showPoiDetailsHTML(poi, poiDetails, clickSource) {
3658 if (debug) console.log('show details poi', poi, poiDetails);
3659 var comments = null;
3660 var loc = rvTripHelper.getStopAddress(poiDetails);
3661
3662 var verifyAndShow = function verifyAndShow(data, className, attr) {
3663 var element = $("#marker-info-modal ." + className);
3664 var attrType = (typeof attr === 'object') ? 'obj' : 'str';
3665 var hideTarget = function hideParent(element) {
3666 return element.hasClass("parent-hidden") ? hideParent(element.parent()) : element;
3667 }(element);
3668 if (data) {
3669 if (!attr) {
3670 element.text(data);
3671 } else if (attrType === 'str') {
3672 element.attr(attr, data);
3673 } else if (attrType === 'obj') {
3674 // Iterate keys in attr object
3675 $.each(attr, function (key, value) {
3676 if (key === 'text') {
3677 element.text(value);
3678 } else {
3679 element.attr(key, value);
3680 }
3681 });
3682 }
3683 hideTarget.removeClass("hidden");
3684 } else {
3685 hideTarget.addClass("hidden");
3686 }
3687 };
3688 if (curRoute && curRoute.routeLegs.length > 0 && curRoute.routeLegs.length > curSelItemIndex && curSelItemIndex !== null) {
3689 var poiLeg = curRoute.routeLegs[curSelItemIndex];
3690 if (poiLeg) {
3691 comments = poiLeg.poi.comments;
3692 }
3693 }
3694
3695 $("#marker-info-modal").find(".modal-title span").first().text(poiDetails.name);
3696 $(".poi-vicinity").html(loc);
3697
3698 if (curRoute && curRoute.routeLegs && curRoute.routeLegs.length > 0 && !poi.distance) {
3699 for (var i = 0; i < curRoute.routeLegs.length; i++) {
3700 if (
3701 (
3702 (poi.id > 0 && curRoute.routeLegs[i].poi.id === poi.id) ||
3703 (!poi.id && curRoute.routeLegs[i].poi.place_id === poi.place_id)
3704 ) && poi.poiCat !== PoiCat.User && curRoute.routeLegs[i].poi.poiCat === poi.poiCat
3705 ) {
3706 poi.distance = curRoute.routeLegs[i].poi.distance;
3707 }
3708 }
3709 }
3710
3711 // if (poi.distance) {
3712 // verifyAndShow(Math.floor(poi.distance), "distance");
3713 // } else {
3714 // console.log("third distance");
3715 // getDistanceAndShowInInfoBox(poi);
3716 // // if(!poi.distance){
3717 // // verifyAndShow(null,"distance");
3718 // // }
3719 // // else{
3720 // // verifyAndShow(Math.floor(poi.distance), "distance");
3721 // // }
3722 // }
3723
3724 $("#marker-affils").empty();
3725 var affiliations = [];
3726 if (poiDetails.affiliations) {
3727
3728 for (var x = 0; x < poiDetails.affiliations.length; x++) {
3729 var affiliation = poiDetails.affiliations[x];
3730 $("#marker-affils").prepend("<span data-affil='" + affiliation.name + "'><img src=\"/app/images/marker_img/" + affiliation.image_name + "\"></span>");
3731 affiliations.push(affiliation.name);
3732 }
3733
3734 affiliations = affiliations.join(', ');
3735 } else {
3736 affiliations = '';
3737 }
3738
3739 var park_siteinfo = [];
3740 var park_features = [];
3741 if (poiDetails.park_info && poiDetails.park_info['Hookups_&_Connectivity']) {
3742 $.each(poiDetails.park_info['Hookups_&_Connectivity'], function (key, info) {
3743 if (info.type == 'bool' && info.value == true) {
3744 park_siteinfo.push(info.desc);
3745 }
3746 });
3747 }
3748
3749 if (poiDetails.park_info && poiDetails.park_info.Park_Features) {
3750 $.each(poiDetails.park_info.Park_Features, function (key, info) {
3751 if (info.type == 'bool' && info.value == true) {
3752 park_features.push(info.desc);
3753 }
3754 });
3755 }
3756
3757 if (poiDetails.park_info && poiDetails.park_info.Amenities) {
3758 $.each(poiDetails.park_info.Amenities, function (key, info) {
3759 if (info.type == 'bool' && info.value == true) {
3760 park_features.push(info.desc);
3761 }
3762 });
3763 }
3764
3765 if (poiDetails.park_info && poiDetails.park_info.Recreation) {
3766 $.each(poiDetails.park_info.Recreation, function (key, info) {
3767 if (info.type == 'bool' && info.value == true) {
3768 park_features.push(info.desc);
3769 }
3770 });
3771 }
3772
3773 if (park_siteinfo.length) {
3774 poiDetails.siteinfo = park_siteinfo.join(', ');
3775 }
3776
3777 if (park_features.length) {
3778 poiDetails.features = park_features.join(', ');
3779 }
3780
3781 $(".txt-add-poi-nights").on("input", function () {
3782 var nights = $(this).val();
3783 var $parentForm = $(this).closest('form');
3784 $parentForm.find('.txt-add-poi-camping-total').val(userProfile.camping * nights);
3785 });
3786
3787 verifyAndShow(poiDetails.price, "price");
3788 verifyAndShow(comments, "comments");
3789 verifyAndShow(affiliations, "affil");
3790 // verifyAndShow(loc, "location");
3791 verifyAndShow(true, "phone", {
3792 'href': poiDetails.phone ? "tel:" + poiDetails.phone : null,
3793 'text': poiDetails.phone ? poiDetails.phone : null
3794 });
3795 verifyAndShow(poiDetails.siteinfo, "site-info");
3796 verifyAndShow(poiDetails.features, "features");
3797 verifyAndShow(poiDetails.season, "season");
3798
3799 var url = null;
3800 if (poiDetails.website) {
3801 url = poiDetails.website;
3802 }
3803
3804 url = formatUrl(url);
3805
3806 if (poiDetails.park_id) {
3807 verifyAndShow(true, "url", {
3808 'href': url,
3809 'data-interaction': 'park_click',
3810 'data-park_id': poiDetails.park_id
3811 });
3812 } else {
3813 verifyAndShow(true, "url", {
3814 'href': url,
3815 'data-interaction': '',
3816 'data-park_id': ''
3817 });
3818 }
3819 verifyAndShow(poiDetails.email ? "mailto:" + poiDetails.email : null, "email", "href");
3820 verifyAndShow(poiDetails.desc, "desc");
3821 if (poi.rating_avg) {
3822 verifyAndShow(Math.round(poi.rating_avg * 10) / 10, "rating");
3823 } else {
3824 verifyAndShow(poi.rating, "rating");
3825 }
3826 verifyAndShow(poiDetails.lat, "lat");
3827 verifyAndShow(poiDetails.lon, "lon");
3828 verifyAndShow('https://www.google.com/maps/@?api=1&map_action=map¢er=' + poiDetails.lat + ',' + poiDetails.lon + '&zoom=18&basemap=satellite', "satellite", "href");
3829 verifyAndShow(poiDetails.lat && poiDetails.lon ? "http://rrtexternalweb.wrightexpress.com/search?sortByValue=Price&sortDirectionValue=ASC&mapType=Hybrid&mapZoom=3&sorting=false&fuelTypeValue=" + userProfile.gas_type + "&radius=15&latitude=" + poiDetails.lat + "&longitude=" + poiDetails.lon + "&city=" + poiDetails.city + "&state=" + poiDetails.state + "&zip=" + poiDetails.zip : null, "fuel-prices", "href");
3830 //generateSlider($('#thumbnails'), $('.thumbs'), poi.photos);
3831
3832 globalSelectedPoi = poi;
3833 if (poi.poitype_id === 1) {
3834 $("#poiId").val(poi.id);
3835 $("#poiCat").val(poi.cat);
3836 fillStars($('.rating-container'), poiDetails);
3837 } else {
3838 $('#custom-poi-detailed-modal').find('[name=poiId]').val(poi.id);
3839 $("#custom-poi-detailed-modal").find("[name=poiCat]").val(poi.cat);
3840 }
3841
3842 $("#poiCg").val(poi.cg);
3843
3844 $(".follow-trip").empty();
3845 var $formChildren = $(".add-to-trip-form").find(".form-control, input, .btn");
3846 if (curRoute && curRoute.routeLegs) {
3847 $formChildren.attr("disabled", false);
3848 setRouteCombo(null);
3849 } else {
3850 $formChildren.attr("disabled", true);
3851 }
3852
3853 $(".rating-text").text(_global.ratingCaptions[(poiDetails.rating ? poiDetails.rating * 2 : 0)]);
3854 if (poi.address !== poi.name) {
3855 $(".show-reviews").parent().removeClass("hidden");
3856 $(".show-reviews").attr("href", poiDetails.url);
3857 } else {
3858 $(".show-reviews").parent().addClass("hidden");
3859 }
3860 $(".stop-select input, .stop-select select").attr("disabled", !curRoute || !curRoute.routeLegs || curRoute.routeLegs.length < 2);
3861 $(".stop-select select").attr("disabled", function () {
3862 return !$(this).siblings("input[type=radio]")[0].checked;
3863 });
3864 }
3865
3866
3867 $("[name=stop]").on("change", function () {
3868 var $select = $(this).parents(".radio").parent().find("select");
3869 $select.attr("disabled", this.value !== "stop" || curRoute.routeLegs.length < 2);
3870 });
3871
3872
3873 function setRouteCombo(itemIndex) {
3874 if (!curRoute) {
3875 return;
3876 }
3877
3878 var bIndex = itemIndex - 1;
3879
3880 var option = $("<option></option>");
3881 option.text("-- The Last Stop --");
3882 option.val("-1");
3883 $(".follow-trip").append(option);
3884
3885 curRoute.routeLegs.forEach(function (leg, index) {
3886 if (itemIndex != index && bIndex != index) {
3887 option = $("<option></option>");
3888 option.text((index + 1) + " - " + leg.poi.name);
3889 option.val(index);
3890 $(".follow-trip").append(option);
3891 }
3892 });
3893 }
3894 //SHOULD PROBABLY MOVE THIS TOO
3895
3896 $('#marker-info-modal').on('shown.bs.modal', function (e) {
3897 $(window).trigger("resize");
3898 window.dispatchEvent(new Event('resize'));
3899 $(this).trigger("resize");
3900 $("#collapseOne").collapse('show');
3901 });
3902
3903 $('#marker-info-modal').on('hidden.bs.modal', function (e) {
3904 AddToTripComponent.disableSticky();
3905 $(".affiliation-text").show();
3906 $(".connection-container").remove();
3907 $("#collapseOne").collapse('hide');
3908 $("#collapseTwo").collapse('hide');
3909 $("#collapseThree").collapse('hide');
3910 $("#collapseFour").collapse('hide');
3911 $("#collapseFive").collapse('hide');
3912
3913 // RESET TO OVERVIEW
3914 $('.nav-tabs a[href="#nav-overview"]').tab('show');
3915 $(".nav-item").removeClass("lg-tab-active lg-tab");
3916 $('.nav-tabs a[href="#nav-overview"]').addClass("lg-tab-active");
3917 $(".nav-item").not('.nav-tabs a[href="#nav-overview"]').addClass("lg-tab");
3918
3919 $(".tip-area").empty();
3920 $(".question-container-lg, question-answer-sm").empty();
3921 $('.feature-container, .features-content-lg').empty();
3922 $(".lg-space").remove();
3923 $('.review-section').empty();
3924 $(".review-section-lg").empty();
3925 $(".modal-miles").text("...");
3926 $.each($('.connectivity-item'), function (index, item) {
3927 $(item).attr("src", './images/marker_modal/no-wifi.svg');
3928 });
3929
3930 $(".affiliation-cont").empty();
3931 $(".thumbs").empty();
3932 $('.collapse').removeClass("show");
3933 var $reAddDiv = $("<ul></ul>").attr("id", "carousel-new");
3934 $('.poi-photo-section').prepend($reAddDiv);
3935 var $reAddDivSm = $("<ul></ul>").attr("id", "carousel-new-sm");
3936 $(".poi-photo-section-sm").prepend($reAddDivSm);
3937 $(".lSSlideOuter").remove();
3938 });
3939
3940 $("#nav-overview-tab").on("shown.bs.tab", function () {
3941 $(window).trigger("resize");
3942 });
3943
3944 $('.nav-item').click(function (e) {
3945 $(".nav-item").removeClass("lg-tab-active lg-tab");
3946 $(this).addClass("lg-tab-active");
3947 $(".nav-item").not(this).addClass("lg-tab");
3948 });
3949
3950 $('#modal-overview').on('shown.bs.collapse', function (e) {
3951 // if($(".lSSlideOuter").length > 0){
3952 // debug && console.log("noGood");
3953 // debug && console.log($(".lSSlideOuter"));
3954 // }
3955 // else{
3956 if ($(window).width() < 992) {
3957 setTimeout(function () {
3958 startGallerySmall(currentPhotos);
3959 }, 1000);
3960 }
3961
3962 // startGallerySmall(currentPhotos);
3963
3964
3965 });
3966
3967 $("#collapseFour").on("shown.bs.collapse", function () {
3968 $(".modal-content").animate({
3969 scrollTop: $("#collapseFour")[0].offsetTop
3970 }, 200);
3971
3972 });
3973
3974 $("#collapseParkTypes").on("shown.bs.collapse", function () {
3975 if (debug) console.log($("#collapseParkTypes")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
3976 });
3977
3978 $("#collapseParkFeatures").on("shown.bs.collapse", function () {
3979 if (debug) console.log($("#collapseParkFeatures")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
3980 if ($("#collapseParkFeatures")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
3981 $(".set-filters-view").animate({
3982 scrollTop: $("#collapseParkFeatures")[0].offsetTop
3983 }, 200);
3984 }
3985 });
3986
3987 $("#collapseHookupsConnectivity").on("shown.bs.collapse", function () {
3988 if (debug) console.log($("#collapseHookupsConnectivity")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
3989 if ($("#collapseHookupsConnectivity")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
3990 $(".set-filters-view").animate({
3991 scrollTop: $("#collapseHookupsConnectivity")[0].offsetTop
3992 }, 200);
3993 }
3994 });
3995
3996 $("#collapseParkFeatures").on("shown.bs.collapse", function () {
3997 if (debug) console.log($("#collapseParkFeatures")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
3998 if ($("#collapseParkFeatures")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
3999 $(".set-filters-view").animate({
4000 scrollTop: $("#collapseParkFeatures")[0].offsetTop
4001 }, 200);
4002 }
4003 });
4004
4005 $("#collapseAmenities").on("shown.bs.collapse", function () {
4006 if (debug) console.log($("#collapseAmenities")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
4007 if ($("#collapseAmenities")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
4008 $(".set-filters-view").animate({
4009 scrollTop: $("#collapseAmenities")[0].offsetTop
4010 }, 200);
4011 }
4012 });
4013
4014 $("#collapseParkPricing").on("shown.bs.collapse", function () {
4015 if (debug) console.log($("#collapseParkPricing")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
4016 if ($("#collapseParkPricing")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
4017 $(".set-filters-view").animate({
4018 scrollTop: $("#collapseParkPricing")[0].offsetTop
4019 }, 200);
4020 }
4021 });
4022
4023 $("#collapseRecreation").on("shown.bs.collapse", function () {
4024 if (debug) console.log($("#collapseRecreation")[0].offsetTop, $(".set-filters-view").height(), $(".set-filters-view").scrollTop());
4025 if ($("#collapseRecreation")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
4026 $(".set-filters-view").animate({
4027 scrollTop: $("#collapseRecreation")[0].offsetTop
4028 }, 200);
4029 }
4030 });
4031
4032 $("#collapseDiscountClubs").on("shown.bs.collapse", function () {
4033 if ($("#collapseDiscountClubs")[0].offsetTop - 50 > $(".set-filters-view").height() + $(".set-filters-view").scrollTop()) {
4034 $(".set-filters-view").animate({
4035 scrollTop: $("#collapseDiscountClubs")[0].offsetTop
4036 }, 200);
4037 }
4038 });
4039
4040
4041 function startGallerySmall(photos) {
4042 if (photos && photos.length > 0) {
4043 $(".photo-num").show();
4044 $(".overview-lg-no-phto").hide();
4045 $('.poi-photo-section-sm').show();
4046 var photoNum = 1;
4047 var allPics = 0;
4048 var currentIndex = 0;
4049 var photoArray = [];
4050 photoSize = photos.length;
4051 var controlBool = true;
4052 if (photoSize == 1) {
4053 controlBool = false;
4054 }
4055 photos.forEach(function (photo) {
4056 var caroList = $("<li data-thumb=" + photo.large_url + "></li>");
4057 var caroLink = $("<a href='#slide" + photoNum + "'></a>");
4058 var caroPic = $("<div class='slide-box'></div>").css('background-image', 'url(' + photo.large_url + ')');
4059 caroLink.append(caroPic);
4060 caroList.append(caroLink);
4061 caroList.appendTo("#carousel-new-sm");
4062
4063 photoNum += 1;
4064 });
4065
4066 var thumbs = jQuery('#carousel-new-sm').lightSlider({
4067 // general elements & wrapper
4068 pager: true,
4069 gallery: false,
4070 item: 1,
4071 loop: true,
4072 enableTouch: true,
4073 thumbMargin: 5, //photos.length > 10 ? 10: photos.length,
4074 thumbItem: 10,
4075 galleryMargin: 3,
4076 auto: false,
4077 controls: true,
4078 onSliderLoad: function () {
4079 $('.poi-photo-section-sm .lSPager').remove();
4080 $('.poi-photo-section-sm span').text("1 of " + photoSize);
4081 },
4082 onBeforeSlide: function (el, index_old, index_new) {
4083 // slider when revolving puts in some weird indexs around the end and beginning. This sanitizes those
4084 if (index_old == 0) {
4085 $('.poi-photo-section-sm span').text(photoSize + " of " + photoSize);
4086 } else {
4087 $('.poi-photo-section-sm span').text((((index_old - 1) % (photoSize)) + 1) + " of " + photoSize);
4088 }
4089
4090 jQuery('.thumbs a img').removeClass('active');
4091 jQuery('img', jQuery('.thumbs a')[index_new]).addClass('active');
4092
4093 }
4094 });
4095 } else {
4096 $(".photo-num").hide();
4097 $(".overview-lg-no-phto").show().css("display", "flex");
4098 $('.poi-photo-section').hide();
4099 }
4100 }
4101 // MOVE THIS TOO
4102 function startGallery(photos) {
4103 if (photos && photos.length > 0) {
4104 $(".overview-lg-no-phto").hide();
4105 $('.poi-photo-section').show();
4106 var photoNum = 1;
4107 var allPics = 0;
4108 var currentIndex = 0;
4109 var photoArray = [];
4110 photoSize = photos.length;
4111 var controlBool = true;
4112 if (photoSize == 1) {
4113 controlBool = false;
4114 }
4115 photos.forEach(function (photo) {
4116 var caroList = $("<li data-thumb=" + photo.large_url + "></li>");
4117 var caroLink = $("<a href='#slide" + photoNum + "'></a>");
4118 var caroPic = $("<div class='slide-box'></div>").css('background-image', 'url(' + photo.large_url + ')');
4119 caroLink.append(caroPic);
4120 caroList.append(caroLink);
4121 caroList.appendTo("#carousel-new");
4122
4123 photoNum += 1;
4124 });
4125 var thumbs = jQuery('#carousel-new').lightSlider({
4126 // general elements & wrapper
4127 pager: true,
4128 gallery: true,
4129 item: 1,
4130 loop: true,
4131 enableTouch: true,
4132 thumbMargin: 5, //photos.length > 10 ? 10: photos.length,
4133 thumbItem: 10,
4134 galleryMargin: 3,
4135 auto: false,
4136 controls: true,
4137 onSliderLoad: function () {
4138 //$('.lSPager').remove();
4139 $('.poi-photo-section span').text("1 of " + photoSize);
4140 },
4141 onBeforeSlide: function (el, index_old, index_new) {
4142 // slider when revolving puts in some weird indexs around the end and beginning. This sanitizes those
4143 if (index_old == 0) {
4144 $('.poi-photo-section span').text(photoSize + " of " + photoSize);
4145 } else {
4146 $('.poi-photo-section span').text((((index_old - 1) % (photoSize)) + 1) + " of " + photoSize);
4147 }
4148
4149 jQuery('.thumbs a img').removeClass('active');
4150 jQuery('img', jQuery('.thumbs a')[index_new]).addClass('active');
4151
4152 }
4153 });
4154 } else {
4155 $(".overview-lg-no-phto").show().css("display", "flex");
4156 $('.poi-photo-section').hide();
4157 }
4158 }
4159 // MOVE IT
4160 function fillStars($container, poi) {
4161 var $stars = $container.find('.stars i');
4162 var $rating = $container.find('.rating');
4163
4164 $container.removeClass('hidden');
4165
4166 $.each(_global.ratingCaptions, function (key, value) {
4167 $container.removeClass('rating-' + value.toLowerCase());
4168 });
4169
4170 if (!poi.rating) {
4171 $container.addClass('rating-unrated');
4172 $stars.addClass('hidden');
4173 $rating.addClass('hidden');
4174 return;
4175 }
4176 $rating.removeClass('hidden');
4177
4178 var rating = poi.rating * 2;
4179 $rating.html(Math.round(poi.rating_avg * 10) / 10);
4180 if (_global.ratingCaptions[parseInt(poi.rating * 2)]) {
4181 $container.addClass('rating-' + _global.ratingCaptions[parseInt(poi.rating * 2)].toLowerCase());
4182 } else {
4183 $container.addClass('rating-null');
4184 }
4185
4186 $.each($stars, function (index, star) {
4187 var i = index;
4188 // going through ten stars, not five. Desktop and mobile versions of the star ratings.
4189 if (i > 4) {
4190 i -= 5;
4191 }
4192 $(star).removeClass('hidden fa-star fa-star-o fa-star-half-o');
4193
4194 if (i + 0.5 == poi.rating) {
4195 $(star).addClass('fa fa-star-half-o');
4196 } else if (i + 1 <= poi.rating) {
4197 $(star).addClass('fa fa-star');
4198 } else {
4199 $(star).addClass('fa fa-star-o');
4200 }
4201 });
4202 }
4203
4204 function handleApiAjaxError(result) {
4205 if (result.message) {
4206 alert(result.message);
4207 return false;
4208 } else {
4209 return true;
4210 }
4211 }
4212
4213 function handleAjaxError(result) {
4214 if (!result.status || result.errMsg) {
4215 if (result.errMsg && result.errMsg != '') {
4216 alert(result.errMsg);
4217 }
4218 if (result.code && result.code == 'SESSION_TIMEOUT') {
4219 $('.logout').click();
4220 }
4221 return false;
4222 } else {
4223 return true;
4224 }
4225 }
4226 //var hammertime2;
4227 function genUserPoiDetails() {
4228 var poi = {};
4229 poi.poiCat = PoiCat.USER;
4230 poi.id = -1;
4231 poi.cg = "no";
4232 poi.imageName = curUserPoi.imageName;
4233 poi.address = curUserPoi.address;
4234 }
4235 var currentPhotos;
4236
4237 function showMarkerInfoBox(poi, marker, hideShowMore) {
4238 if (debug) console.log('Show Marker Info Box - ' + poi.id);
4239 var infoPoi = {};
4240 if (poi.region_abbr && !poi.state) {
4241 poi.state = poi.region_abbr;
4242 }
4243 infoPoi.name = poi.name;
4244 infoPoi.address = _global.getFormattedAddress(poi) || poi.address || poi.name || "";
4245 infoPoi.lat = poi.lat;
4246 infoPoi.lon = poi.lon;
4247 /* GENERATE CUSTOM-INFOBOX OBJECT */
4248 var infoBoxOptions = {
4249 config: {
4250 offsetX: ($("#mapContainer").hasClass('map-container-contracted') && window.innerWidth >= 1200) ? 408 : 0,
4251 offsetY: parseFloat($('.navbar').css('height').replace('px', ''))
4252 },
4253 content: {
4254 id: poi.id,
4255 title: poi.poitype_id == 26 ? (poi.name + " - " + infoPoi.address) : poi.name,
4256 text: infoPoi.address,
4257 lat: infoPoi.lat,
4258 lon: infoPoi.lon,
4259 num_ratings: poi.rating_count,
4260 width: window.innerWidth,
4261 hours: poi.hours,
4262 closed: poi.closed
4263 },
4264 events: {
4265 onMouseEnter: function () {
4266 pointerInInfobox = true;
4267 },
4268 onMouseLeave: function () {
4269 pointerInInfobox = false;
4270 },
4271 onTopButtonClick: function () {
4272 rvGmapHelper.handleSetADCircleZoom(this);
4273 }
4274 }
4275 };
4276 if (poi.propane) {
4277 if (poi.dump) {
4278 infoBoxOptions.content.title += ' (Propane and Dump Station)';
4279 } else {
4280 infoBoxOptions.content.title += ' (Propane)';
4281 }
4282 } else if (poi.dump) {
4283 infoBoxOptions.content.title += ' (Dump Station)';
4284 }
4285
4286 if (poi.id <= 0 && poi.poi_type) {
4287 infoBoxOptions.content.poi_type = lowerToUpper(poi.poi_type);
4288 }
4289
4290 if (poi.distance) {
4291 infoBoxOptions.content.distance = poi.distance;
4292 }
4293
4294 if (poi.price_level) {
4295 infoBoxOptions.content.price_level = poi.price_level;
4296 }
4297
4298 if (poi.photos && poi.photos.length > 0) {
4299 if (poi.photos[0].src) {
4300 infoBoxOptions.content.preview = poi.photos[0].src;
4301 } else {
4302 infoBoxOptions.content.preview = poi.photos[0].small_url;
4303 }
4304 }
4305
4306 if (poi.rating_avg) {
4307 infoBoxOptions.content.rating = poi.rating_avg;
4308 } else if (poi.rating) {
4309 infoBoxOptions.content.rating = poi.rating; //restrict to halfs
4310 }
4311
4312 if (marker.poi_type_image) {
4313 poi.poi_type_image = marker.poi_type_image;
4314 }
4315
4316 if (poi.poitype_id == 1) {
4317 $(".custom-infobox-text").show();
4318 $(".custom-infobox-title").css("text-align", "left");
4319 infoBoxOptions.content.buttonText = 'More Details';
4320 infoBoxOptions.events.onMainButtonClick = function (content) {
4321 var disableStopToFollow = !curRoute || !curRoute.routeLegs || curRoute.routeLegs.length < 1;
4322
4323 if (disableStopToFollow) {
4324 $(".stop-select input, .stop-select select").prop("disabled", "true");
4325 } else {
4326 $(".stop-select input, .stop-select select").removeProp("disabled");
4327 }
4328 markerModalHelper.populateModal(poi);
4329 $(content.id === -1 ? "#custom-poi-info-modal" : "#marker-info-modal").modal("show");
4330 if ($('.modal-badge-info-lg').children().size() > 1 || $('.modal-badge-info').children().size() > 1) {
4331 $('.marker-title-container').css('padding-left', 145);
4332 } else {
4333 $('.marker-title-container').css('padding-left', 20);
4334 }
4335 currentPhotos = poi.photos;
4336 if (currentPhotos && currentPhotos.length > 0) {
4337 startGallery(currentPhotos);
4338 }
4339 };
4340 }
4341 // This is for waypoints, no need for more details box
4342 else if (poi.poitype_id == -2 || poi.poitype_id == 26) {
4343 $(".custom-infobox-text").hide();
4344 $(".custom-infobox-title").css("text-align", "center");
4345 } else {
4346 $(".custom-infobox-title").css("text-align", "left");
4347 $(".custom-infobox-text").show();
4348
4349 infoBoxOptions.content.buttonText = 'More Details';
4350 infoBoxOptions.events.onMainButtonClick = function (content) {
4351 if (poi.id > -1 || poi.place_id || poi.poi_place_id || poi.placeReference) {
4352 if (poi.reference) { //Delete sortable reference prop which interferes with gmaps
4353 delete poi.reference;
4354 }
4355
4356 if (!poi.placeId) {
4357 poi.placeId = poi.place_id || poi.poi_place_id;
4358 }
4359
4360 poi.marker = marker;
4361 PoiMarkerModal.initializePoiMarkerModal(poi);
4362 } else {
4363 showCustomStop(content.lat, content.lon, content.title, poi);
4364 }
4365
4366 };
4367 }
4368
4369 if (infoBoxOptions && infoBoxOptions.content && infoBoxOptions.content.title && infoBoxOptions.content.title.selector) {
4370 infoBoxOptions.content.title = infoBoxOptions.content.title.selector;
4371 }
4372 infoBox = new customInfobox(infoBoxOptions);
4373 infoBox.id = poi.id;
4374 /* /GENERATE CUSTOM-INFOBOX OBJECT */
4375 if (poi.poitype_id == -2 || poi.poitype_id == 26) {
4376 infoBox.hideButton();
4377 } else {
4378 infoBox.showButton();
4379 }
4380 infoBox.open(map, marker);
4381 if (poi.poitype_id == 26) {
4382 $("#infobox-circle").hide();
4383 }
4384 if (!poi.poitype_id) {
4385 $("#custom-stars > i").hide();
4386 } else {
4387 $("#custom-stars > i").show();
4388 }
4389 }
4390
4391 function isElementInViewport(el) {
4392
4393 //special bonus for those using jQuery
4394 if (typeof jQuery === "function" && el instanceof jQuery) {
4395 el = el[0];
4396 }
4397
4398 var rect = el.getBoundingClientRect();
4399
4400 return (
4401 rect.top >= 0 &&
4402 rect.left >= 0 &&
4403 rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
4404 rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
4405 );
4406 }
4407
4408 function getCustomIconName(poi) {
4409 if (!poi || !poi.name) return null;
4410 var skipWords = ['near', 'the'];
4411 var nameWords = poi.name.split(' ');
4412 for (var i = 0; i < nameWords.length; i++) {
4413 if (skipWords.indexOf(nameWords[i].toLowerCase()) >= 0) {
4414 continue;
4415 }
4416 var firstLetter = nameWords[i][0].toUpperCase();
4417 return firstLetter.match(/[A-Z0-9]/) ? firstLetter : null;
4418 }
4419 return null;
4420 }
4421 // add poi to the end to trip
4422 function btnAddToTripEndClick(id, cg, poiCat, formData) {
4423 if (!curRoute) {
4424 alert(_global.msg.needToCreateTrip);
4425 return;
4426 }
4427 if (poiCat == PoiCat.USER) {
4428 addUserPoi();
4429 return;
4430 }
4431
4432 var nights = formData ? formData.nights : $(".txt-add-poi-nights").val(),
4433 costCamping = formData ? formData.camping_total : $(".txt-add-poi-camping-total").val(),
4434 comment = formData ? formData.comment : $(".poi-details-poi-comment").val();
4435
4436 // adding basic poi
4437 //var poi = $.extend(true, {}, curBasicPoi); //for both cg and noncg poi but not user poi
4438 var poi = curBasicPoi; //for both cg and noncg poi but not user poi
4439 if (!poi) {
4440 poi = {};
4441 }
4442 if (formData.address) {
4443 poi.address = formData.address;
4444 }
4445
4446 if (poiCat == undefined) {
4447 poi.poiCat = PoiCat.USER;
4448 }
4449
4450 if (formData && formData.lat && formData.lon) {
4451 poi.lat = formData.lat;
4452 poi.lon = formData.lon;
4453 }
4454
4455 if (formData.name) {
4456 poi.name = formData.name;
4457 }
4458
4459 if (formData.poi_type_image) {
4460 poi.poi_type_image = formData.poi_type_image;
4461 }
4462
4463 if (formData.street) {
4464 poi.street = formData.street;
4465 }
4466
4467 if (!poi.id && poi.lat && poi.lon) { //Set an Id for custom pois so we can show/hide them if necessary
4468 poi.id = poi.lat + '|' + poi.lon;
4469 poi.poi_map_icon = getCustomIconName(poi);
4470 poi.imageName = customImageName(poi);
4471 poi.poi_type_image = customImageName(poi);
4472 }
4473
4474 poi.nights = _global.utils.isNumber(nights) ? parseInt(nights, 10) : 0;
4475 if (poi.nights) {
4476 poi.costCamping = _global.utils.isNumber(costCamping) ? costCamping : parseInt(userProfile.camping);
4477 } else {
4478 poi.costCamping = 0;
4479 }
4480
4481
4482 poi.cost = null;
4483 poi.costCamping = null;
4484 poi.costMeals = null;
4485 poi.costMisc = null;
4486 poi.fuelCpg = null;
4487 poi.comments = comment ? comment : "";
4488 rvTripHelper.setBasicPoiDetailsProperties(poi);
4489 callBlockUI();
4490
4491 // if (!startPositionInfo.status) {
4492 // console.log("custom 1");
4493 // //poi.marker = createCustomMarker(poi);
4494
4495 // genRouteListing();
4496 // SaveTrip();
4497 // callUnBlockUI();
4498 // if (selectedState != "-1") {
4499 // rvTripHelper.clearPoiStateSelection();
4500 // }
4501 // } else {
4502 AddToRoute(poi, true, function () {
4503 callUnBlockUI();
4504 if (selectedState != "-1") {
4505 rvTripHelper.clearPoiStateSelection();
4506 }
4507 rvTripHelper.drawDriveCircle(poi);
4508 rvTripLC.showOverlayLC();
4509 });
4510 // }
4511 }
4512 // add poi to user define index.
4513 function AddToTripInDefineIndex(id, cg, poiCat, index, formData) {
4514 var stopNum = -1;
4515 // validate stopper position number
4516 if (!_global.utils.isNumber(index)) {
4517 alert("Please enter valid stop number.");
4518 return;
4519 }
4520
4521 stopNum = parseInt(index, 10);
4522 if (stopNum <= 0 || stopNum > curRoute.routeLegs.length) {
4523 alert("Please enter valid stop number.");
4524 return;
4525 }
4526
4527
4528 // check at the end of the trip
4529 if (stopNum == curRoute.routeLegs.length) {
4530 if (poiCat == PoiCat.BASIC) {
4531 btnAddToTripEndClick(id, cg);
4532 } else {
4533 addUserPoi();
4534 }
4535
4536 return;
4537 }
4538
4539 var nights = formData ? formData.nights : $(".txt-add-poi-nights").val(),
4540 costCamping = formData ? formData.camping_total : $(".txt-add-poi-camping-total").val(),
4541 comment = formData ? formData.comment : $(".poi-details-poi-comment").val();
4542 var poi = null;
4543 nights = _global.utils.isNumber(nights) ? parseInt(nights, 10) : 0;
4544 comments = comment ? comment : "";
4545
4546 poi = curBasicPoi;
4547 if (!poi) {
4548 poi = {};
4549 }
4550
4551 if (poiCat == undefined) {
4552 poi.poiCat = PoiCat.USER;
4553 }
4554
4555 if (formData && formData.lat && formData.lon) {
4556 poi.lat = formData.lat;
4557 poi.lon = formData.lon;
4558 }
4559
4560 //nights
4561 if (formData.name) {
4562 poi.name = formData.name;
4563 }
4564 poi.cost = null;
4565 poi.costCamping = null;
4566 poi.costMeals = null;
4567 poi.costMisc = null;
4568 poi.fuelCpg = null;
4569 poi.nights = nights;
4570 poi.comments = comments;
4571 rvTripHelper.setBasicPoiDetailsProperties(poi);
4572
4573 if (formData.poi_type_image) {
4574 poi.poi_type_image = formData.poi_type_image;
4575 }
4576 if (!id) {
4577 poi.poi_map_icon = getCustomIconName(poi);
4578 poi.imageName = customImageName(poi);
4579 poi.poi_type_image = customImageName(poi);
4580 }
4581 var newLeg = {};
4582 newLeg.poi = poi;
4583 newLeg.nights = nights;
4584 newLeg.poi.costCamping = parseInt(costCamping);
4585 newLeg.poi.fuelCpg = parseInt(routeCostHelper.getStopCpg(stopNum - 1));
4586 newLeg.poi.cost = parseInt(routeCostHelper.routeCost(newLeg.poi.distance, parseInt(newLeg.poi.nights), newLeg.poi.poiCat, parseInt(newLeg.poi.fuelCpg)));
4587
4588 rvTripHelper.setPoiExtendedProperties(poi);
4589
4590 var nextLeg = curRoute.routeLegs[stopNum];
4591 // clear route
4592 rvTripHelper.clearLegRoutePath(nextLeg);
4593 //clear waypoints of next leg
4594 newLeg.poi.waypoints = [];
4595 //getting new Poi Leg
4596 callBlockUI();
4597
4598 curRoute.routeLegs.splice(stopNum, 1);
4599 AddToRoute(newLeg.poi, false, function () {
4600 AddToRoute(nextLeg.poi, true, function () {
4601 if (selectedState != "-1") {
4602 rvTripHelper.clearPoiStateSelection();
4603 }
4604 fuelCalculator.recalculateAllFuelRemaining();
4605 clearAfterAddToRoute();
4606 genRouteListing();
4607
4608 callUnBlockUI();
4609 }, stopNum + 1);
4610
4611 }, stopNum);
4612 }
4613 // add basic[actully cg and noncg poi] poi as start point
4614
4615
4616
4617 function SaveTrip(callback, forceSave, nameChanged) {
4618 if (!curRoute) {
4619 if (callback) callback(false);
4620 return;
4621 }
4622 ElevationSection.close();
4623 var tripName = curRoute.name;
4624 var tripId = parseInt($("#hdnTripId").val(), 10);
4625 $("#search-location").val("");
4626 var routeDetails = [];
4627 var miles = 0;
4628 //recalculateDates(curRoute);
4629 for (var i = 0; i < curRoute.routeLegs.length; i++) {
4630 var leg = curRoute.routeLegs[i];
4631
4632 if (i > 0) {
4633 leg.poi.fuelCpg = leg.poi.fuelCpg ? leg.poi.fuelCpg : routeCostHelper.getStopCpg(i - 1);
4634 } else {
4635 leg.poi.distance = 0;
4636 leg.poi.time = undefined;
4637 }
4638
4639 if (leg.poi.distance) {
4640 miles += Math.floor(leg.poi.distance);
4641 }
4642
4643 var item = {};
4644
4645 // We can not save stops that don't have a lat or lon, which apparently happens occasionally.. Probably from a failed Google decode
4646 //create alert for bad park values
4647 if (!leg.poi.lat) {
4648 alert('Invalid park, contact us for help');
4649 alert("Failed to Save Trip!");
4650 } else {
4651 item.lat = parseFloat(leg.poi.lat);
4652 item.lon = parseFloat(leg.poi.lon);
4653 item.poiName = leg.poi.name.replace(/[\']/gi, "");
4654 }
4655 /* Custom POIs can not have a poiId as the parent POI can, and is, replaced when we do POI updates. Any data
4656 intended to be connected to the POI on reload has to be stored as part of the stop. Beside that, there is an issue
4657 where we are setting the poi.id of POIs to the lat and lon so this was assigning wrong ids to those stops. */
4658 if (leg.poi.poiCat == PoiCat.USER) {
4659 item.id = -1;
4660 } else {
4661 item.id = parseInt(leg.poi.id);
4662 }
4663 item.poitype_id = leg.poi.poitype_id;
4664
4665 item.nights = leg.poi.nights;
4666 item.serial = i;
4667 if (leg.poi.comments) {
4668 item.comments = encodeURIComponent(leg.poi.comments);
4669 }
4670 if (leg.poi.reservationNum) {
4671 item.reservationNum = encodeURIComponent(leg.poi.reservationNum ? leg.poi.reservationNum : "");
4672 }
4673 item.cost = leg.poi.cost;
4674 // extended poi properties
4675 item.fuelCpg = leg.poi.fuelCpg == -1 ? userProfile.cpg : leg.poi.fuelCpg;
4676 item.costCamping = leg.poi.costCamping;
4677 item.costMeals = leg.poi.costMeals;
4678 item.costMisc = leg.poi.costMisc;
4679 item.fuelRemaining = !leg.poi.isFuelRemainingCustom || !leg.poi.fuelRemaining ? null : leg.poi.fuelRemaining;
4680 item.address = leg.poi.poiCat == PoiCat.USER ? leg.poi.street : ""; //storing user poi address
4681 if (leg.poi.address && item.id == -1) {
4682 item.address = leg.poi.address;
4683 }
4684
4685 // waypoints
4686 //item
4687 item.waypoints = leg.poi.waypoints ? leg.poi.waypoints : [];
4688 item.waypoints = item.waypoints.map(function (curElement, index) {
4689 if ($.type(curElement.lat) == "function") {
4690 return {
4691 lat: curElement.lat().toString(),
4692 lon: curElement.lon().toString()
4693 };
4694 } else {
4695 return curElement;
4696 }
4697
4698 });
4699 if (item.lat == 0 || isNaN(item.lat) || item.lon == 0 || isNaN(item.lon)) {
4700 alert("Can't save this trip because stop #" + i + " \"" + item.poiName + "\" stop has invalid coordinates. Please remove and add this stop again.");
4701 return;
4702 }
4703
4704 item.place_id = leg.poi.place_id || '';
4705 item.poi_type_image = leg.poi.poi_type_image || '';
4706 item.poi_map_icon = leg.poi.poi_map_icon;
4707 if (item.place_id) {
4708 item.place_rating = leg.poi.rating;
4709 item.place_price_level = leg.poi.price_level;
4710 if (leg.poi.photos && leg.poi.photos.length > 0) {
4711 if (leg.poi.photos[0].getUrl) {
4712 item.place_photo_url = leg.poi.photos[0].getUrl({
4713 'maxWidth': 100,
4714 'maxHeight': 100
4715 });
4716 } else {
4717 item.place_photo_url = leg.poi.photos[0].small_url;
4718 }
4719 }
4720 }
4721 item.arrival = leg.poi.arrival;
4722 item.depart = leg.poi.depart;
4723
4724 // If we're saving a Google place, this ID needs to be 0
4725 if (item.place_id) {
4726 item.poiId = 0;
4727 }
4728
4729 routeDetails.push(item);
4730 }
4731 var routeDetailStr = JSON.stringify(routeDetails);
4732 var tripStartDate = curRoute.startDate.getUTCFullYear() + "-" + (curRoute.startDate.getMonth() + 1) + "-" + curRoute.startDate.getDate();
4733 var tripUpdateDate = curRoute.updateDate;
4734 var tripNotes = curRoute.notes;
4735 //var sharedID = curRoute.sharedID;
4736
4737 // another check to make sure a race condition hasn't occured and the data about to be saved is going to be put into the wrong spot in the db
4738 if (tripName != curRoute.name) {
4739 return;
4740 }
4741 if (!nameChanged || beforeSaveName == null || beforeSaveName == "") {
4742 beforeSaveName = tripName;
4743 }
4744 clearHighlightedRoute();
4745 if (curRoute.dragEnable == false) {
4746 highlightRoute();
4747 }
4748 $.ajax({
4749 type: "POST",
4750 ws: "save_trip",
4751 data: {
4752 trip_original_name: beforeSaveName,
4753 trip_miles: miles,
4754 trip_name: tripName,
4755 trip_info: routeDetailStr,
4756 trip_id: tripId,
4757 trip_start_date: tripStartDate,
4758 trip_last_update: tripUpdateDate,
4759 trip_notes: tripNotes,
4760 //shared_from_id: sharedID,
4761 trip_user_id: $("#trip_user_id").val(),
4762 is_drag_route: curRoute.dragEnable,
4763 force_save: forceSave
4764 },
4765 success: function success(res) {
4766 beforeSaveName = tripName;
4767 if (!handleAjaxError(res)) {
4768 if (res.errMsg && res.errMsg === "demo session timeout") {
4769 demouUserService.sessionEnd();
4770 }
4771 return;
4772 }
4773
4774 // How could there not be a curRoute? We access items of curRoute above^^
4775 if (curRoute) {
4776 // Update last update time stamp
4777 curRoute.updateDate = res.last_update;
4778
4779 $("#hdnTripId").val(res.trip_id);
4780 PageState.addTrip(res.trip_id);
4781 if ($("#trip-select option[value=\"" + res.trip_id + "\"]").length < 1) {
4782 var $option = $("<option></option>");
4783 $option.val(res.trip_id);
4784 $option.text(tripName);
4785 $(".rv-search").val(tripName);
4786 }
4787 }
4788 getTrips();
4789 },
4790 error: function error(request, status, _error) {
4791 alert("Failed to Save Trip!");
4792 },
4793 complete: function complete(xhr, textStatus) {
4794 progressBarService.stop();
4795 if (callback) {
4796 callback(textStatus == "success");
4797 }
4798 }
4799 });
4800 }
4801
4802 $(".aside-right").on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
4803
4804 if (!$(this).hasClass("desk-visible-right")) {
4805 $(".nav-right").addClass("initial-hidden");
4806 }
4807 });
4808
4809 $("#sidebar").on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
4810 if (HighchartService.chart) {
4811 ElevationSection.recalculateElevationSize();
4812 }
4813 });
4814
4815 $("#filter-sidebar").on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
4816 if (HighchartService.chart && e && e.originalEvent && e.originalEvent.propertyName == "left") {
4817 ElevationSection.recalculateElevationSize();
4818 }
4819
4820 });
4821
4822
4823 // $("#collapse-tiny-filter-nav").click(function(){
4824 // $(".aside-right").removeClass("initial-hidden");
4825 // })
4826
4827 function loadSelectedTrip(trip_id, doNotFitBounds, showDemoTrip) {
4828 // Close research tab
4829 // $.each(arrMarkers, function(index, marker){
4830 // marker.setMap(null);
4831 // delete marker;
4832 // })
4833 RouteTable.removeAllPois();
4834 if ($(window).width() < 1200) {
4835 $("#toggle-map-view-tiny").trigger("click");
4836 } else {
4837 if ($(".aside-right").hasClass("desk-visible-right")) {
4838 expandOrHideFilterBar();
4839 }
4840 }
4841 // close elevation div if open
4842 closeElevation();
4843 if (plotZoom) {
4844 clearRoutesOverlays();
4845 google.maps.event.removeListener(plotZoom);
4846 plotZoom = "";
4847 }
4848 if ($("aside").hasClass("visible")) {
4849 $(".toggle-side-bar-container button").trigger("click");
4850 }
4851
4852 $('#loader-modal').modal('show');
4853 $('.complete-text').hide();
4854 $(".load-item").removeClass("loaded loading").addClass("not-loading");
4855 $("#first-load-item").removeClass("not-loading").addClass("loading");
4856 progressBarService.start();
4857 return $.ajax({
4858 ws: "get_data",
4859 data: {
4860 action: "getTripDetails",
4861 trip_user_id: $("#trip_user_id").val(),
4862 trip_id: trip_id,
4863 demo_trip: showDemoTrip
4864 },
4865 success: function success(res) {
4866 beforeSaveName = res.data.route_basic.route_name;
4867 $("#first-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
4868 $("#second-load-item").removeClass("not-loading").addClass("loading");
4869 $(".menu-navbar-option").removeClass("no-clicks");
4870 // $(".aside-right").removeClass("initial-hidden")
4871 if (!handleAjaxError(res)) {
4872 return;
4873 }
4874
4875 $('.rv-search-empty-container').hide();
4876
4877 PageState.addTrip(trip_id);
4878 OpenTripGeo(res.data, doNotFitBounds);
4879
4880 lockMapService.tryLockIfNoRoutes(curRoute);
4881 startLoadPoi();
4882 },
4883 error: function () {
4884 $('#loader-modal').modal('hide');
4885 },
4886 complete: function () {
4887
4888 setTimeout(progressBarService.stop, 4000);
4889 if (disableCgPoiLoading) {
4890 if (debug) console.log("here');");
4891 }
4892 }
4893 });
4894 }
4895
4896 function OpenTripGeo(userTrip, doNotFitBounds) {
4897 curSelItemIndex = null;
4898 clearRoutesOverlays();
4899 var tripInfo = userTrip.route_basic;
4900 var tripDetl = userTrip.route_detl;
4901
4902 if (!tripInfo) {
4903 return;
4904 }
4905 // setting route
4906 initRoute();
4907 curRoute.name = tripInfo.route_name;
4908 curRoute.archived = tripInfo.archived;
4909
4910 if (!curRoute.name) {
4911 $('.rv-search-empty-container').show();
4912 }
4913
4914 if (curRoute.archived == 1) {
4915 $(".rv-search").val(curRoute.name + " (Archived)");
4916 } else {
4917 $(".rv-search").val(curRoute.name);
4918 }
4919 curRoute.startDate = new Date(tripInfo.start_date);
4920 curRoute.notes = tripInfo.notes;
4921 curRoute.archived = tripInfo.archived;
4922 curRoute.updateDate = tripInfo.last_update;
4923 curRoute.dragEnable = isDragEnabled;
4924 if (curRoute.dragEnable) {
4925 $(".map-header-btn-drag-route").addClass("active");
4926 }
4927 $("#hdnTripId").val(tripInfo.id);
4928 var tripPois = [];
4929 var bound = new google.maps.LatLngBounds();
4930 // add campgrounds
4931 var save = 0;
4932 if (tripDetl && tripDetl.length > 0 && !tripDetl[0].arrival_date) {
4933 //If dates are not already stored
4934 //For trips already in the database
4935 //console.log("DID NOT LOAD FROM DATABASE");
4936 calculateInitialDates(curRoute.startDate, tripDetl);
4937 save = 1;
4938 }
4939
4940 for (var j = 0; j < tripDetl.length; j++) {
4941 var tripPoi = tripDetl[j];
4942 var poi = {
4943 id: parseInt(tripPoi.id),
4944 lat: parseFloat(tripPoi.lat),
4945 lon: parseFloat(tripPoi.lon),
4946 name: tripPoi.name,
4947 nights: parseInt(tripPoi.nights, 10),
4948 arrival: tripPoi.arrival_date,
4949 depart: tripPoi.departure_date,
4950 comments: tripPoi.poi_comments,
4951 waypoints: tripPoi.waypoints,
4952 cost: parseFloat(tripPoi.poi_cost),
4953 costCamping: parseFloat(tripPoi.poi_cost_camping),
4954 costMeals: parseFloat(tripPoi.poi_cost_meals),
4955 costMisc: parseFloat(tripPoi.poi_cost_misc),
4956 fuelCpg: j !== 0 ? parseFloat(tripPoi.poi_cost_fuel_cpg) : 0,
4957 fuelRemaining: tripPoi.fuel_remaining ? parseFloat(tripPoi.fuel_remaining) : null,
4958 fuelAdded: tripPoi.fuel_added ? parseFloat(tripPoi.fuel_added) : null,
4959 reservationNum: tripPoi.reservation_num,
4960 features: tripPoi.features,
4961 poitype_id: tripPoi.poitype_id,
4962 poi_place_id: tripPoi.poi_place_id,
4963 place_id: tripPoi.poi_place_id,
4964 poi_type_image: tripPoi.poi_type_image,
4965 poi_map_icon: tripPoi.poi_map_icon,
4966 poi_type: tripPoi.poi_type,
4967 rating: tripPoi.rating,
4968 address: tripPoi.poi_address
4969 };
4970 if (poi.place_id && poi.place_id.length > 0) {
4971 if (tripPoi.places_price_level) {
4972 poi.price_level = tripPoi.places_price_level;
4973 }
4974 if (tripPoi.places_photo_url) {
4975 poi.photos = [{
4976 small_url: tripPoi.places_photo_url
4977 }];
4978 }
4979 if (tripPoi.places_rating) {
4980 poi.rating = tripPoi.places_rating;
4981 }
4982 }
4983
4984 if (tripPoi.nights && parseInt(tripPoi.nights) > 0 && (isNaN(tripPoi.poi_cost_camping) || tripPoi.poi_cost_camping == null)) {
4985 // hack to fix corrupt cost campigns
4986 poi.costCamping = userProfile.camping * tripPoi.nights;
4987 }
4988
4989 poi.isFuelRemainingCustom = poi.fuelRemaining !== null;
4990 // backward compability code. we have run script set poi.costFuelCpg==-1 for old trip
4991 if (poi.fuelCpg == -1) {
4992 // setting up by default value
4993 poi.fuelCpg = userProfile.cpg;
4994 poi.costCamping = poi.nights * userProfile.camping;
4995 poi.costMeals = poi.nights * userProfile.meals;
4996 poi.costMisc = poi.nights * userProfile.misc;
4997 poi.cost = -1; // need to calculate during open trip
4998 }
4999
5000 if (poi.poitype_id == undefined) {
5001 poi.poiCat = PoiCat.USER;
5002 } else if (poi.id != -1) {
5003 poi.poiCat = PoiCat.BASIC;
5004 poi.price = tripPoi.price;
5005 poi.affil = tripPoi.affil;
5006 poi.membership = tripPoi.membership;
5007 poi.street = tripPoi.street;
5008 poi.city = tripPoi.city;
5009 poi.state = tripPoi.state;
5010 poi.zip = tripPoi.zip;
5011 poi.phone = tripPoi.phone;
5012 poi.email = tripPoi.email;
5013 poi.imageName = tripPoi.imageName;
5014 poi.url = tripPoi.url;
5015 } else {
5016 poi.poiCat = PoiCat.USER;
5017 }
5018
5019 bound.extend(new google.maps.LatLng(poi.lat, poi.lon));
5020 if (debug) console.log('Stop: ' + poi.name + ' - ' + poi.poiCat);
5021 if (poi.poiCat == PoiCat.USER) {
5022
5023 //image sequence for user poi. Not applicable for start poi.
5024 poi.imageName = customImageName(poi);
5025 }
5026 if (j == 0) {
5027 //create own poi marker
5028 //poi.marker = getMarker(poi);
5029
5030 if (!doNotFitBounds) {
5031 updateMapCenter(new google.maps.LatLng(poi.lat, poi.lon), _global.map.zoom.end);
5032 } else {
5033 reallyDoSearch();
5034 }
5035 genRouteListing();
5036 resetNonOverNightPoiList();
5037 }
5038 tripPois.push(poi);
5039 }
5040
5041 $("#second-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
5042 if (!doNotFitBounds && tripDetl.length > 1) {
5043 map.fitBounds(bound);
5044 }
5045
5046
5047 /*
5048 // This code is calling the places APi for each custom stop. Needs to be refactored to not need to do this.
5049 var poi;
5050 for(var i = 0; i < tripPois.length; i++) {
5051 var poi = tripPois[i];
5052 if (poi.place_id && poi.place_id.length > 0) {
5053 getAttractionDetailsByPoi(poi, placesService);
5054 }
5055 }
5056 */
5057 getImages(tripPois, null, null, true, function (tripPois) {
5058 if (tripPois.length) {
5059 poi.cost = _global.utils.nullOrUndefined(tripPois[0].cost) || tripPois[0].cost == -1 ? routeCostHelper.getStopDayCost(parseInt(tripPois[0].nights), parseInt(userProfile.camping), parseInt(userProfile.meals), parseInt(userProfile.misc)) : parseInt(tripPois[0].cost);
5060 }
5061
5062 //Call recursive to add poi to route plan
5063 callBlockUI();
5064 if (save) {
5065 addPoisToRoute(tripPois, true);
5066 } else {
5067 addPoisToRoute(tripPois, false);
5068 }
5069 //addPoisToRoute(tripPois, false);
5070 });
5071 }
5072
5073 function calculateInitialDates(startDate, tripDetl) {
5074 for (var i = 0; i < tripDetl.length; i++) {
5075 var arrivalDate;
5076 var departureDate;
5077 if (i == 0) {
5078 arrivalDate = new Date(startDate);
5079 departureDate = new Date(startDate);
5080 departureDate.setDate(startDate.getDate() + parseInt(tripDetl[i].nights, 10));
5081 } else {
5082 arrivalDate = new Date(tripDetl[i - 1].departure_date);
5083 departureDate = new Date(tripDetl[i - 1].departure_date);
5084 departureDate.setDate(arrivalDate.getDate() + parseInt(tripDetl[i].nights, 10));
5085 }
5086 tripDetl[i].arrival_date = arrivalDate;
5087 tripDetl[i].departure_date = departureDate;
5088 }
5089 }
5090
5091 // move to route table
5092
5093 function recalculateDates(curRoute) {
5094 var startDate = new Date(curRoute.startDate);
5095 var arrivalDate;
5096 var departureDate;
5097 for (var i = 0; i < curRoute.routeLegs.length; i++) {
5098 var leg = curRoute.routeLegs[i];
5099 if (i == 0) {
5100 arrivalDate = new Date(startDate);
5101 departureDate = new Date(startDate);
5102 departureDate.setDate(startDate.getDate() + parseInt(leg.poi.nights, 10));
5103 } else {
5104 var lastStop = curRoute.routeLegs[i - 1];
5105 arrivalDate = new Date(lastStop.poi.depart);
5106 departureDate = new Date(lastStop.poi.depart);
5107 departureDate.setDate(arrivalDate.getDate() + parseInt(leg.poi.nights, 10));
5108 }
5109 leg.poi.arrival = arrivalDate;
5110 leg.poi.depart = departureDate;
5111 }
5112 }
5113
5114 // end move
5115
5116 function generateFetchRouteRequest(pois, prevLat, prevLon) {
5117 var xpois = [];
5118 if (pois && pois.length > 0) {
5119 $.each(pois, function (key, poi) {
5120 if (poi.waypoints && poi.waypoints[0] && poi.waypoints[0].lat == "") {
5121 poi.waypoints = [];
5122 }
5123 xpois[key] = {
5124 prevlat: prevLat,
5125 prevlon: prevLon,
5126 lat: poi.lat,
5127 lon: poi.lon,
5128 waypoints: poi.waypoints,
5129 nights: poi.nights
5130 };
5131
5132 prevLat = poi.lat;
5133 prevLon = poi.lon;
5134 });
5135 }
5136 fetchRouteRequest = {
5137 pois: xpois,
5138 avoidHighways: userProfile.avoid_major_highways === "1",
5139 avoidTolls: userProfile.avoid_tolls === "1",
5140 avoidFerries: userProfile.avoid_ferries === "1",
5141 startDate: (curRoute && curRoute.startDate) ?
5142 curRoute.startDate.toISOString() : (new Date()).toISOString()
5143 };
5144 }
5145
5146
5147 function addPoisToRoute(pois, needToSave, forceSave, index, callback) {
5148 //set the elevation button on load
5149 closeElevation();
5150 if ($('#mapContainer').parent().width() > 1200) {
5151 $("#desktopChartbtns").css("display", "inline-block");
5152 if ($('#sidebar').hasClass("desk-visible")) {
5153 var newLeft = $("#sidebar").css("width");
5154 $('#desktopChartbtns').css('margin-Left', newLeft);
5155 } else {
5156 $("#desktopChartbtns").css("left", 0);
5157 }
5158 } else {
5159 $("#elevation_wrapper").css("display", "none");
5160 }
5161
5162
5163
5164 if (pois.length == 0) {
5165 $("#third-load-item").removeClass("not-loading").addClass("loaded").find(".complete-text").show();
5166 $("#fourth-load-item").removeClass("not-loading").addClass("loaded").find(".complete-text").show();
5167 $("#fifth-load-item").removeClass("not-loading").addClass("loaded").find(".complete-text").show();
5168 checkLoadingModal();
5169 } else {
5170 $("#third-load-item").removeClass("not-loading").addClass("loading");
5171 }
5172 var firstPoi;
5173 if (curRoute.routeLegs.length < 1 && pois.length > 0) {
5174 firstPoi = pois[0];
5175 firstPoi.cost = _global.utils.nullOrUndefined(firstPoi.cost) || firstPoi.cost == -1 ? routeCostHelper.getStopDayCost(parseInt(firstPoi.nights), parseInt(userProfile.camping), parseInt(userProfile.meals), parseInt(userProfile.misc)) : parseInt(firstPoi.cost);
5176 firstPoi.distance = 0;
5177 firstPoi.time = '';
5178 firstPoi.poiCat = firstPoi && firstPoi.poiCat !== undefined ? firstPoi.poiCat : PoiCat.USER;
5179 firstPoi.name = firstPoi.name ? firstPoi.name : firstPoi.address;
5180 rvTripHelper.setPoiExtendedProperties(firstPoi);
5181
5182 curRoute.routeLegs.push({
5183 poi: firstPoi,
5184 start: new google.maps.LatLng(firstPoi.lat, firstPoi.lon),
5185 end: new google.maps.LatLng(firstPoi.lat, firstPoi.lon),
5186 directionsDisplay: null
5187 });
5188
5189 pois.splice(0, 1);
5190 if (pois.length == 0) {
5191 $("#third-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
5192 }
5193 }
5194
5195 manyTripDirections = [];
5196 var xpois = [];
5197 if (curRoute.routeLegs.length > 0 && pois.length > 0) {
5198
5199 firstPoi = curRoute.routeLegs[0].poi;
5200 var prevLat = firstPoi.lat;
5201 var prevLon = firstPoi.lon;
5202
5203 generateFetchRouteRequest(pois, prevLat, prevLon);
5204 progressBarService.start();
5205 console.log(fetchRouteRequest);
5206 // do it here...
5207 $.ajax({
5208 type: "POST",
5209 ws: "fetch_route",
5210 dataType: "json",
5211 data: fetchRouteRequest,
5212 success: function success(res) {
5213 if (!handleAjaxError(res)) {
5214 return;
5215 }
5216 console.log("this one 2");
5217 console.log(res);
5218 MapsController.incrementRoutingDirectionsCounter(res.total_google);
5219 var counter = 0;
5220 $.each(res.data, function (key, stop) {
5221 if (index && counter != index) {
5222 counter += 1;
5223 return true;
5224 } else {
5225 counter += 1;
5226 }
5227 poi = pois[key];
5228 // ONE PIECE OF THE PUZZLE DECODED, NEXT I HAVE TO GET THE REST TO SUCCESSFULLY BUILD A currentTripDirections
5229 var prevPoi = curRoute.routeLegs[curRoute.routeLegs.length - 1].poi,
5230 start = new google.maps.LatLng(prevPoi.lat, prevPoi.lon),
5231 end = new google.maps.LatLng(poi.lat, poi.lon);
5232
5233 var request = getDirectionsServiceRequest(start, end, poi.waypoints);
5234 var currentTripDirections = {
5235 geocoded_waypoints: stop.geocoded_waypoints, // have this now
5236 routes: typecastRoutes(stop.routes),
5237 request: request
5238 };
5239 manyTripDirections.push(currentTripDirections);
5240
5241 var directionsToDisplay = MapsController.getDirectionsRenderer(currentTripDirections);
5242 poi.distance = rvTripHelper.routeDistance(stop);
5243 poi.time = rvTripHelper.routeTime(stop);
5244 if (_global.utils.nullOrUndefined(poi.cost)) {
5245 // during new trip cost properties is undefined.
5246 // plz note that for getStopCpg(curRoute.routeLegs.length-1) curRoute.routeLegs.length refering current
5247 // stop index. Current poi is not yet added, acutally it is reffering prev poi.
5248 poi.cost = routeCostHelper.routeCost(poi.distance, poi.nights, poi.poiCat, parseInt(userProfile.cpg), parseInt(userProfile.camping), parseInt(userProfile.meals), parseInt(userProfile.misc));
5249 } else {
5250 if (poi.cost === -1) {
5251 // poi cost setted to -1 for old trip.
5252 poi.cost = routeCostHelper.getStopFuelCost(poi.distance) + ( // fuel cost
5253 parseInt(poi.costCamping) + parseInt(poi.costMeals) + parseInt(poi.costMisc)); // usefull for old custom cost
5254 }
5255 }
5256
5257 var newPoi = $.extend(true, {}, poi); //for both cg and noncg poi but not user poi
5258 if (index) {
5259 curRoute.routeLegs.splice(index, 0, {
5260 poi: newPoi,
5261 start: start,
5262 end: end,
5263 directionsDisplay: directionsToDisplay,
5264 directionsServiceResult: stop
5265 });
5266 } else {
5267 curRoute.routeLegs.push({
5268 poi: newPoi,
5269 start: start,
5270 end: end,
5271 directionsDisplay: directionsToDisplay,
5272 directionsServiceResult: stop
5273 });
5274 }
5275 newPoi.marker = getLegPoiMarker(poi);
5276 if (newPoi.marker) {
5277 newPoi.marker.setMap(map);
5278 newPoi.marker.setVisible(true);
5279 newPoi.marker.setAnimation(null);
5280 }
5281
5282 if (newPoi.costCamping || newPoi.costMeals || newPoi.costMisc) {
5283 newPoi.cost = (parseInt(newPoi.costCamping) || 0) + (parseInt(newPoi.costMeals) || 0) + (parseInt(newPoi.costMisc) || 0);
5284 } else {
5285 newPoi.cost = routeCostHelper.getStopDayCost(newPoi.nights, newPoi.costCamping, newPoi.costMeals, newPoi.costMisc);
5286 }
5287 newPoi.cost = parseInt(newPoi.cost) + routeCostHelper.getStopFuelCost(newPoi.distance, (newPoi.fuelCpg ? newPoi.fuelCpg : undefined));
5288
5289 rvTripHelper.setPoiExtendedProperties(newPoi);
5290 if (curUserPoiMarker) {
5291 curUserPoiMarker.setMap(null);
5292 }
5293 });
5294
5295
5296 if (needToSave) {
5297 SaveTrip(null, forceSave);
5298 } else {
5299 progressBarService.stop();
5300 }
5301 genRouteListing();
5302 clearAfterAddToRoute();
5303
5304 if (demouUserService.isDemoUser && !hasShownTour) {
5305 startTour();
5306 }
5307 curRoute.routeLegs[0].poi.marker = getLegPoiMarker(curRoute.routeLegs[0].poi);
5308 curRoute.routeLegs[0].poi.marker.setMap(map);
5309 curRoute.routeLegs[0].poi.marker.first = true;
5310
5311 checkLoadingModal();
5312 if (callback) {
5313 callback();
5314 }
5315 },
5316 error: function error(x, y, z) {
5317 // resetTripWizard();
5318 alert("Failed to load trip, please try opening the trip again.");
5319 },
5320 complete: function () {
5321 $("#third-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
5322 if (curRoute.dragEnable == false) {
5323 highlightRoute();
5324 }
5325 checkLoadingModal();
5326 if (curRoute && curRoute.routeLegs.length > 0) {
5327 rvTripHelper.drawDriveCircle(curRoute.routeLegs[curRoute.routeLegs.length - 1].poi);
5328 rvTripLC.showOverlayLC();
5329 }
5330 },
5331 timeout: 100000
5332 });
5333 } else if (curRoute.routeLegs.length > 0 && pois.length < 1) {
5334 curRoute.routeLegs[0].poi.marker = getLegPoiMarker(curRoute.routeLegs[0].poi);
5335 curRoute.routeLegs[0].poi.marker.setMap(map);
5336 curRoute.routeLegs[0].poi.marker.first = true;
5337 }
5338
5339 genRouteListing();
5340 if (((curRoute.routeLegs.length === 0 || pois.length === 0) && needToSave)) {
5341 SaveTrip(null, forceSave);
5342 }
5343 rvTripLC.showOverlayLC();
5344 fuelCalculator.overlayFuelWarning();
5345 callUnBlockUI();
5346 redrawingRoute = false;
5347 }
5348
5349 var redrawingRoute = false;
5350
5351 function redrawPoiRoute(needToSave, forceSave) {
5352 $(".popover").fadeOut();
5353 if (plotZoom) {
5354 google.maps.event.removeListener(plotZoom);
5355 }
5356 closeElevation();
5357 if (curRoute.routeLegs.length > 0 && !redrawingRoute) {
5358 redrawingRoute = true;
5359 clearRoutesOverlays();
5360 var newRoute = _global.utils.extend(curRoute),
5361 newRouteLegs = newRoute.routeLegs,
5362 _pois = newRouteLegs.map(function (leg) {
5363 return leg.poi;
5364 });
5365
5366 Object.assign(curRoute, {
5367 routeLegs: [],
5368 status: true
5369 });
5370
5371 clearStartMarker();
5372 firstPoi.cost = routeCostHelper.getStopDayCost(parseInt(firstPoi.nights), parseInt(userProfile.camping), parseInt(userProfile.meals), parseInt(userProfile.misc));
5373 setMapBoundToTrip(newRouteLegs);
5374 callBlockUI();
5375 addPoisToRoute(_pois, needToSave, forceSave);
5376 }
5377 }
5378
5379 function redrawPoiRouteNoReFocus(needToSave, forceSave) {
5380 $(".popover").fadeOut();
5381 if (curRoute.routeLegs.length > 0 && !redrawingRoute) {
5382 redrawingRoute = true;
5383 clearRoutesOverlays();
5384 var newRoute = _global.utils.extend(curRoute),
5385 newRouteLegs = newRoute.routeLegs,
5386 _pois = newRouteLegs.map(function (leg) {
5387 return leg.poi;
5388 });
5389 // firstPoi = _pois.shift();
5390
5391 Object.assign(curRoute, {
5392 routeLegs: [],
5393 status: true
5394 });
5395
5396 clearStartMarker();
5397 firstPoi.cost = routeCostHelper.getStopDayCost(parseInt(firstPoi.nights), parseInt(userProfile.camping), parseInt(userProfile.meals), parseInt(userProfile.misc));
5398 callBlockUI();
5399 addPoisToRoute(_pois, needToSave, forceSave);
5400 }
5401 }
5402
5403 function getMarkerIcon(poi) {
5404 if (debug) console.log('Get Marker Icon - ' + poi.id);
5405 return {
5406 url: getMarkerImage(poi),
5407 scaledSize: new google.maps.Size(24, 30)
5408 };
5409 }
5410
5411 function getMarkerImage(poi) {
5412 var imageFile = "";
5413 //If the poi type image is defined, parse the route and return that
5414 if (!!poi.poi_type_image) {
5415 return getMarkerImageCustomPoiTypeImage(poi.poi_type_image);
5416 }
5417 if (typeof poi.imageName === 'undefined') {
5418 imageFile = customImageName(poi);
5419
5420 } else if (poi.poiCat === PoiCat.USER) {
5421 poi.imageName = poi.imageName.replace(markerImagePath, '');
5422 poi.imageName = poi.imageName.replace(/^\/+/g, '');
5423 imageFile = markerImagePath + "/" + poi.imageName;
5424 } else {
5425 if (poi.imageName && poi.imageName !== "-1") {
5426 if (poi.imageName.substring(0, markerImagePath.length) == markerImagePath) {
5427 imageFile = poi.imageName;
5428 } else {
5429 imageFile = markerImagePath + "/" + poi.imageName;
5430 }
5431 } else {
5432 imageFile = clusterImageName;
5433 }
5434 }
5435
5436 //Last fallback...
5437 if (imageFile === 'Default.png') {
5438 imageFile = customImageName();
5439 }
5440
5441 if (debug) console.log('Returning Marker Image - ' + imageFile);
5442 return imageFile;
5443 }
5444
5445 function getMarkerImageCustomPoiTypeImage(imagePath) {
5446 var imageFile = "";
5447
5448 if (imagePath.indexOf('images/marker_img') === -1) {
5449 imageFile = markerImagePath + "/" + imagePath;
5450 } else {
5451 imageFile = imagePath;
5452 }
5453
5454 if (debug) console.log('Returning Marker Image Custom - ' + imageFile);
5455 return imageFile;
5456 }
5457
5458 function getCgPoiById(id) {
5459 if (!fusionData) return null;
5460 pois = fusionData.poi;
5461 for (var i = 0; i < pois.length; i++) {
5462 var temPoi = pois[i];
5463 if (temPoi) {
5464 if (temPoi.id == id) return temPoi;
5465 }
5466 }
5467 return null;
5468 }
5469
5470 function setMapBoundToTrip(legs) {
5471 if (legs.length >= 1) {
5472 (function () {
5473 var bound = new google.maps.LatLngBounds();
5474 legs.forEach(function (leg) {
5475 return bound.extend(new google.maps.LatLng(leg.poi.lat, leg.poi.lon));
5476 });
5477 if (bound) {
5478 map.fitBounds(bound);
5479 }
5480 })();
5481 }
5482 }
5483
5484 function callBlockUI() {
5485 blockUICount++;
5486
5487 var isAlreadyVisible = document.querySelector("#block-ui").classList.contains('visible');
5488 if (!isAlreadyVisible) {
5489 document.querySelector("#block-ui").classList.add("visible");
5490 }
5491 }
5492
5493 function callUnBlockUI() {
5494 blockUICount--;
5495 if (blockUICount < 1) {
5496 document.querySelector("#block-ui").classList.remove("visible");
5497 }
5498 }
5499 var timerClick = null;
5500
5501 function tripItemClick(index) {
5502 placesNearBy.clearPlacesMarker();
5503 if (!_global.utils.nullOrUndefined(index)) {
5504 if (timerClick) {
5505 clearTimeout(timerClick);
5506 timerClick = null;
5507 }
5508 timerClick = setTimeout(function () {
5509 var poi = curRoute.routeLegs[index].poi;
5510 curSelItemIndex = index;
5511 updateMapCenter(new google.maps.LatLng(poi.lat, poi.lon), _global.numberMarkerZoom);
5512 if (poi.poiCat === PoiCat.BASIC) {
5513 genPoiDetails(poi, PoiDetailsClickSource.TRIP_POI_LIST);
5514 }
5515 if (poi.marker) {
5516 if (!rvTripHelper.isDevice()) {
5517 getDistanceAndShowInInfoBox(poi);
5518 showMarkerInfoBox(poi, poi.marker, poi.id === 0 || poi.id === undefined);
5519 }
5520 }
5521 rvTripHelper.drawDriveCircle(poi);
5522 }, 250);
5523 }
5524 }
5525
5526
5527 $(".add-to-trip-form input[type=number]").on("keypress", function (event) {
5528 showTwoDecimals($(this));
5529 });
5530
5531 function showTwoDecimals(node) {
5532 var $this = node;
5533
5534 if ($this.attr("step") && $this.attr("step") == "0.01") {
5535
5536 setTimeout(function () {
5537 if ($this.val().substring($this.val().indexOf('.')).length > 2 && $this.val().indexOf('.') != -1) {
5538 var value = Number($this.val()).toFixed(2);
5539 $this.val(value);
5540 }
5541 }, 1);
5542 }
5543 }
5544
5545
5546
5547 function setFilterResuts(data) {
5548 if (debug) console.log(data);
5549 $("#filter-results > div").empty();
5550
5551 data.map(function (poi) {
5552 return Object.assign(Object.create(null), poi, {
5553 address: _global.getFormattedAddressShort({
5554 city: poi.city,
5555 state: poi.state
5556 }).replace(/,/gi, "")
5557 });
5558 }).forEach(function (poi) {
5559 delete poi.marker;
5560 $("#filter-results > div").append("<a></a>");
5561 $("#filter-results > div a:last").text(poi.name).on("click", function (event) {
5562
5563 event.preventDefault();
5564 var data = JSON.parse(event.target.dataset.data),
5565 markerData = Object.assign({
5566 street: data.street,
5567 zip: data.zip,
5568 lat: data.lat,
5569 lon: data.lon,
5570 photos: data.photos,
5571 rating: data.rating
5572 }, data),
5573 position = new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lon)),
5574 marker = new google.maps.Marker({
5575 position: position,
5576 map: map,
5577 visible: false
5578 });
5579
5580 genPoiDetails(poi, PoiDetailsClickSource.MAP);
5581 showMarkerInfoBox(poi, marker);
5582 updateMapCenter2(data.lat, data.lon, 16);
5583 })[0].dataset.data = JSON.stringify(poi);
5584 $("#filter-results").removeClass("hidden");
5585 });
5586 }
5587 var favs;
5588 var currentPrefProp = false;
5589
5590 $("#open-edit-profile-modal").click(function () {
5591 EditProfileModal.showModal();
5592 });
5593
5594 $(".poi-container button").on("click", function (event) {
5595 if ((map.getZoom() < _global.map.zoom.end) && alreadyLoaded) {
5596 /* Don't allow users to toggle filters while too far zoomed out */
5597 notificationService.show(_global.msg.zoomInToShowPoi);
5598 return;
5599 }
5600
5601 $(this).toggleClass('selected');
5602 $(this).children('span').toggleClass('selected');
5603
5604 var _this = $(this);
5605 if ($(this).hasClass('selected')) {
5606 addFilterItem($(_this).children('span').text(), _this, "");
5607 } else {
5608 var tempa = $('.footer-buttons-poi').children().find('span:contains("' + _this.children('span').text() + '")');
5609 filterCount -= 1;
5610 $(tempa).parent().remove();
5611 $('footer-buttons-poi').remove(tempa.parent());
5612 }
5613
5614 checkFilterBar();
5615 updatePOIFooter();
5616 saveTopPois();
5617
5618 var poiContainerFilter = $(".poi-container-filter");
5619
5620 if ($('.poi-container button').hasClass('selected') && (filterValues.fuel || filterValues.rest || filterValues.overnight || filterValues.dump)) {
5621 poiContainerFilter.removeClass("red-bar").addClass("green-bar");
5622 } else {
5623 poiContainerFilter.removeClass("green-bar").addClass("red-bar");
5624 }
5625 clickPoiChkBox(this, this.value);
5626 });
5627
5628 function updatePOIFooter() {
5629 if (filterCount == 0) {
5630 $('.add-pois').removeClass('selected');
5631 $('.add-pois-button-text').removeClass('selected');
5632 $('.add-pois').children('span').text('Add POI');
5633 $('.clear-pois').addClass('hidden');
5634 } else if (filterCount == 1) {
5635 $('.add-pois').addClass('selected');
5636 $('.add-pois-button-text').addClass('selected');
5637 // $('.add-pois').children('span').text('POI Types (' + filterCount + ')');
5638 if (debug) console.log("GO BIRDS");
5639 if ($('.footer-buttons-poi').css('display') == 'none') {
5640 $('.add-pois').children('span').html('POI Types (' + filterCount + ') <img src="images/filters-up.svg">');
5641 } else {
5642 $('.add-pois').children('span').html('POI Types (' + filterCount + ') <img src="images/filters-down.svg">');
5643 }
5644 $('.clear-pois').removeClass('hidden');
5645 } else if (filterCount > 1) {
5646 $('.add-pois').children('span').text('POI Types (' + filterCount + ')');
5647 if ($('.footer-buttons-poi').css('display') == 'none') {
5648 $('.add-pois').children('span').html('POI Types (' + filterCount + ') <img src="images/filters-up.svg">');
5649 } else {
5650 $('.add-pois').children('span').html('POI Types (' + filterCount + ') <img src="images/filters-down.svg">');
5651 }
5652 }
5653 }
5654
5655 radiusChange = function () {
5656 var innerRadius = $("#driving_inner_radius");
5657 var middleRadius = $("#driving_middle_radius");
5658 var perDayMiles = $("#driving_per_day_amount_miles");
5659 var perDayHours = $("#driving_per_day_amount_hours");
5660 var drivingAds = $("#driving_ads");
5661 var med = middleRadius.val();
5662 var inn = innerRadius.val();
5663 var mil = perDayMiles.val();
5664 var hours = perDayHours.val();
5665 var mph = drivingAds.val();
5666 var miles;
5667 if ($("#milesperday").is(":checked")) {
5668 miles = mil;
5669 perDayMiles.prop('required', true).attr('min', 1);
5670 } else {
5671 perDayMiles.removeAttr('required').attr('min', 0);
5672 }
5673
5674 if ($("#hoursperday").is(':checked')) {
5675 miles = hours * mph;
5676 drivingAds.prop('required', true);
5677 perDayHours.prop('required', true).attr('min', 1);
5678 } else {
5679 drivingAds.removeAttr('required');
5680 perDayHours.removeAttr('required').attr('min', 0);
5681 }
5682
5683 if (inn) {
5684 middleRadius.attr("min", inn);
5685 } else {
5686 middleRadius.removeAttr("min");
5687 }
5688 if (med) {
5689 innerRadius.attr("max", med);
5690 } else {
5691 innerRadius.removeAttr("max");
5692 }
5693 innerRadius.attr("min", "0");
5694 middleRadius.attr("max", miles);
5695 };
5696
5697 var switchParam;
5698 if ($(".body").width() > 1200) {
5699 switchParam = 1;
5700 } else {
5701 switchParam = 0;
5702 }
5703
5704
5705 $("#driving").find(".js-radius").on("change", radiusChange);
5706
5707 (function () {
5708 // Messing with prototype, because this code doesn't suck enough...
5709 if (Number.prototype.toRad === void 0) {
5710 Number.prototype.toRad = function () {
5711 return this * Math.PI / 180;
5712 };
5713 }
5714
5715 if (Date.prototype.getMonthNameFull === void 0) {
5716 Date.prototype.getMonthNameFull = function () {
5717 return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][this.getMonth()];
5718 };
5719 }
5720
5721 if (Date.prototype.getMonthName === void 0) {
5722 Date.prototype.getMonthName = function () {
5723 return ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"][this.getMonth()];
5724 };
5725 }
5726 if (Date.prototype.getDayNameFull === void 0) {
5727 Date.prototype.getDayNameFull = function () {
5728 return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][this.getDay()];
5729 };
5730 }
5731
5732 if (Date.prototype.getDayName === void 0) {
5733 Date.prototype.getDayName = function () {
5734 return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][this.getDay()];
5735 };
5736 }
5737
5738 String.prototype.hashCode = function () {
5739 var hash = 0;
5740 if (this.length == 0) {
5741 return hash;
5742 }
5743 for (i = 0; i < this.length; i++) {
5744 hash = ((hash << 5) - hash) + this.charCodeAt(i);
5745 hash &= hash; // Convert to 32bit integer
5746 }
5747 return hash;
5748 };
5749
5750 })();
5751
5752 var sidebar = $("body > main > aside")[0],
5753 filterbar = $("body > main > aside")[1],
5754 searchLocation = $("#search-location")[0],
5755 userId = $("#trip_user_id").val();
5756
5757 // Logout (click on any .logout element)
5758 $(".logout").on("click", function (event) {
5759 var a = this;
5760 event.preventDefault();
5761 $.ajax({
5762 url: a.href,
5763 success: function success() {
5764 location.href = "/members/index.php?page=login&msg=Log+out+successful.";
5765 }
5766 });
5767 });
5768
5769 // Sidebar toggle mobile
5770 $("#toggle-side-bar, #toggle-side-bar-tiny").on("click", function () {
5771 $("img[name=binoculars]").attr("src", "/app/images/binoculars.svg");
5772 $("img[name=pins]").attr("src", "/app/images/pin-copy_red.svg");
5773 $("img[name=map-pin]").attr("src", "/app/images/map-pin.svg");
5774
5775 if ($(".btn-elevation").hasClass('active')) {
5776 $('.btn-elevation').click();
5777 }
5778 if (lockMapService.isLocked()) {
5779 return;
5780 }
5781 if ($("#collapse-tiny-filter-nav").hasClass("active")) {
5782 $(".aside-right").removeClass("desk-visible-right");
5783 $(".aside-right").animate({
5784 "right": "-408px"
5785 }, 200, function () {
5786 $(".nav-right").addClass("initial-hidden");
5787 });
5788 }
5789
5790 if ($("#toggle-side-bar-tiny").hasClass("active")) {
5791 return;
5792 } else {
5793 sidebar.classList.toggle("visible");
5794 }
5795
5796 if (rvTripHelper.isDevice()) {
5797 closeMarkerInfoBox();
5798 }
5799 });
5800
5801 // Sidebar toggle desktop
5802 $("#collapse-side-bar").on("click", expandOrHideSideBar);
5803
5804 //Filterbar toggle desktop
5805 $("#collapse-filter-nav").on("click", expandOrHideFilterBar);
5806 $("#collapse-tiny-filter-nav").on("click", function () {
5807 $(".aside-right").animate({
5808 "right": "0px"
5809 }, 200);
5810 if ($("body").width() < 560) {
5811 $("#poi-form").width($("body").width());
5812 } else {
5813 $("#poi-form").css("width", "408px");
5814 }
5815
5816 // change images
5817 $("img[name=binoculars]").attr("src", "/app/images/binoculars_red.svg");
5818 $("img[name=pins]").attr("src", "/app/images/pin-copy.svg");
5819 $("img[name=map-pin]").attr("src", "/app/images/map-pin.svg");
5820 if ($(".btn-elevation").hasClass('active')) {
5821 $('.btn-elevation').click();
5822 }
5823 if ($("#toggle-side-bar-tiny").hasClass("active")) {
5824 sidebar.classList.toggle("visible");
5825 }
5826 if ($("#collapse-tiny-filter-nav").hasClass("active")) {
5827 return;
5828 } else {
5829
5830 if (debug) console.log($("aside-right").hasClass("desk-visible-right"));
5831 $(".nav-right").removeClass("initial-hidden");
5832 $(".aside-right").removeClass("initial-hidden");
5833 setTimeout(function () {
5834 filterbar.classList.toggle("desk-visible-right");
5835 }, 5);
5836
5837 }
5838 });
5839 $("#toggle-map-view-tiny").on("click", function () {
5840 $("img[name=pins]").attr("src", "/app/images/pin-copy.svg");
5841 $("img[name=binoculars]").attr("src", "/app/images/binoculars.svg");
5842 $("img[name=map-pin]").attr("src", "/app/images/map-pin_red.svg");
5843 if ($("#toggle-side-bar-tiny").hasClass("active")) {
5844 sidebar.classList.toggle("visible");
5845 } else
5846 if ($("#collapse-tiny-filter-nav").hasClass("active")) {
5847 $(".aside-right").removeClass("desk-visible-right");
5848 $(".aside-right").animate({
5849 "right": "-408px"
5850 }, 200, function () {
5851 $(".nav-right").addClass("initial-hidden");
5852 });
5853 }
5854 });
5855
5856 if (sidebar) {
5857 sidebar.addEventListener("click", function (event) {
5858 if (event.offsetX > sidebar.querySelector("nav").offsetWidth) {
5859 sidebar.classList.remove("visible");
5860 $("body > main > aside > .popover").popover("hide");
5861 }
5862 });
5863 }
5864
5865 if (filterbar) {
5866 filterbar.addEventListener("click", function (event) {
5867 if (event.offsetX > filterbar.querySelector("nav").offsetWidth) {
5868 filterbar.classList.remove("visible");
5869 $("body > main > aside > .popover").popover("hide");
5870 }
5871 });
5872 }
5873
5874 // Google Maps autocomplete
5875 // google.maps.event.addListener(autocomplete, "place_changed", function () {
5876 // setUserLocationByAddress(searchLocation.value, false);
5877 //});
5878 $("#search-location-form").on("submit", function (event) {
5879 if (lockMapService.isLocked()) {
5880 return false;
5881 }
5882 event.preventDefault();
5883 setUserLocationByAddress(searchLocation.value, false);
5884
5885 });
5886
5887 // Open trip modal
5888 $(".open-trips").on("click", function () {
5889 if (demouUserService.isDemoUser) {
5890 alert(_global.msg.DemoUserNotAllow);
5891 return;
5892 }
5893 closeElevation();
5894 OpenTripModal.showModal();
5895 });
5896
5897
5898 function getTrips() {
5899 return $.ajax({
5900 tryCount: 0,
5901 retryLimit: 3,
5902 ws: "get_data",
5903 data: {
5904 action: "getTrips",
5905 trip_user_id: userId
5906 },
5907 success: function success(res) {
5908 if (res && res.data) {
5909 if (!handleAjaxError(res)) {
5910 return;
5911 }
5912 OpenTripModal.rebuildTripsList(res);
5913 $(".trips-count").text(OpenTripModal.getTripsListLength());
5914 OpenTripModal.refreshTable();
5915
5916 } else {
5917 this.tryCount++;
5918 if (this.tryCount <= this.retryLimit) {
5919 $.ajax(this);
5920 return;
5921 } else {
5922 alert('problem loading trips, try reloading the page');
5923 }
5924 }
5925 },
5926 error: function error(x, y, z) {
5927 console.log(x, y, z);
5928
5929 this.tryCount++;
5930 if (this.tryCount <= this.retryLimit) {
5931 $.ajax(this);
5932 return;
5933 } else {
5934 alert('problem loading trips, try reloading the page');
5935 }
5936 }
5937 });
5938 }
5939
5940 // Hide popovers on scroll
5941 $(".table-wrapper").on("scroll", function () {
5942 $(".popover:not(.tour-tour)").popover("hide");
5943 });
5944
5945 $(".create-new-trip").on("click", function () {
5946 if (demouUserService.isDemoUser) {
5947 alert(_global.msg.DemoUserNewTrip);
5948 return;
5949 }
5950 NewTripModal.showModal();
5951 });
5952
5953
5954
5955 function initCurRoute(tripName, startDate) {
5956 initRoute();
5957
5958 curRoute.name = tripName;
5959 curRoute.routeLegs = [];
5960 fetchRouteRequest = undefined;
5961 curRoute.dragEnable = false;
5962 startDate = new Date(startDate);
5963 curRoute.startDate = startDate < new Date("2000-01-01") ? startDate.setYear(startDate.getFullYear() + 100) : startDate;
5964 }
5965
5966
5967 // Ugly and hacky way of getting the contact form file token
5968 $.ajax({
5969 url: "/machform/embed.php?id=12",
5970 success: function success(res) {
5971 var loadedDOM = new DOMParser().parseFromString(res, "text/html");
5972 if (loadedDOM.querySelector("#element_5_token")) {
5973 $("#element_5_token").val(loadedDOM.querySelector("#element_5_token").value);
5974 }
5975 }
5976 });
5977
5978
5979 $("#routeList").sortable({
5980 axis: 'y',
5981 containment: 'parent',
5982 items: "tr[data-index]:not([data-index='-1'])",
5983 scroll: true,
5984 scrollSensitivity: 80,
5985 tolerance: 'pointer',
5986 handle: '.drag-handle',
5987 start: function start(event, ui) {
5988 $(".popover:not(.tour-tour)").popover("hide");
5989 RouteTable.setStartIndex(ui.item.index());
5990 updateFiller = false;
5991 ui.placeholder.height(ui.item.height());
5992 $("#routeList").find("tr[data-index]:not([data-index='-1']) td").css({
5993 cursor: "url(https://maps.gstatic.com/mapfiles/openhand_8_8.cur) 8 8, default"
5994 });
5995 return ui;
5996 },
5997 helper: function helper(event, ui) {
5998 ui.children().each(function () {
5999 $(this).width($(this).width());
6000 });
6001 return ui;
6002 },
6003 beforeStop: function beforeStop(event, ui) {
6004 $("#routeList").find("tr[data-index]:not([data-index='-1']) td").removeAttr("style", "");
6005 updateFiller = true;
6006 return ui;
6007 },
6008 update: function update(event, ui) {
6009 RouteTable.changeStop(ui.item.index());
6010 recalculateDates(curRoute);
6011 // for(var i = ui.item.index(); i < RouteTable.getLength(); i++){
6012 // // RouteTable.getTableRow(i).redrawNumber(i);
6013 // // }
6014
6015 //RouteTable.changeStop();
6016 return ui;
6017 }
6018 }).disableSelection();
6019
6020 $("#create-trip-datepicker, #edit-trip-datepicker, #support-datepicker").datetimepicker({
6021 format: "MM/DD/YYYY"
6022 });
6023
6024
6025
6026
6027 $(window).resize(function () {
6028 window.requestAnimationFrame(setTableFiller);
6029 //AddToTripComponent.reset();
6030 if ($(this).width() < 992) {
6031 AddToTripComponent.enableMobile();
6032 } else {
6033 AddToTripComponent.disableMobile();
6034 }
6035 if (wrenchPushed == 2) {
6036 return;
6037 }
6038 if (wrenchPushed == 1) {
6039 wrenchPushed = 0;
6040 return false;
6041 } else {
6042 $(".popover").remove();
6043 }
6044 if ($("body").width() < 1200) {
6045 if (switchParam == 1) {
6046 if ($(".aside-left").hasClass("visible")) {
6047 expandOrHideSideBar();
6048 }
6049 switchParam = 0;
6050 }
6051
6052 } else {
6053 switchParam = 1;
6054 }
6055 if ($("body").width() < 560) {
6056 $("#poi-form").width($("body").width());
6057 } else {
6058 $("#poi-form").css("width", "408px");
6059 }
6060 $("#toggle-map-view-tiny").trigger("click");
6061 if ($(".aside-right").hasClass("desk-visible-right")) {
6062 expandOrHideFilterBar();
6063 }
6064 });
6065 // This fix is one of the ugliest I ever done ... sorry :'(
6066 var previousTabFillerHeight = 0,
6067 updateFiller = true;
6068 var setTableFiller = function setTableFiller() {
6069 var tableFiller = $(".table-filler");
6070 var $trs = $("#routeList").find("tr[data-index]"),
6071 height = $(".table-wrapper").height() - $(".table-wrapper thead").outerHeight() - ($trs.length ? $trs.toArray().map(function (e) {
6072 return $(e).outerHeight();
6073 }).reduce(function (t, h) {
6074 return t + h;
6075 }) : 0);
6076 if (height !== previousTabFillerHeight && updateFiller) {
6077 var $filler = tableFiller.length ? tableFiller : $("<tr class=\"table-filler\"></tr>");
6078 $filler.html($trs.first().find("td").clone().empty());
6079 if (height > 0) {
6080 $("#routeList").append($filler);
6081 $filler.height(height);
6082 } else {
6083 $("#routeList").find(".table-filler").remove();
6084 }
6085 previousTabFillerHeight = height;
6086 }
6087 };
6088
6089 $(function () {
6090 return rvTripHelper.openStateList();
6091 });
6092
6093 $("#filter-area-state-select").on("change", function () {
6094 var $this = $(this);
6095 rvTripHelper.loadStatePoi($this.val());
6096 });
6097
6098 $("#filter-area-state-order").on("change", function () {
6099 poiSorting = $(this).val();
6100 rvTripHelper.loadStatePoi($("#filter-area-state-select").val());
6101 });
6102
6103 radiusChange();
6104
6105 function changeFavoritesBadges() {
6106 var favs = Array.from(document.querySelectorAll("#affiliations-fav li .badge"));
6107 favs.forEach(function (badge, index) {
6108 badge.textContent = index + 1;
6109 return badge.textContent;
6110 });
6111 }
6112
6113 $(window).on("click", function () {
6114 if (tour && tour.running()) {
6115 return;
6116 }
6117
6118 $(".popover:not(.tour-tour)").popover("hide");
6119 });
6120 $(".popover").on("click", function (event) {
6121 event.stopPropagation();
6122 });
6123
6124
6125 $('.poi-container .clear-all').on('click', function () {
6126 if (gettingPoi) {
6127 return;
6128 }
6129 $('.poi-container-filter').addClass('red-bar');
6130 $('.poi-container-filter').removeClass('green-bar');
6131 $('.filter-box').not($('.no-active')).remove();
6132 $('.footer-buttons-poi').empty();
6133 var poiContainer = $(".poi-container button");
6134 poiContainer.attr("disabled", false);
6135 poiContainer.removeClass('green-background');
6136 poiContainer.each(function (index, item) {
6137 // $(item).unbind("click");
6138 clearNonOvernightPoi($(item).val());
6139 });
6140 clearNonOvernightPoi(17);
6141 setFilterValues("all", 0);
6142 $(".poi-container-filter button").each(function (index, item) {
6143 if ($(item).hasClass('selected')) {
6144 // $(item).unbind("click.inside");
6145 $(item).removeClass("selected");
6146 $(item).children('span').removeClass("selected");
6147 }
6148 });
6149 filterCount = 0;
6150 updatePOIFooter();
6151 checkFilterBar();
6152
6153 var container = $(this).closest('.header').parent();
6154 $(container).find('button.selected').each(function (k, input) {
6155 // deselect each of them
6156 $(this).attr('previousValue', false);
6157 $(this).toggleClass('selected');
6158 $(this).children('span').toggleClass('selected');
6159 });
6160 saveTopPois();
6161 });
6162
6163 $('.attractions-container .clear-all').click(function () {
6164 var container = $(this).closest('.header').parent();
6165 var body = $(container).find('.body');
6166
6167 $(container).find('input[type=radio]:checked,input[type=checkbox]:checked').each(function (k, input) {
6168 // deselect each of them
6169 $(this).removeAttr('checked');
6170 $(this).attr('previousValue', false);
6171 $(this).trigger('change');
6172 });
6173 });
6174
6175 $('.attractions-container input:radio').click(function (event) {
6176 if (gettingPoi) {
6177 event.preventDefault();
6178 event.stopPropagation();
6179 return false;
6180 }
6181
6182 $('.attractions-container input:radio').not(this).prop('checked', false).trigger('change');
6183 var previousValue = $(this).attr('previousValue');
6184 var name = $(this).attr('name');
6185
6186 if (previousValue == 'checked') {
6187 $(this).removeAttr('checked');
6188 $(this).attr('previousValue', false);
6189 $(this).trigger('change');
6190 } else {
6191 $("input[name=" + name + "]:radio").attr('previousValue', false);
6192 $(this).attr('previousValue', 'checked');
6193 }
6194 });
6195
6196 $(".attraction input[type=radio]").on("change", function () {
6197 var type = $(this).find('input');
6198 var selection = $(this).val();
6199 if (map.getZoom() < _global.map.zoom.end) {
6200 if (!$(this).is(':checked')) {
6201 placesNearBy.removeAreaAttractions(selection);
6202 return;
6203 }
6204
6205 /* If zoom too far then do nothing */
6206 notificationService.show(_global.msg.zoomInToShowPoi);
6207 $(this).attr("checked", false);
6208 return;
6209 }
6210
6211 if (!$(this).is(':checked')) {
6212 placesNearBy.removeAreaAttractions(selection);
6213 return;
6214 }
6215 gettingPoi = true;
6216 var $elem = $(this);
6217 $elem.attr('disabled', true);
6218
6219 placesNearBy.overlayAreaAttractionsByMapCenter(selection)
6220 .then(function () {
6221 $elem.attr('disabled', false);
6222 gettingPoi = false;
6223 });
6224 });
6225
6226
6227 $("#top-poi-save").click(function () {
6228 saveTopPois();
6229 });
6230
6231 var viewableRadius = function () {
6232 var bounds = map.getBounds();
6233 var center = map.getCenter();
6234 if (bounds && center) {
6235 var ne = bounds.getNorthEast();
6236 // Calculate radius (in meters).
6237 return (1270 * 1000);
6238 //return google.maps.geometry.spherical.computeDistanceBetween(center, ne);
6239 }
6240 return (1270 * 1000); //If it couldnt calculate the radius for some reason, give it the aprox radius of the US
6241 };
6242
6243 function searchInputLookup(query, done) {
6244 var parkNames = [];
6245 var radius = viewableRadius();
6246 var string = query + '|' + map.getCenter() + '|' + radius;
6247 var hash = string.hashCode();
6248 var d1 = $.Deferred();
6249 var d2 = $.Deferred();
6250
6251 if (searchLookupStack.has(hash)) {
6252 done({
6253 suggestions: searchLookupStack.get(hash)
6254 });
6255 return;
6256 }
6257
6258 GoogleLog.logPlacePrediction({
6259 data: {
6260 query: query
6261 }
6262 });
6263
6264 var autocompleteRequestParams = {
6265 query: query,
6266 location: map.getCenter(),
6267 radius: radius
6268 };
6269
6270 MapsController.getAutocompletePlacePredictions(autocompleteRequestParams, function (placePredictions) {
6271 d1.resolve(placePredictions);
6272 });
6273
6274 $.ajax({
6275 type: "GET",
6276 dataType: 'json',
6277 url: apiUrl + 'search_suggest.php',
6278 data: {
6279 query: query
6280 },
6281 success: function success(res) {
6282 d2.resolve(res);
6283 }
6284 });
6285
6286 $.when(d1, d2).then(function (google, rvtrip) {
6287 var found = [];
6288 var results = [];
6289 var tripCount = 0;
6290 $.each(rvtrip.parks, function (key, object) {
6291 if (tripCount < 3) {
6292 found[object.name] = true;
6293 object.category = 'Parks';
6294 object.type = 'park';
6295 object.poitype_id = 1;
6296 var objectName = object.name;
6297 parkNames.push(objectName);
6298 objectName = objectName.replace("amp;", "");
6299 var finalObject = {
6300 value: objectName,
6301 data: object
6302 };
6303 results.push(finalObject);
6304 tripCount++;
6305 }
6306 });
6307
6308 var googleCount = 0;
6309 var googleResults = [];
6310 $.each(google, function (key, object) {
6311 if (!object.id) {
6312 return true;
6313 }
6314 var name = object.structured_formatting.main_text;
6315 for (var x = 0; x < parkNames.length; x++) {
6316 if (object.description.indexOf(parkNames[x]) != -1) {
6317 return true;
6318 }
6319 }
6320 var descKey = object.description + object.vicinity;
6321 if (googleResults.indexOf(descKey) != -1) {
6322 return true;
6323 }
6324 if (!found[name]) {
6325 if (googleCount < 4) {
6326 object.type = 'google-places';
6327 object.category = 'Places of Interest';
6328 var finalObject = {
6329 value: object.description,
6330 data: object
6331 };
6332 if (parkSubs[finalObject.data.id]) {
6333 finalObject = parkSubs[finalObject.data.id];
6334 }
6335 results.push(finalObject);
6336 googleResults.push((object.description + object.vicinity));
6337 googleCount++;
6338 }
6339 }
6340 });
6341 searchLookupStack.push(hash, results);
6342 done({
6343 suggestions: results
6344 });
6345 });
6346 }
6347
6348 var parkSearchResult = "";
6349
6350 function searchLocationOnSelect(suggestion) {
6351 if (rvTripHelper.isDevice()) {
6352 $('label#toggle-map-view-tiny').click(); // Click on Map tab to hide sidebar
6353 }
6354
6355 searchResult = false;
6356 if (suggestion.data.type == 'park') {
6357 parkSearchResult = suggestion.data.name;
6358 prefParkSearch = suggestion.data;
6359 searchOpenPark(suggestion.data);
6360 // } else if (dataset == 'places') {
6361 // setUserLocationByAddress(suggestion.name, false);
6362 } else if (suggestion.data.type == 'google-places') {
6363 // place_id here is suggestion.place_id
6364 if (googlePlaces[suggestion.data.place_id]) {
6365 setUserLocationByPlace(googlePlaces[suggestion.data.place_id]);
6366 } else {
6367 if (suggestion.data.terms && suggestion.data.terms.length == 3 &&
6368 (suggestion.data.terms[2].value == 'United States' || suggestion.data.terms[2].value == 'USA' || suggestion.data.terms[2].value == 'Canada')) {
6369 var city = suggestion.data.terms[0].value;
6370 var region = suggestion.data.terms[1].value;
6371 var country = suggestion.data.terms[2].value;
6372
6373 $.ajax({
6374 url: apiUrl + 'country/' + country + '/region/' + region + '/city/' + city,
6375 data: 'lite=true',
6376 noblock: false,
6377 type: 'get',
6378 dataType: 'json',
6379 headers: {
6380 Accept: 'application/x.rvparkreviews.v1+json'
6381 },
6382 success: function (r) {
6383 var data = {
6384 name: r.city_name,
6385 address: 'Locality',
6386 lat: r.city_latitude,
6387 lon: r.city_longitude
6388 };
6389 setUserLocationByLocation(data, false);
6390 },
6391 error: function () {
6392 GoogleLog.logPlacesDetails({
6393 call: 'Call #3 - Google Search Lookup, RV Park Lookup Failed',
6394 data: {
6395 'Desc': suggestion.data.description,
6396 'Place ID': suggestion.data.place_id
6397 }
6398 });
6399 MapsController.getLocationDetails(suggestion.data, function (place, placesServiceStatus) {
6400 if (placesServiceStatus == google.maps.GeocoderStatus.OK) {
6401 if (place.formatted_address) {
6402 place.name = jQuery(place.formatted_address);
6403 }
6404 if (!googlePlaces[suggestion.data.place_id]) {
6405 googlePlaces[suggestion.data.place_id] = place;
6406 }
6407 setUserLocationByPlace(place);
6408 } else {
6409 alert('Failed to retrieve details for this location. Please try again.');
6410 }
6411 });
6412 }
6413 });
6414 } else {
6415 GoogleLog.logPlacesDetails({
6416 call: 'Call #3 - Google Search Lookup',
6417 data: {
6418 'Desc': suggestion.data.description,
6419 'Place ID': suggestion.data.place_id
6420 }
6421 });
6422 MapsController.getLocationDetails(suggestion.data, function (place, placesServiceStatus) {
6423 if (placesServiceStatus == google.maps.GeocoderStatus.OK) {
6424 if (place.formatted_address) {
6425 place.name = jQuery(place.formatted_address);
6426 }
6427 if (!googlePlaces[suggestion.data.place_id]) {
6428 googlePlaces[suggestion.data.place_id] = place;
6429 }
6430
6431 setUserLocationByPlace(place);
6432 } else {
6433 alert('Failed to retrieve details for this location. Please try again.');
6434 }
6435 });
6436 }
6437 }
6438 }
6439 }
6440
6441
6442 $('#search-location-form').find('.typeahead').devbridgeAutocomplete({
6443 lookupLimit: 7,
6444 minChars: 2,
6445 groupBy: 'category',
6446 lookup: searchInputLookup,
6447 onSelect: searchLocationOnSelect,
6448 formatResult: function (suggestion, currentValue) {
6449 var cv = currentValue.replace(/[([)]|\\/g, "");
6450 var reg = new RegExp("(" + cv + ")", 'gi');
6451 if (suggestion.data.type == "park") {
6452 if (suggestion.data.name) {
6453 return '<span>' + suggestion.data.name.replace(reg, '<strong>$1</strong>') + '<span class="autocomplete-suggestion-location">' + suggestion.data.city + ', ' + suggestion.data.region + '</span></span>';
6454
6455 }
6456 } else {
6457 if (suggestion.value) {
6458 var newVicinity = suggestion.data.vicinity.split("<br/>");
6459 return '<span>' + suggestion.value.replace(reg, '<strong>$1</strong>') + '<span class="autocomplete-suggestion-location">' + (newVicinity.length > 1 ? newVicinity[1] : newVicinity[0]) + '</span></span>';
6460 }
6461 }
6462 }
6463 });
6464
6465 function searchOpenPark(park) {
6466 searchResult = true;
6467 updateMapCenter(new google.maps.LatLng(park.latitude, park.longitude), _global.numberMarkerZoom);
6468 highlightPoi = park.park_id + '-' + 1;
6469 highlightedPoiObject = park;
6470 reallyDoSearch();
6471 }
6472
6473 /* No sidebar = print mode */
6474 if ($("#sidebar").length > 0) {
6475
6476 document.getElementById('newpassword').addEventListener('keyup', function () {
6477 document.getElementById('newpassword1').reportValidity();
6478 });
6479
6480 hyperform.add_validator(
6481 document.getElementById('newpassword1'),
6482 function (element) {
6483 var valid = element.value === document.getElementById('newpassword').value;
6484 element.setCustomValidity(
6485 valid ?
6486 '' :
6487 'The password and confirmation do not match.'
6488 );
6489 return valid;
6490 }
6491 );
6492 hyperform(window);
6493
6494 if (typeof (Raven) != 'undefined') {
6495 Raven.setUserContext({
6496 trip_user_id: $('#trip_user_id').val(),
6497 emp_user_id: $('#emp_user_id').val(),
6498 emp_user_email: $('#emp_user_email').val()
6499 });
6500 }
6501 }
6502
6503 $('.open-help-missing-park').on('click', function (event) {
6504 HelpModal.showModal();
6505 HelpModal.showMissingParkTab();
6506 });
6507
6508 $(".open-help-user-guide").on("click", function (event) {
6509 HelpModal.showModal();
6510 HelpModal.showUserGuideTab();
6511 });
6512
6513 function expandOrHideSideBar() {
6514 if (lockMapService.isLocked()) {
6515 return;
6516 }
6517
6518
6519 if ($('.aside-right').hasClass('desk-visible-right') && $('#mapContainer').parent().width() < 1299) {
6520 if ($(".aside-left").hasClass("visible")) {
6521 expandOrHideFilterBar();
6522 }
6523
6524 }
6525
6526 $("#toggle-side-bar").click();
6527 sidebar.classList.toggle("desk-visible");
6528 $("#arrow-toggle").toggleClass("glyphicon-chevron-left").toggleClass("glyphicon-chevron-right");
6529 $("#collapse-side-bar").toggleClass("collapsed");
6530 $("#mapContainer").toggleClass('map-container-contracted');
6531 // google maps needs to have the resize event trigger when map is resized
6532 google.maps.event.trigger(map, 'resize');
6533 if ($('#sidebar').hasClass('desk-visible')) {
6534 //adjust highcharts btns
6535 var newLeft = $("#sidebar").css("width");
6536 $('#desktopChartbtns').animate({
6537 'margin-Left': newLeft
6538 }, 100);
6539
6540 notificationService.addMargin();
6541 } else {
6542 $('#desktopChartbtns').animate({
6543 'margin-Left': 0
6544 }, 100);
6545
6546 notificationService.removeMargin();
6547 }
6548 }
6549
6550 function expandOrHideFilterBar() {
6551 if (lockMapService.isLocked()) {
6552 return;
6553 }
6554
6555 if ($('.aside-left').hasClass('desk-visible') && $('#mapContainer').parent().width() < 1299) {
6556 expandOrHideSideBar();
6557 }
6558 filterbar.classList.toggle("desk-visible-right");
6559 $("#arrow-toggle-filter").toggleClass("glyphicon-chevron-right").toggleClass("glyphicon-chevron-left");
6560 $("#collapse-filter-nav").toggleClass("collapsed");
6561 $("#mapContainer").toggleClass('map-container-contracted-filter');
6562 callDoSearch();
6563 if ($('#show_hide_parks').hasClass('btn-hide-parks')) {
6564 hideParks();
6565 }
6566 // google maps needs to have the resize event trigger when map is resized
6567 google.maps.event.trigger(map, 'resize');
6568 if ($('#filter-sidebar').hasClass('desk-visible-right')) {
6569 //adjust highcharts btns
6570 var newLeft = $("#filter-sidebar").css("width");
6571
6572 notificationService.addMargin();
6573 } else {
6574
6575 notificationService.removeMargin();
6576 }
6577 }
6578
6579 $(function () {
6580 if ($('#sidebar').hasClass('desk-visible')) {
6581 notificationService.addMargin();
6582 } else {
6583 notificationService.removeMargin();
6584 }
6585 });
6586
6587 $(function () {
6588 if ($('#filter-sidebar').hasClass('desk-visible-right')) {
6589 notificationService.addMargin();
6590 } else {
6591 notificationService.removeMargin();
6592 }
6593 });
6594
6595
6596 $('.start-tour-icon').on('click', loadTripAndStartTour);
6597
6598 function loadTripAndStartTour() {
6599 loadSelectedTrip(null, null, true)
6600 .then(function () {
6601 setTimeout(startTour, 3000);
6602 });
6603 }
6604
6605 var tour;
6606 var hasShownTour = false;
6607
6608 function startTour() {
6609 if (tour && tour.running()) {
6610 return;
6611 }
6612
6613 hasShownTour = true;
6614
6615 tour = new tourService(factories.tour.create({
6616 width: window.innerWidth,
6617 isDevice: $('#toggle-side-bar').is(':visible')
6618 }));
6619
6620 tour.start();
6621 }
6622
6623 function objectStack(obj, max_length) {
6624 if (max_length) {
6625 this.max_length = max_length;
6626 } else {
6627 this.max_length = 100;
6628 }
6629 this.object = obj;
6630 this.stack = [];
6631
6632 this.push = function (key, value) {
6633 if (this.length() > this.max_length) {
6634 this.shift();
6635 }
6636 this.object[key] = value;
6637 this.stack.push(key);
6638 };
6639
6640 this.pop = function () {
6641 var key = this.stack.pop();
6642 var prop = this.object[key];
6643 delete this.object[key];
6644 return prop;
6645 };
6646
6647 this.shift = function () {
6648 var key = this.stack.shift();
6649 var prop = this.object[key];
6650 delete this.object[key];
6651 return prop;
6652 };
6653
6654 this.length = function () {
6655 return this.stack.length;
6656 };
6657
6658 this.has = function (key) {
6659 return (typeof this.object[key] != 'undefined');
6660 };
6661
6662 this.get = function (key) {
6663 return this.object[key];
6664 };
6665 }
6666
6667 // $('.btn-hide-parks').click(function(){
6668 // hideParks();
6669 // });
6670 //
6671 // $('.btn-show-parks').click(function(){
6672 // showParks();
6673 // });
6674
6675 function saveViewParkOption(viewOption) {
6676 $.ajax({
6677 type: "POST",
6678 ws: "save_view_parks",
6679 data: {
6680 viewToggle: JSON.stringify(viewOption),
6681 trip_user_id: $("#trip_user_id").val()
6682 },
6683 success: function success(res) {}
6684 });
6685 }
6686
6687 function hideParks() {
6688 disableCgPoiLoading = true;
6689 if (curRoute && curRoute.routeLegs) {
6690 $.each(curRoute.routeLegs, function (index, item) {
6691 item.poi.marker.main = 'yes';
6692 });
6693 }
6694
6695 if (arrMarkers) {
6696 $.each(arrMarkers, function (key, arrMarker) {
6697
6698 if (!arrMarker.poiType) {
6699 if (arrMarker.main == "yes" || arrMarker.search == "yes") {} else {
6700 arrMarker.setMap(null);
6701 }
6702 }
6703 });
6704 }
6705
6706 var viewOption = {
6707 "view": 0
6708 };
6709 saveViewParkOption(viewOption);
6710
6711
6712 }
6713
6714 function showParks() {
6715 if (arrMarkers) {
6716 $.each(arrMarkers, function (key, arrMarker) {
6717 if (!arrMarker.poiType) {
6718 arrMarker.setMap(map);
6719 }
6720
6721 });
6722 }
6723 disableCgPoiLoading = false;
6724 var viewOption = {
6725 "view": 1
6726 };
6727 saveViewParkOption(viewOption);
6728 callDoSearch();
6729 }
6730
6731 function saveTopPois() {
6732 var topPoiStates = {};
6733 $.each($('.poi-container .body button'), function () {
6734 topPoiStates["poi_type" + $(this).context.value.toString()] = {};
6735 topPoiStates["poi_type" + $(this).context.value.toString()].value = $(this).context.value.toString();
6736 topPoiStates["poi_type" + $(this).context.value.toString()].set = $(this).hasClass('selected') ? 1 : 0;
6737 });
6738 $.each($('.poi-container-filter .body button'), function () {
6739 topPoiStates[$(this).context.value.toString()] = {};
6740 topPoiStates[$(this).context.value.toString()].value = $(this).context.value.toString();
6741 topPoiStates[$(this).context.value.toString()].set = $(this).hasClass('selected') ? 1 : 0;
6742 });
6743 $.ajax({
6744 type: "POST",
6745 ws: "save_top_pois",
6746 data: {
6747 topPoiSaves: JSON.stringify(topPoiStates),
6748 trip_user_id: $("#trip_user_id").val()
6749 },
6750 success: function success(res) {
6751 if (debug) console.log(res);
6752 },
6753 error: function error(x, y, z) {}
6754 });
6755 }
6756
6757 function saveFilters() {
6758 $.ajax({
6759 type: "POST",
6760 ws: "save_filter",
6761 data: {
6762 filterSaves: JSON.stringify(activeFilters),
6763 trip_user_id: $("#trip_user_id").val()
6764 },
6765 success: function success(res) {},
6766 error: function error(x, y, z) {}
6767 });
6768 }
6769
6770 function getSavedFilters() {
6771 /* No Sidebar = print mode */
6772 if ($("#sidebar").length == 0) {
6773 return;
6774 }
6775 $.ajax({
6776 type: "GET",
6777 ws: "get_filters",
6778 data: {
6779 trip_user_id: $("#trip_user_id").val()
6780 },
6781 success: function success(res) {
6782 tempFilters = JSON.parse(res.filter_states);
6783 for (var item in activeFilters) {
6784 if (tempFilters[item] != null) {
6785 activeFilters[item] = tempFilters[item];
6786 } else {
6787 activeFilters[item] = [];
6788 }
6789 }
6790
6791
6792 updateParksFiltering();
6793 setActiveButtons();
6794 updateFilterFooter();
6795 updateFilterIndicator();
6796 },
6797 error: function error(x, y, z) {}
6798 });
6799 }
6800
6801 $(".navbar-right").click(function () {
6802 if (rvTripHelper.isDevice()) {
6803 if (rvTripHelper.isIpad()) {
6804 $('.news-notification').addClass('news-notification-ipad').removeClass('news-notification');
6805 } else {
6806 $('.news-notification').addClass('news-notification-mobile').removeClass('news-notification');
6807 }
6808 if (rvTripHelper.isDevice) {
6809 $('.dropdown-menu').addClass("dropdown-multiple-columns").css("left", "-288px");
6810 } else {
6811 $('.dropdown-menu').addClass("dropdown-multiple-columns").css("left", "-263px");
6812 }
6813 $('#open-settings').addClass("mobile-adjust");
6814 $('.dropdown-divider').hide();
6815 } else {
6816 $(".column-seperator").css("height", "0px");
6817 }
6818 });
6819
6820
6821
6822 $(".news-button").click(function () {
6823 $(".tools-dropdown").removeClass("tools-dropdown");
6824 $(".news-notification").removeClass("news-notification");
6825 $.ajax({
6826 type: "POST",
6827 ws: "save_news_seen",
6828 data: {
6829 trip_user_id: $("#trip_user_id").val()
6830 },
6831 success: function success(res) {},
6832 error: function error(x, y, z) {}
6833 });
6834 });
6835
6836
6837 var filterValues = {
6838 "fuel": 0,
6839 "rest": 0,
6840 "overnight": 0,
6841 "dump": 0,
6842 "checked": 0
6843 };
6844 var chartLegend;
6845
6846 function getFilterLocations(callback) {
6847 if (!filterValues.fuel && !filterValues.rest && !filterValues.overnight && !filterValues.dump) {
6848 toHighlight({
6849 "count": 0
6850 });
6851 return;
6852 }
6853 $.ajax({
6854 type: "GET",
6855 ws: "get_filter",
6856 data: {
6857 filter: JSON.stringify(filterValues),
6858 trip_user_id: $("#trip_user_id").val()
6859 },
6860 success: function success(res) {
6861 filterHighlight = res;
6862 callback(filterHighlight);
6863
6864 },
6865 error: function error(x, y, z) {}
6866 });
6867 }
6868
6869 function toHighlight(highlight) {
6870 $.each($('.poi-container .body button'), function (index, item) {
6871 clearNonOvernightPoi($(item).val());
6872 if ($(this).hasClass('selected')) {
6873 $(this).trigger("click");
6874 }
6875 $(this).removeClass('green-background');
6876 if (highlight.count == 0) {
6877 $(this).prop("disabled", false);
6878 } else {
6879 $(this).prop("disabled", true);
6880 }
6881
6882 });
6883 $(".poi-container-filter").removeClass("green-bar").addClass("red-bar");
6884 if (highlight.count > 0) {
6885 $(".poi-container-filter button").prop("disabled", true);
6886 }
6887 for (var x = 0; x < highlight.count; x++) {
6888 $('.poi-container .body button[value="' + highlight[x] + '"]').toggleClass("green-background");
6889 $('.poi-container .body button[value="' + highlight[x] + '"]').prop("disabled", true);
6890 var temp = x;
6891 if (map.getZoom() < _global.map.zoom.end) {
6892 $(".poi-container-filter button").prop("disabled", false);
6893 } else {
6894 loadNonPoi(highlight[x], function (index) {
6895 return function () {
6896 $('.poi-container .body button[value="' + highlight[index] + '"]').prop("disabled", false);
6897 if (index == highlight.count - 1) {
6898 $(".poi-container-filter button").prop("disabled", false);
6899 }
6900 };
6901 }(temp));
6902 }
6903 }
6904 }
6905
6906 var filterCount = 0;
6907
6908 function checkFilterBar() {
6909 if (filterCount == 0) {
6910 $('.no-active').show();
6911 $('.top-nav-poi-filter').css("color", "inherit");
6912 } else {
6913 $('.no-active').hide();
6914 $('.top-nav-poi-filter').css("color", "#17B4B3");
6915 }
6916 }
6917
6918 var filterId = {
6919 id: 0
6920 };
6921
6922 function addFilterItem(text, checkbox, value) {
6923
6924 var tempFilterItem;
6925 tempFilterItem = $("<button>", {
6926 "class": "footer-filter-button poi" + filterId.id
6927 });
6928 var currentCount = $.extend({}, filterId);
6929 filterId.id += 1;
6930 var span2 = document.createElement("span");
6931 span2.classList.add('filter-footer-button-text');
6932 span2.innerHTML = text + '<img class="filter-x" src="images/filter-x.svg"></img>';
6933 tempFilterItem.append(span2);
6934
6935
6936
6937
6938
6939 // var tempFilterItem;
6940 // tempFilterItem = $("<div>", {"class":"filter-box filter" + filterId.id});
6941 // var currentCount = $.extend({}, filterId);
6942 // filterId.id +=1;
6943 // tempFilterItem.append($("<p>", {"text": text}));
6944 // var tempFilterButton = $("<button>");
6945 // tempFilterItem.append(tempFilterButton);
6946 // tempFilterButton.append($("<i>", {"class": "fa fa-times"}))
6947
6948
6949 filterCount += 1;
6950 if (checkbox.val() == "rest") {
6951 clickPoiChkBox(checkbox.get(0), checkbox.val() == "rest" ? 17 : checkbox.val());
6952 }
6953 $(tempFilterItem).click(function (event) {
6954 event.preventDefault();
6955 event.stopPropagation();
6956 $('.poi' + currentCount.id).remove();
6957 setFilterValues(value, 0);
6958 filterCount -= 1;
6959 $(checkbox).prop("checked", false);
6960 if (isNaN(checkbox.val()) && checkbox.val() != "rest") {
6961 getFilterLocations(toHighlight);
6962 } else {
6963 clickPoiChkBox(checkbox.get(0), checkbox.val() == "rest" ? 17 : checkbox.val());
6964 }
6965 checkbox.off("click.inside");
6966 updatePOIFooter();
6967 checkFilterBar();
6968 if ($(checkbox).val() > 0) {
6969 $(checkbox).unbind("click");
6970 }
6971 });
6972 $('.footer-buttons-poi').append(tempFilterItem);
6973 return tempFilterItem;
6974 }
6975
6976 function setFilterValues(filter, value) {
6977 if (filter == "fuel") {
6978 filterValues.fuel = value;
6979 } else if (filter == "dump") {
6980 filterValues.dump = value;
6981 } else if (filter == "overnight") {
6982 filterValues.overnight = value;
6983 } else if (filter == "all") {
6984 filterValues.overnight = value;
6985 filterValues.dump = value;
6986 filterValues.fuel = value;
6987 } else {
6988 return;
6989 }
6990 }
6991
6992 $(".poi-container .checkbox").click(function () {
6993 var isDisabled = $(this).find("button").is(":disabled");
6994 if (updatingPois.length > 0) {
6995 return;
6996 }
6997 if ($(this).find("button").is(":disabled")) {
6998 if (rvTripHelper.isDevice()) {
6999 notificationService.show(_global.msg.filterDisabledPoiMobile);
7000 } else {
7001 notificationService.show(_global.msg.filterDisabledPoi);
7002 }
7003
7004 }
7005 });
7006
7007 $(".poi-container-filter button").click(function (event) {
7008 if ((map.getZoom() < _global.map.zoom.end) && alreadyLoaded) {
7009 /* Don't allow users to toggle filters while too far zoomed out */
7010 notificationService.show(_global.msg.zoomInToShowPoi);
7011 return;
7012 }
7013
7014 $(this).toggleClass('selected');
7015 $(this).children('span').toggleClass('selected');
7016
7017 var _this = $(this);
7018 var val = $(this).val();
7019 if ($(this).hasClass('selected')) {
7020 setFilterValues(val, 1);
7021 var filterItem = addFilterItem(val.charAt(0).toUpperCase() + val.slice(1), _this, val);
7022 $(_this).on("click.inside", function (filterItem) {
7023 updatePOIFooter();
7024 return function () {
7025 if (map.getZoom() < _global.map.zoom.end) {
7026 if (!$(this)[0].checked) {
7027
7028 } else {
7029 return;
7030 }
7031 }
7032 $(filterItem).remove();
7033 _this.off("click.inside");
7034 };
7035 }(filterItem));
7036 } else {
7037 setFilterValues(val, 0);
7038 filterCount -= 1;
7039 if (val == "rest") {
7040 clickPoiChkBox(this, 17);
7041 }
7042 }
7043 saveTopPois();
7044 updatePOIFooter();
7045 checkFilterBar();
7046 getFilterLocations(toHighlight);
7047 });
7048
7049 var curYPos, curXPos, curDown;
7050 var curOffset = 0;
7051
7052 //need to look at this loading one more time. Maybe only make it at the start. Also figure out why it's not really working anymore.
7053 var alreadyLoaded = 0;
7054
7055 function startLoadPoi() {
7056 if (!alreadyLoaded) {
7057
7058 $.each($('.poi-container-filter .body button'), function () {
7059 var _this = $(this);
7060 if ($(this).hasClass("set1")) {
7061 _this.trigger('click');
7062 }
7063 });
7064 $(document).ajaxStop(function () {
7065 $(this).unbind("ajaxStop");
7066 $.each($('.poi-container .body button'), function () {
7067 var _this = $(this);
7068 if ($(this).hasClass("set1")) {
7069 $(_this).trigger("click");
7070 $(_this).addClass("selected");
7071 }
7072 });
7073 getSavedFilters();
7074 $("#fourth-load-item").removeClass("loading").addClass("loaded").find(".complete-text").show();
7075 checkLoadingModal();
7076 initialLoad = false;
7077 });
7078 }
7079 checkFilterBar();
7080 alreadyLoaded += 1;
7081 }
7082
7083
7084 $(document).ready(function () {
7085 // Where new classes will be created
7086 if (!rvTripHelper.isDevice()) {
7087 $(document).on("mousemove", function (e) {
7088 if (curDown) {
7089 $('body').addClass('noSelect');
7090 $('.filter-bar').scrollLeft(curOffset + (curXPos - e.pageX));
7091 }
7092 });
7093
7094 $('.filter-bar').on('mousedown', function (e) {
7095 curYPos = e.pageY;
7096 curXPos = e.pageX;
7097 curDown = true;
7098 });
7099
7100 $(document).on('mouseup', function (e) {
7101 if (curDown) {
7102 $('body').removeClass('noSelect');
7103 curOffset = (curOffset + (curXPos - e.pageX)) < 0 ? 0 : curOffset + (curXPos - e.pageX);
7104 curOffset = curOffset > $('.filter-bar')[0].scrollWidth - $(window).width() ? $('.filter-bar')[0].scrollWidth - $(window).width() : curOffset;
7105 curDown = false;
7106 }
7107 });
7108 } else {
7109 $('.filter-bar').addClass('scroll-x');
7110 }
7111
7112 // have research tab open by default if larger than 1300 pixels
7113 if ($('#mapContainer').parent().width() >= 1300) {
7114 $(".nav-right").removeClass("initial-hidden");
7115 $("#collapse-filter-nav").trigger("click");
7116 $(".first-actions").css("left", $("#mapContainer").width() / 2);
7117 }
7118 });
7119
7120
7121
7122 //hold saved series to swap without reworking
7123
7124 function showElevationProfile() {
7125 if (ElevationSection.isClosed()) {
7126 ElevationSection.open();
7127 $('#showGradeBtn').css('display', 'inline');
7128 }
7129 // here is the code for closing the elevation panels
7130 else {
7131 ElevationSection.close();
7132 metric = false;
7133 }
7134 }
7135
7136
7137 // changes elevation panel to and from metric
7138
7139 $(".grade-button-container, #showGradeBtn").click(function () {
7140 if (ElevationSection.gradientDisabled) {
7141 return;
7142 }
7143 ElevationSection.disableGradientButton();
7144 setTimeout(function () {
7145 ElevationController.createGradients();
7146 ElevationSection.enableGradientButton();
7147 }, 0);
7148 });
7149 //get the color and add it to the legend tracker if it exists
7150
7151 function closeElevation() {
7152 ElevationSection.close();
7153 }
7154
7155 $("#elevationBtn").click(function () {
7156 if ($('#elevation_chart').is(":hidden")) {
7157 var mapheight = $("#mapContainer").parent().height();
7158 // animates sidebar toggle to go up and out of way of the chart
7159 $('.nav-pills').animate({
7160 bottom: mapheight * 0.5
7161 }, 750, function () {
7162 // Animation complete.
7163 });
7164
7165 // animates filter bar toggle to go up and out of way of the chart
7166 $('.nav-pills-filter').animate({
7167 bottom: mapheight * 0.5
7168 }, 750, function () {
7169 // Animation complete.
7170 });
7171
7172 } else {
7173 $('.nav-pills').animate({
7174 bottom: "140px"
7175 }, 750, function () {});
7176
7177 $('.nav-pills-filter').animate({
7178 bottom: "140px"
7179 }, 750, function () {});
7180 }
7181
7182 showElevationProfile();
7183 });
7184 //end Elevation
7185
7186 var hammertime = new Hammer($("main")[0], {
7187 prevent_default: false,
7188 touchAction: "pan"
7189 });
7190 hammertime.get('pinch').set({
7191 enable: true
7192 });
7193 hammertime.on('pinch pinchmove pinchcancel pinchin pinchout pinchend pinchstart', function (e) {
7194 e.preventDefault();
7195 });
7196
7197 var hammertime2 = new Hammer($(".marker-modal")[0], {
7198 prevent_default: false,
7199 touchAction: "pan"
7200 });
7201 hammertime2.get('pinch').set({
7202 enable: true
7203 });
7204 hammertime2.on('pinch pinchmove pinchcancel pinchin pinchout pinchend pinchstart', function (e) {
7205 e.preventDefault();
7206 });
7207 // var hammertime3 = new Hammer($("custom-infobox")[0], {
7208 // prevent_default: false,
7209 // touchAction: "pan"
7210 // });
7211 // hammertime3.get('pinch').set({enable:true});
7212 // hammertime3.on('pinch pinchmove pinchcancel pinchin pinchout pinchend pinchstart', function(e){
7213 // e.preventDefault();
7214 // });
7215
7216 function formatUrl(url) {
7217 if (url) {
7218 url = url.trim();
7219 var httpString = "http://";
7220 var httpsString = "https://";
7221 if (url.substr(0, httpString.length).toLowerCase() !== httpString && url.substr(0, httpsString.length).toLowerCase() !== httpsString) {
7222 url = httpString + url;
7223 }
7224 }
7225
7226 return url;
7227 }
7228
7229 /**
7230 *
7231 */
7232 $("#marker-info-modal .url").on("click", function (event) {
7233 var interaction = $(this).data('interaction');
7234 var park_id = $(this).data('park_id');
7235 $.get('https://www.rvparkreviews.com/interactions/event/' + interaction + '/' + park_id, {}, function (data) {
7236
7237 });
7238 });
7239
7240 function getMarkerId(poi) {
7241 var id;
7242 if (poi.id && poi.id > 0) {
7243 id = poi.id + '-' + poi.poitype_id;
7244 } else {
7245 id = poi.lat + "|" + poi.lon + '-' + poi.poitype_id;
7246 }
7247
7248 return id;
7249 }
7250
7251 $('.filter-show-filters, .filter-show-filters-bottom').click(function () {
7252 $('.parks-filter-list').toggle();
7253 $('.set-filters-view').toggle();
7254 $('.filter-sort').toggle();
7255
7256 if ($('.filter-show-filters').text() == "Show Filters") {
7257 $('.filter-show-filters-bottom').html("Show Parks List");
7258 $('.filter-show-filters').html("Show Parks List");
7259 if (!$('.add-filters').hasClass('selected')) {
7260 $('.add-filters-button-text').html('<i class="fa fa-filter gray-filter-icon"></i> 0 Active Filters');
7261 }
7262 } else {
7263 $('.filter-show-filters-bottom').html("Show Filters");
7264 $('.filter-show-filters').html("Show Filters");
7265 if (!$('.add-filters').hasClass('selected')) {
7266 $('.add-filters-button-text').html('<i class="fa fa-filter green-filter-icon"></i> Add Filters');
7267 }
7268
7269 }
7270 });
7271
7272 $('.add-filters').click(function () {
7273 if ($('.footer-buttons').children().length > 0) {
7274 $('.footer-buttons').toggleClass('hidden');
7275 if ($('#footer-buttons-filter').hasClass('hidden')) {
7276 $('.add-filters').children('span').html('Filters (' + $(".footer-buttons").children().length + ') <img src="images/filters-up.svg">');
7277 } else {
7278 $('.add-filters').children('span').html('Filters (' + $(".footer-buttons").children().length + ') <img src="images/filters-down.svg">');
7279 }
7280 } else if ($('.add-filters-button-text').text() == " Add Filters") {
7281 $('.filter-show-filters').click();
7282 }
7283 });
7284
7285 $('.ratingbutton').on("click", function () {
7286 var ratingFloor = $(this).children(0).attr("id");
7287 $('.footer-filter-button.allratings').remove();
7288 if (ratingFloor == "threeplus") {
7289 activeFilters.rating[0] = 3;
7290 addFilterToFooter("Three Stars", $("#allratings").attr('id'));
7291 } else if (ratingFloor == "fourplus") {
7292 activeFilters.rating[0] = 4;
7293 addFilterToFooter("Four Stars", $("#allratings").attr('id'));
7294 } else if (ratingFloor == "fiveplus") {
7295 activeFilters.rating[0] = 4.5;
7296 addFilterToFooter("Five Stars", $("#allratings").attr('id'));
7297 } else {
7298 activeFilters.rating[0] = 0;
7299 }
7300 activeFilters.rating[1] = 5;
7301 updateFilterFooter();
7302 updateParksFiltering();
7303 updateFilterIndicator();
7304 saveFilters();
7305 });
7306
7307 // $("#filter-rating-slider").on("slide", function(slideEvt) {
7308 // $(".filter-rating-text").html(slideEvt.value[0]+" - "+slideEvt.value[1]);
7309 // activeFilters['rating'][0] = slideEvt.value[0];
7310 // activeFilters['rating'][1] = slideEvt.value[1];
7311 // updateParksFiltering();
7312 // });
7313
7314 $('.clear-filters').click(function () {
7315 $(".filter-rating-text").html("Any Rating");
7316
7317 $('.footer-buttons').children().click();
7318
7319 updateParksFiltering();
7320 saveFilters();
7321 });
7322
7323 function updateParksFiltering() {
7324 var noParks;
7325 if (map.getZoom() < 8) {
7326 noParks = document.createElement("span");
7327 noParks.classList.add('no-parks-filter-text');
7328 noParks.innerHTML = "Please Zoom In To View Parks";
7329 $("#parks-filter-body").empty();
7330 $("#parks-filter-body").append(noParks);
7331 $('.parks-filter-count').html("0");
7332 if ($('.filter-show-filters').text() == "Show Parks List") {
7333 $('.filter-show-filters').click();
7334 }
7335 return;
7336 }
7337
7338 filteredParks = parksInView.filter(filterParks);
7339 $('.parks-filter-count').html(filteredParks.length);
7340 if (filteredParks.length == 0) {
7341 noParks = document.createElement("span");
7342 noParks.classList.add('no-parks-filter-text');
7343 noParks.innerHTML = "No parks meet your filter criteria. Remove filters to display more parks or zoom to a different area of the map.";
7344 $("#parks-filter-body").empty();
7345 $("#parks-filter-body").append(noParks);
7346 return;
7347 }
7348 updateParkPreviews(filteredParks);
7349
7350 if (filterMapped == false) {
7351 filterMapped = true;
7352 callDoSearch();
7353 } else {
7354 filterMapped = false;
7355 }
7356
7357 //updates the text and count for each filter
7358 updateFilterButtons();
7359 }
7360
7361 function updateParkPreviews(parks) {
7362 parks = getPreviewDistances(parks);
7363 parks = sortParksByKey(parks, filterSortKey);
7364 $("#parks-filter-body").empty();
7365 parks.forEach(function (p, i) {
7366 park = formatParkObject(p);
7367 if (park.makrer) {
7368 park.marker.setAnimation(null);
7369 }
7370 var div = createParkPreview(park, i);
7371 //add bottom border line
7372 $("#parks-filter-body").append(div);
7373 });
7374 }
7375
7376 function getPreviewDistances(parks) {
7377 var selectedPoi = getSelectedPoiStopOrDefault();
7378 if (!selectedPoi) {
7379 return parks;
7380 }
7381 resultParks = [];
7382 parks.forEach(function (p, index) {
7383 park = formatParkObject(p);
7384 parks[index].haversine = haversineDistance(selectedPoi.lat, selectedPoi.lon, park.lat, park.lon, true);
7385 });
7386 return parks;
7387 }
7388
7389 function sortParksByKey(array, key) {
7390 if (!array) {
7391 return array;
7392 }
7393 if (key == 'name') {
7394 return array.sort(function (a, b) {
7395 var x = a.name;
7396 var y = b.name;
7397 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
7398 });
7399 } else if (key == 'rating asc') {
7400 return array.sort(function (a, b) {
7401 var x = a.rating_avg;
7402 var y = b.rating_avg;
7403 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
7404 });
7405 } else if (key == 'rating desc') {
7406 return array.sort(function (a, b) {
7407 var x = a.rating_avg;
7408 var y = b.rating_avg;
7409 return ((x > y) ? -1 : ((x < y) ? 1 : 0));
7410 });
7411 } else if (key == 'reviews') {
7412 return array.sort(function (a, b) {
7413 var x = a.review_count;
7414 var y = b.review_count;
7415 return ((x > y) ? -1 : ((x < y) ? 1 : 0));
7416 });
7417 } else if (key == 'photos') {
7418 return array.sort(function (a, b) {
7419 var x = a.photos.length;
7420 var y = b.photos.length;
7421 return ((x > y) ? -1 : ((x < y) ? 1 : 0));
7422 });
7423 } else if (key == 'distance') {
7424 return array.sort(function (a, b) {
7425 var x = a.haversine;
7426 var y = b.haversine;
7427 if (debug) console.log(a, b);
7428 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
7429 });
7430 }
7431
7432 }
7433
7434 function filterParks(park) {
7435 if (debug) console.log("filterParks()");
7436
7437 if (park.park_info == null) {
7438 return false;
7439 }
7440 //assume a null rating is a 0 rating
7441 var rating = 0;
7442 if (park.rating != null) {
7443 rating = park.rating;
7444 } else if (park.rating_avg != null) {
7445 rating = Math.round(park.rating_avg) / 2;
7446 }
7447
7448 var priceIn = activeFilters.price.every(function (e1) {
7449 if (e1 == park.price_level) {
7450 return true;
7451 }
7452 });
7453
7454 var clubIn = activeFilters.clubs.every(function (e1) {
7455 var r = false;
7456 park.affiliations.forEach(function (e2) {
7457 if (e1 == e2.name) {
7458 if (debug) console.log('woop');
7459 r = true;
7460 }
7461 });
7462 return r;
7463 });
7464
7465 var hookupIn = false;
7466 if (activeFilters.hookups.length != 0) {
7467 hookupIn = activeFilters.hookups.every(function (e1) {
7468 var r = false;
7469 for (var e2 in park.park_info['Hookups_&_Connectivity']) {
7470 if (e1 == park.park_info['Hookups_&_Connectivity'][e2].desc && park.park_info['Hookups_&_Connectivity'][e2].value) {
7471 r = true;
7472 }
7473 }
7474 return r;
7475 });
7476 }
7477
7478 var amenitiesIn = false;
7479 if (activeFilters.amenities.length != 0) {
7480 amenitiesIn = activeFilters.amenities.every(function (e1) {
7481 var r = false;
7482 for (var e2 in park.park_info.Amenities) {
7483 if (e1 == park.park_info.Amenities[e2].desc && park.park_info.Amenities[e2].value) {
7484 r = true;
7485 }
7486 }
7487 return r;
7488 });
7489 }
7490
7491 var featuresIn = false;
7492 if (activeFilters.features.length != 0) {
7493 featuresIn = activeFilters.features.every(function (e1) {
7494 var r = false;
7495 for (var e2 in park.park_info.Park_Features) {
7496 if (e1 == park.park_info.Park_Features[e2].desc && park.park_info.Park_Features[e2].value) {
7497 r = true;
7498 }
7499 }
7500 return r;
7501 });
7502 }
7503
7504 var recreationIn = false;
7505 if (activeFilters.recreation.length != 0) {
7506 recreationIn = activeFilters.recreation.every(function (e1) {
7507 var r = false;
7508 for (var e2 in park.park_info.Recreation) {
7509 if (e1 == park.park_info.Recreation[e2].desc && park.park_info.Recreation[e2].value) {
7510 r = true;
7511 }
7512 }
7513 return r;
7514 });
7515 }
7516 if (park.park_id == null) {
7517 return false;
7518 } else if (activeFilters.rating && rating < activeFilters.rating[0] || rating > activeFilters.rating[1]) {
7519 return false;
7520 } else if (!priceIn && activeFilters.price.length != 0) {
7521 return false;
7522 } else if (!activeFilters.types.includes(park.park_type) && activeFilters.types.length != 0) {
7523 return false;
7524 } else if (!clubIn && activeFilters.clubs.length != 0) {
7525 return false;
7526 } else if (!hookupIn && activeFilters.hookups.length != 0) {
7527 return false;
7528 } else if (!amenitiesIn && activeFilters.amenities.length != 0) {
7529 return false;
7530 } else if (!featuresIn && activeFilters.features.length != 0) {
7531 return false;
7532 } else if (!recreationIn && activeFilters.recreation.length != 0) {
7533 return false;
7534 } else {
7535 return true;
7536 }
7537 }
7538
7539 function createParkPreview(park, index) {
7540 var div = document.createElement("div");
7541 div.classList.add('park-filter-preview-box');
7542 var span1 = document.createElement("span");
7543 span1.classList.add('park-filter-preview-name');
7544 span1.innerHTML = park.name;
7545
7546 var imgBox = document.createElement("img");
7547 imgBox.style.width = "116px";
7548 imgBox.style.height = "80px";
7549 imgBox.style.marginTop = "11px";
7550 if (park && park.photos && park.photos.length > 0) {
7551 imgBox.src = park.photos[0].url;
7552 } else {
7553 imgBox.src = "images/rvtw-nophoto.jpg";
7554 }
7555 curRoute.routeLegs.forEach(function (leg) {
7556 if (leg.poi.park_id) {
7557 if (leg.poi.park_id == park.park_id) {
7558 div.classList.add('park-preview-background');
7559 }
7560 }
7561 });
7562 var span2 = document.createElement("span");
7563 span2.classList.add('park-filter-preview-location');
7564 span2.innerHTML = park.city + ", " + park.region_abbr;
7565
7566 div.appendChild(imgBox);
7567 div.appendChild(span1);
7568 div.appendChild(span2);
7569
7570 var span3 = document.createElement("span");
7571 span3.classList.add('park-filter-preview-distance');
7572 var selectedPoi = getSelectedPoiStopOrDefault();
7573 var parkDistance = park.haversine;
7574 if (parkDistance != 0) {
7575 span3.innerHTML = "apx mi: " + parkDistance;
7576 div.appendChild(span3);
7577 }
7578
7579 var $ratingContainer = $('<div></div>').addClass('filter-rating');
7580 var $starsContainer = $('<div></div>').addClass('stars');
7581 var $numReviewsContainer = $('<div></div').addClass("filter-numReviews");
7582
7583 $numReviewsContainer.text(' (' + park.rating_count + ')');
7584
7585 for (var i = 0; i < 5; i++) {
7586 var $star = $('<i></i>').addClass('fa')
7587 .addClass('fa-star-o filter-color');
7588 $starsContainer.append($star);
7589 }
7590 $starsContainer.append($numReviewsContainer);
7591 $ratingContainer.append($starsContainer);
7592
7593 function fillStars(rating) {
7594 if (!rating) {
7595 return;
7596 }
7597 //$element.find('.rating').addClass('rating-' + _global.ratingCaptions[Math.round(rating)].toLowerCase());
7598
7599 var $stars = $ratingContainer.find('.stars i');
7600 var remainingRating = Math.round(rating);
7601 $.each($stars, function (index, star) {
7602 $(star).removeClass('hidden fa-star fa-star-o fa-star-half-o');
7603 if (remainingRating - 2 >= 0) {
7604 remainingRating -= 2;
7605 $(star).addClass('fa fa-star filter-color');
7606 } else if (remainingRating - 1 >= 0) {
7607 remainingRating -= 1;
7608 $(star).addClass('fa fa-star-half-o');
7609 } else {
7610 $(star).addClass('fa fa-star-o');
7611 }
7612 });
7613 }
7614
7615 fillStars(park.rating_avg);
7616 $(div).append($ratingContainer);
7617
7618 var $affils = $('<span></span>').addClass('filter-affils-container');
7619 if (park.affiliations) {
7620 var affiliations = [];
7621 for (var x = 0; x < park.affiliations.length; x++) {
7622 if (x >= 4) {
7623 break;
7624 }
7625 var affiliation = park.affiliations[x];
7626 if (debug) console.log('affiliation', affiliation);
7627 $($affils).prepend("<span data-affil='" + affiliation.name + "' ><img class=\'filter-affil-data\' src=\"/app/images/marker_img/" + affiliation.image_name + "\"></span>");
7628 }
7629 }
7630 $(div).append($affils);
7631 park.marker = getMarker(park);
7632 div.addEventListener("mouseenter", function () {
7633 if (park.marker) {
7634 park.marker.setAnimation(google.maps.Animation.BOUNCE);
7635 if (debug) console.log('park marker enter', park.marker);
7636 }
7637 }, false);
7638
7639 div.addEventListener("mouseleave", function () {
7640 if (park.marker) {
7641 park.marker.setAnimation(null);
7642 if (debug) console.log('park marker leave', park.marker);
7643 }
7644 }, false);
7645 div.addEventListener("click", function () {
7646 currentPhotos = park.photos;
7647 showDescription(park);
7648 $("#marker-info-modal").modal("show");
7649 }, false);
7650
7651
7652
7653
7654 return div;
7655
7656
7657 }
7658
7659 function haversineDistance(lat1, lon1, lat2, lon2, isMiles) {
7660 function toRad(x) {
7661 return x * Math.PI / 180;
7662 }
7663
7664 var R = 6371; // km
7665
7666 var x1 = lat2 - lat1;
7667 var dLat = toRad(x1);
7668 var x2 = lon2 - lon1;
7669 var dLon = toRad(x2);
7670 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
7671 Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
7672 Math.sin(dLon / 2) * Math.sin(dLon / 2);
7673 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
7674 var d = R * c;
7675
7676 if (isMiles) d /= 1.60934;
7677
7678 return Math.round(d);
7679 }
7680
7681 function sortByOrder(a, b) {
7682 if (a.order < b.order || (a.order != null && b.order == null)) {
7683 return -1;
7684 } else if (a.order > b.order || (a.order == null && b.order != null)) {
7685 return 1;
7686 } else if (a.desc < b.desc) {
7687 return -1;
7688 } else if (a.desc > b.desc) {
7689 return 1;
7690 }
7691 return 0;
7692 }
7693
7694 function initFilters() {
7695 if (debug) console.log("initFilters()");
7696 //Add all possible filter options set to grayed out and (0)
7697 setFilterCategory(filterOptions.park_types.options.sort(sortByOrder), 'types', "#collapseParkTypes");
7698 setFilterCategory(filterOptions.clubs.sort(sortByOrder), 'clubs', "#collapseDiscountClubs");
7699 filterOptions.park_info.forEach(function (e) {
7700 if (e.category == "Park Features") {
7701 setFilterCategory(e.items.sort(sortByOrder), 'features', "#collapseParkFeatures");
7702 } else if (e.category == "Hookups & Connectivity") {
7703 setFilterCategory(e.items.sort(sortByOrder), 'hookups', "#collapseHookupsConnectivity");
7704 } else if (e.category == "Amenities") {
7705 setFilterCategory(e.items.sort(sortByOrder), 'amenities', "#collapseAmenities");
7706 } else if (e.category == "Recreation") {
7707 setFilterCategory(e.items.sort(sortByOrder), 'recreation', "#collapseRecreation");
7708 }
7709 });
7710 setPriceFilters();
7711
7712 //Go through active filters and select the active onBeforeSlide
7713 setActiveButtons();
7714
7715 //Potentially redundant??
7716 updateFilterButtons();
7717
7718 //Click listeners for a button
7719 $('.filter-button').click(function () {
7720 $('.btn-hide-parks').click();
7721 $(this).toggleClass('selected');
7722 $(this).children('span').toggleClass('selected');
7723 if ($(this).hasClass('selected')) {
7724 addFilterToFooter($(this).children('span')[0].innerText, $(this).attr('id'));
7725 if ($(this).children('div').length > 0) {
7726 activeFilters[$(this).attr('type')].push($(this).children('div')[0].innerHTML);
7727 } else {
7728 activeFilters[$(this).attr('type')].push($(this).children('span')[0].innerHTML);
7729 }
7730
7731 } else {
7732 var id = $(this).attr('id');
7733 $('.' + id).remove();
7734 if ($(this).children('div').length > 0) {
7735 activeFilters[$(this).attr('type')].splice(activeFilters[$(this).attr('type')].indexOf($(this).children('div')[0].innerHTML), 1);
7736 } else {
7737 activeFilters[$(this).attr('type')].splice(activeFilters[$(this).attr('type')].indexOf($(this).children('span')[0].innerHTML), 1);
7738 }
7739
7740 }
7741 updateFilterFooter();
7742 updateParksFiltering();
7743 updateFilterIndicator();
7744 saveFilters();
7745 });
7746 }
7747
7748 function setFilterCategory(list, type, parent) {
7749 if (debug) console.log("setFilterCategory()");
7750 if (debug) console.log(list);
7751 $(parent).empty();
7752 var id = 0;
7753 var div = document.createElement("div");
7754 var dvm = document.createElement("div");
7755
7756 div.classList.add('filter-section');
7757 $(parent).append(div);
7758 if (list.length > 4) {
7759 div.setAttribute('style', "padding-bottom: 0px;");
7760 dvm.setAttribute('id', 'collapseViewMore' + type);
7761 dvm.classList.add('card-body');
7762 dvm.classList.add('collapse');
7763 dvm.setAttribute('aria-labelledby', 'headingViewMore' + type);
7764 dvm.setAttribute('aria-expanded', 'false');
7765
7766 var divlink = document.createElement('div');
7767 var link = document.createElement('a');
7768
7769 divlink.setAttribute('style', 'text-align: center');
7770
7771 link.setAttribute('href', '#collapseViewMore' + type);
7772 link.setAttribute('data-toggle', 'collapse');
7773 link.classList.add('filter-view-more-text');
7774 link.classList.add('collapsed');
7775 link.setAttribute('id', 'headingViewMore' + type);
7776 link.setAttribute('aria-expanded', 'false');
7777 link.setAttribute('aria-controls', 'collapseViewMore' + type);
7778
7779 var spanlinkdown = document.createElement('span');
7780 spanlinkdown.innerText = 'View More ';
7781 spanlinkdown.classList.add('down');
7782 var spandownimg = document.createElement('img');
7783 spandownimg.setAttribute('src', 'images/filters-down-green.svg');
7784
7785 var spanlinkup = document.createElement('span');
7786 spanlinkup.innerText = 'View Less ';
7787 spanlinkup.classList.add('up');
7788 var spanupimg = document.createElement('img');
7789 spanupimg.setAttribute('src', 'images/filters-up-green.svg');
7790
7791 spanlinkdown.appendChild(spandownimg);
7792 spanlinkup.appendChild(spanupimg);
7793 link.appendChild(spanlinkdown);
7794 link.appendChild(spanlinkup);
7795
7796 divlink.appendChild(link);
7797 $(parent).append(dvm);
7798 $(parent).append(divlink);
7799 }
7800 list.forEach(function (e) {
7801 var button = document.createElement("button");
7802 // button.setAttribute('disabled', 'true');
7803 button.classList.add('filter-button');
7804 button.setAttribute('type', type);
7805 button.setAttribute("id", type + id);
7806 var span = document.createElement("span");
7807 var span2 = document.createElement("span");
7808 span.classList.add('filter-button-text');
7809 span2.classList.add('filter-button-number');
7810 var hiddenSpan;
7811 var typeBreak = document.createElement("br");
7812 if (type == "types") {
7813 hiddenSpan = $("<div></div>").addClass("hidden types-hidden").text(e.value);
7814 span.innerHTML = e.desc;
7815 } else {
7816 if (debug) console.log(e.desc);
7817 if (debug) console.log(e.desc.length);
7818 span.innerHTML = e.desc;
7819 }
7820 span2.innerHTML = " (0)";
7821 if (type == "types") {
7822 button.appendChild($(hiddenSpan)[0]);
7823 }
7824 button.appendChild(span);
7825 if (type == "types" && e.desc.length < 28) {
7826 button.appendChild(typeBreak);
7827 }
7828 button.appendChild(span2);
7829
7830
7831 //Instead of saying false itll check to see if it is in the top 4
7832 if (e.order != null) {
7833 if (debug) console.log("not null");
7834 div.appendChild(button);
7835 // div.insertBefore(button, div.firstChild);
7836 } else {
7837 if (debug) console.log("null");
7838 dvm.appendChild(button);
7839 }
7840 id = id + 1;
7841 });
7842 }
7843
7844 function setPriceFilters() {
7845 $("#collapseParkPricing").empty();
7846 var map = new Map();
7847
7848 map.set("1", 0);
7849 map.set("2", 0);
7850 map.set("3", 0);
7851 map.set("4", 0);
7852 var mapArray = [];
7853 map.forEach(function (num, rank, m) {
7854 mapArray.push([rank, num]);
7855 });
7856 map = new Map(mapArray.sort());
7857 var div = document.createElement("div");
7858 div.classList.add('filter-section');
7859 var count = 0;
7860 map.forEach(function (value, key) {
7861 var button = document.createElement("button");
7862 button.classList.add('filter-button');
7863 button.classList.add('price');
7864 button.setAttribute('type', 'price');
7865 button.setAttribute('id', 'price' + count);
7866 button.style.width = '20%';
7867
7868 var span = document.createElement("span");
7869 span.classList.add('filter-button-number');
7870 span.innerHTML = " (" + value + ")";
7871 var span2 = document.createElement("span");
7872 span2.classList.add('hidden', 'key', 'filter-button-text');
7873 span2.innerHTML = key;
7874 button.appendChild(span2);
7875 for (var i = 0; i < 4; i++) {
7876 var $dollar;
7877 if (i < key) {
7878 $dollar = $('<i></i>').addClass('fa')
7879 .addClass('fa-dollar filter-color');
7880 }
7881 $(button).append($dollar);
7882 }
7883 button.appendChild(span);
7884 button.onclick = function () {
7885 $(button).find('i').toggleClass('dollar-clicked');
7886 };
7887 div.appendChild(button);
7888 count = count + 1;
7889 });
7890
7891 $("#collapseParkPricing").append(div);
7892 }
7893
7894 function setActiveButtons() {
7895 $('.filter-button').removeClass('selected');
7896 $('.filter-button').children('.filter-button-text').removeClass('selected');
7897 $('.filter-button').children('.filter-button-number').removeClass('selected');
7898 for (var type in activeFilters) {
7899 activeFilters[type].forEach(function (q) {
7900 if (type == 'rating') {
7901 if (debug) console.log('rating!!\n\n', q);
7902 if (q == 0) {
7903 $('#allratings').parent().addClass('active');
7904 $('#threeplus').parent().removeClass('active');
7905 $('#fourplus').parent().removeClass('active');
7906 $('#fiveplus').parent().removeClass('active');
7907 } else if (q == 3) {
7908 $('#allratings').parent().removeClass('active');
7909 $('#threeplus').parent().addClass('active');
7910 $('#fourplus').parent().removeClass('active');
7911 $('#fiveplus').parent().removeClass('active');
7912 addFilterToFooter("Three Stars", $('#allratings').attr("id"));
7913 } else if (q == 4) {
7914 $('#allratings').parent().removeClass('active');
7915 $('#threeplus').parent().removeClass('active');
7916 $('#fourplus').parent().addClass('active');
7917 $('#fiveplus').parent().removeClass('active');
7918 addFilterToFooter("Four Stars", $('#allratings').attr("id"));
7919 } else if (q == 4.5) {
7920 $('#allratings').parent().removeClass('active');
7921 $('#threeplus').parent().removeClass('active');
7922 $('#fourplus').parent().removeClass('active');
7923 $('#fiveplus').parent().addClass('active');
7924 addFilterToFooter("Five Stars", $('#allratings').attr("id"));
7925 }
7926 return;
7927
7928 } else {
7929 var selector = '.filter-button-text';
7930 if (type == 'types') {
7931 selector = '.types-hidden';
7932 }
7933 var match = $('.filter-button[type="' + type + '"]').find(selector).filter(function () {
7934 return $(this).text() == q;
7935 });
7936 match.addClass('selected');
7937 match.siblings().addClass('selected');
7938 match.parent().addClass('selected');
7939 if (type == 'price') {
7940 match.siblings().not('.filter-button-number').addClass('dollar-clicked');
7941 match.siblings().not('.filter-button-number').removeClass('dollar');
7942 }
7943 addFilterToFooter(match.text(), match.parent().attr('id'));
7944 }
7945 });
7946 }
7947 }
7948
7949 function updateFilterButtons(typeFlag) {
7950 if (debug) console.log("updateFilterButtons()");
7951
7952 var types = new Map();
7953 var clubs = new Map();
7954 var price = new Map();
7955 var hookups = new Map();
7956 var amenities = new Map();
7957 var features = new Map();
7958 var recreation = new Map();
7959
7960 parksInView.forEach(function (obj, i) {
7961 //Park Type
7962 if (types.has(obj.park_type)) {
7963 types.set(obj.park_type, types.get(obj.park_type) + 1);
7964 } else if (obj.park_type != "") {
7965 types.set(obj.park_type, 1);
7966 }
7967 });
7968
7969 filteredParks.forEach(function (obj, i) {
7970
7971 //Discount Clubs
7972 if (obj.affiliations != null) {
7973 obj.affiliations.forEach(function (obj, i) {
7974 if (clubs.has(obj.name)) {
7975 clubs.set(obj.name, clubs.get(obj.name) + 1);
7976 } else if (obj.name != "") {
7977 clubs.set(obj.name, 1);
7978 }
7979 });
7980 }
7981
7982 //Park Price
7983 if (price.has("p" + obj.price_level)) {
7984 price.set("p" + obj.price_level, price.get("p" + obj.price_level) + 1);
7985 } else if ("p" + obj.price_level != "") {
7986 price.set("p" + obj.price_level, 1);
7987 }
7988 var h, key;
7989 //Hookups and Connectivity
7990 if (obj.park_info['Hookups_&_Connectivity'] != null) {
7991 h = obj.park_info['Hookups_&_Connectivity'];
7992 for (key in h) {
7993 if (h[key].type == 'bool' && h[key].value == true) {
7994 if (hookups.has(h[key].desc)) {
7995 hookups.set(h[key].desc, hookups.get(h[key].desc) + 1);
7996 } else if (h[key].desc != "") {
7997 hookups.set(h[key].desc, 1);
7998 }
7999 }
8000 }
8001 }
8002
8003 //Amenities
8004 if (obj.park_info.Amenities != null) {
8005 h = obj.park_info.Amenities;
8006 for (key in h) {
8007 if (h[key].type == 'bool' && h[key].value == true) {
8008 if (amenities.has(h[key].desc)) {
8009 amenities.set(h[key].desc, amenities.get(h[key].desc) + 1);
8010 } else if (h[key].desc != "") {
8011 amenities.set(h[key].desc, 1);
8012 }
8013 }
8014 }
8015 }
8016
8017 //Features
8018 if (obj.park_info.Park_Features != null) {
8019 h = obj.park_info.Park_Features;
8020 for (key in h) {
8021 if (h[key].type == 'bool' && h[key].value == true) {
8022 if (features.has(h[key].desc)) {
8023 features.set(h[key].desc, features.get(h[key].desc) + 1);
8024 } else if (h[key].desc != "") {
8025 features.set(h[key].desc, 1);
8026 }
8027 }
8028 }
8029 }
8030
8031 //Recreation
8032 if (obj.park_info.Recreation != null) {
8033 h = obj.park_info.Recreation;
8034 for (key in h) {
8035 if (h[key].type == 'bool' && h[key].value == true) {
8036 if (recreation.has(h[key].desc)) {
8037 recreation.set(h[key].desc, recreation.get(h[key].desc) + 1);
8038 } else if (h[key].desc != "") {
8039 recreation.set(h[key].desc, 1);
8040 }
8041 }
8042 }
8043 }
8044 });
8045
8046 $('.filter-button[type="price"]').each(function () {
8047 var count = price.get("p" + $(this).children('span')[0].innerText);
8048 if (count <= 0) {
8049 count = 0;
8050 $(this).attr('disabled', true);
8051 } else {
8052 $(this).attr('disabled', false);
8053 }
8054 $(this).find('.filter-button-number').text(" (" + count + ")");
8055 });
8056
8057 $('.filter-button[type="features"]').each(function () {
8058 var count = features.get($(this).children('span')[0].innerText);
8059 if (count <= 0) {
8060 count = 0;
8061 $(this).attr('disabled', true);
8062 } else {
8063 $(this).attr('disabled', false);
8064 }
8065 $(this).children('span')[1].innerText = " (" + count + ")";
8066 });
8067
8068 $('.filter-button[type="recreation"]').each(function () {
8069 var count = recreation.get($(this).children('span')[0].innerText);
8070 if (count <= 0) {
8071 count = 0;
8072 $(this).attr('disabled', true);
8073 } else {
8074 $(this).attr('disabled', false);
8075 }
8076 $(this).children('span')[1].innerText = " (" + count + ")";
8077 });
8078
8079 $('.filter-button[type="types"]').each(function () {
8080 var count = types.get($(this).children('div')[0].innerText);
8081 if (count <= 0) {
8082 count = 0;
8083 $(this).attr('disabled', true);
8084 } else {
8085 $(this).attr('disabled', false);
8086 }
8087 $(this).children('span')[1].innerText = " (" + count + ")";
8088 });
8089
8090 $('.filter-button[type="clubs"]').each(function () {
8091 var count = clubs.get($(this).children('span')[0].innerText);
8092 if (count <= 0) {
8093 count = 0;
8094 $(this).attr('disabled', true);
8095 } else {
8096 $(this).attr('disabled', false);
8097 }
8098 $(this).children('span')[1].innerText = " (" + count + ")";
8099 });
8100
8101 $('.filter-button[type="hookups"]').each(function () {
8102 var count = hookups.get($(this).children('span')[0].innerText);
8103 if (count <= 0) {
8104 count = 0;
8105 $(this).attr('disabled', true);
8106 } else {
8107 $(this).attr('disabled', false);
8108 }
8109 $(this).children('span')[1].innerText = " (" + count + ")";
8110 });
8111
8112 $('.filter-button[type="amenities"]').each(function () {
8113 var count = amenities.get($(this).children('span')[0].innerText);
8114 if (count <= 0) {
8115 count = 0;
8116 $(this).attr('disabled', true);
8117 } else {
8118 $(this).attr('disabled', false);
8119 }
8120 $(this).children('span')[1].innerText = " (" + count + ")";
8121 });
8122
8123 }
8124
8125 function addFilterToFooter(text, id) {
8126 if (debug) console.log("addFilterToFooter()");
8127 if (!id) {
8128 return;
8129 }
8130 if (id.substr(0, 5) == "price") {
8131 text = "Price " + text;
8132 }
8133
8134 var b = document.createElement("button");
8135 b.classList.add('footer-filter-button');
8136 b.classList.add(id);
8137
8138 var span2 = document.createElement("span");
8139 span2.classList.add('filter-footer-button-text');
8140 span2.innerHTML = text + '<img class="filter-x" src="images/filter-x.svg"></img>';
8141 b.appendChild(span2);
8142 $('.footer-buttons').append(b);
8143
8144 $(b).click(function () {
8145 $(this).remove();
8146 $("#" + id).click();
8147 });
8148 }
8149
8150 function updateFilterFooter() {
8151 if ($(".footer-buttons").children().length == 0) {
8152 $('.add-filters').removeClass('selected');
8153 $('.add-filters-button-text').removeClass('selected');
8154 if ($('.filter-show-filters').text() == "Show Filters") {
8155 $('.add-filters-button-text').html('<i class="fa fa-filter green-filter-icon"></i> Add Filters');
8156 } else {
8157 $('.add-filters-button-text').html('<i class="fa fa-filter gray-filter-icon"></i> 0 Active Filters');
8158 }
8159 $('.clear-filters').addClass('hidden');
8160 } else if ($(".footer-buttons").children().length >= 1) {
8161 $('.add-filters').addClass('selected');
8162 $('.add-filters-button-text').addClass('selected');
8163 if (debug) console.log("GO BIRDS");
8164 if ($('#footer-buttons-filter').hasClass('hidden')) {
8165 $('.add-filters').children('span').html('Filters (' + $(".footer-buttons").children().length + ') <img src="images/filters-up.svg">');
8166 } else {
8167 $('.add-filters').children('span').html('Filters (' + $(".footer-buttons").children().length + ') <img src="images/filters-down.svg">');
8168 }
8169 $('.clear-filters').removeClass('hidden');
8170 }
8171 }
8172
8173 function updateFilterIndicator() {
8174 if ($('.footer-buttons').children().length == 0) {
8175 $('#show_hide_filter').removeClass('active');
8176 $('.indicator-active').addClass('hidden');
8177 $('.indicator-inactive').removeClass('hidden');
8178 $('.filter-badge').addClass('hidden');
8179 $('#show_hide_filter').attr("data-content", 'No Active Park Filters');
8180 } else if ($('.footer-buttons').children().length >= 1) {
8181 if ($('#show_hide_parks').hasClass('btn-hide-parks')) {
8182 $('#show_hide_parks').click();
8183 }
8184 $('#show_hide_filter').addClass('active');
8185 $('.indicator-active').removeClass('hidden');
8186 $('.indicator-inactive').addClass('hidden');
8187 $('.filter-badge').removeClass('hidden');
8188 $('.filter-badge').text($('.footer-buttons').children().length);
8189 $('.filter-badge').css('background', '#DE0909');
8190 $('#show_hide_filter').attr("data-content", $(".footer-buttons").children().length + ' Active Park Filters');
8191 }
8192 }
8193
8194 if (!$('#show_hide_parks').hasClass('active')) {
8195 if (debug) console.log("HERE");
8196 hideParks();
8197 $("#show_hide_parks").removeClass('btn-show-parks');
8198 $("#show_hide_parks").removeClass('active');
8199 $("#show_hide_parks").addClass('btn-hide-parks');
8200 $("#show_hide_parks").children().eq(0).prop('hidden', true);
8201 $("#show_hide_parks").children().eq(1).prop('hidden', false);
8202 disableCgPoiLoading = true;
8203 }
8204
8205 $('#show_hide_parks').click(function () {
8206 if ($(this).hasClass('btn-hide-parks')) {
8207 showParks();
8208 $(this).removeClass('btn-hide-parks');
8209 $(this).addClass('active');
8210 $(this).addClass('btn-show-parks');
8211 $("#show_hide_parks").children().eq(1).prop('hidden', true);
8212 $("#show_hide_parks").children().eq(0).prop('hidden', false);
8213 } else {
8214 hideParks();
8215 $(this).removeClass('btn-show-parks');
8216 $(this).removeClass('active');
8217 $(this).addClass('btn-hide-parks');
8218 $("#show_hide_parks").children().eq(0).prop('hidden', true);
8219 $("#show_hide_parks").children().eq(1).prop('hidden', false);
8220 }
8221 });
8222
8223 $('.show-hide-filters').click(function () {
8224 if ($('#show_hide_parks').hasClass('btn-hide-parks') && $(this).hasClass('btn-hide-filter')) {
8225 $('#show_hide_parks').click();
8226 }
8227
8228 if ($(this).hasClass('btn-hide-filter')) {
8229 $(this).removeClass('btn-hide-filter');
8230 $(this).addClass('active');
8231 $(this).addClass('btn-show-filter');
8232 } else {
8233 $(this).addClass('btn-hide-filter');
8234 if ($(".set-filters-view").css('display') == 'none') {
8235 $('#filter-show-filters').click();
8236 }
8237 }
8238
8239
8240 if ($("#show_hide_filter").hasClass('active')) {
8241 activeFilters = {
8242 rating: [0, 5],
8243 price: [],
8244 types: [],
8245 clubs: [],
8246 hookups: [],
8247 amenities: [],
8248 features: [],
8249 recreation: []
8250 };
8251 $('.footer-buttons').empty();
8252 $('#show_hide_filter').removeClass('active');
8253 $('.indicator-active').addClass('hidden');
8254 $('.indicator-inactive').removeClass('hidden');
8255 $('.filter-badge').removeClass('hidden');
8256 $('.filter-badge').css('background', '#B8B8B8');
8257 } else {
8258 if ($(window).width() < 1200) {
8259 $("#collapse-tiny-filter-nav").click();
8260 } else {
8261 if (!$(".aside-right").hasClass("desk-visible-right")) {
8262 $("#collapse-filter-nav").click();
8263 $(".footer-buttons").removeClass('hidden');
8264 }
8265 }
8266 getSavedFilters();
8267 }
8268
8269 updateFilterFooter();
8270 setActiveButtons();
8271 updateParksFiltering();
8272 });
8273
8274 $('.filter-dropdown-text').click(function (event) {
8275 if (debug) console.log('this', this);
8276 switch (this.innerHTML) {
8277 // case "By Distance(ASC)":
8278 // debug && console.log('dist asc');
8279 // break;
8280 // case "By Distance(Desc)":
8281 // debug && console.log('dist desc');
8282 // break;
8283 case "By Rating (Desc)":
8284 if (debug) console.log("rating desc");
8285 filterSortKey = "rating desc";
8286 break;
8287 case "By Rating (Asc)":
8288 if (debug) console.log("rating asc");
8289 filterSortKey = "rating asc";
8290 break;
8291 case "Alphabetically":
8292 filterSortKey = "name";
8293 break;
8294 case "Reviews":
8295 filterSortKey = "reviews";
8296 break;
8297 case "Photos":
8298 filterSortKey = "photos";
8299 break;
8300 case "Distance":
8301 filterSortKey = "distance";
8302 break;
8303 default:
8304 filterSortKey = "rating desc";
8305 }
8306 updateParksFiltering();
8307 return;
8308 });
8309
8310 $('.filter-header').on('click', '.btn', function () {
8311 if (!$(this).hasClass('filter-header-icon-active')) {
8312 $(this).addClass('filter-header-icon-active');
8313 $(this).children('img').toggleClass('hidden');
8314 $(this).siblings().removeClass('filter-header-icon-active');
8315 $(this).siblings().children('img').toggleClass('hidden');
8316 }
8317 });
8318
8319 $("#divMap").click(function () {
8320 if ($('#toggle-side-bar-tiny').hasClass('active')) {
8321 $('#toggle-map-view-tiny').click();
8322 }
8323 });
8324
8325 $("#filter-poi").click(function () {
8326 // if(!rvTripHelper.isDevice()){
8327 // $('#filter-poi').attr('style','top:1px');
8328 // $('#filter-parks').attr('style','top:1px');
8329 // }
8330 $('#parks-filters-side').hide();
8331 $('#parks-poi-body').show();
8332 });
8333
8334 $("#filter-parks").click(function () {
8335 // if(!rvTripHelper.isDevice()){
8336 // $('#filter-poi').attr('style','top:0px');
8337 // $('#filter-parks').attr('style','top:0px');
8338 // }
8339 $('#parks-filters-side').show();
8340 $('#parks-poi-body').hide();
8341 });
8342
8343 $('.clear-pois').click(function () {
8344 $('.clear-all').click();
8345 saveTopPois();
8346 return false;
8347 });
8348
8349 $('.add-pois').click(function () {
8350 $('.footer-buttons-poi').toggle();
8351 if ($('.footer-buttons-poi').css('display') == 'none') {
8352 $('.add-pois').children('span').html('POI Types (' + filterCount + ') <img src="images/filters-up.svg">');
8353 } else {
8354 $('.add-pois').children('span').html('POI Types (' + filterCount + ') <img src="images/filters-down.svg">');
8355 }
8356 });
8357
8358 $('.expand-collapse-groups').click(function () {
8359 if ($(this).children('a').text() == 'Expand All') {
8360 $('#accordion-filters .collapse').collapse('show');
8361 } else {
8362 $('#accordion-filters .collapse').collapse('hide');
8363 }
8364 });
8365}