PageSourceSearch

https://www.rangerboats.com/etc/designs/baseDesign/clientlibs-dealer.be3f9f5489d425979aa1d6f3c91a56ba.js

js rangerboats.com collected 2026-10-02 16:59:18 UTC 89,565 bytes, 2,368 lines download raw bytes

1'use strict';
2var long;
3var lat;
4var address;
5var searchAddress;
6var country;
7var placeID;
8
9function getLongLat() {
10	if (navigator.geolocation) {
11		navigator.geolocation.getCurrentPosition(showPositions, showError);
12	} else {
13		console.error("Browser does not support geolocation.")
14	}
15}
16
17function showPositions(pos) {
18	if (pos) {
19		lat = pos.coords.latitude;
20		long = pos.coords.longitude;
21	} else if (getCookie("Geo") != null && getCookie("Geo") !== "") {
22		var cordlist = getCookie("Geo").split('|');
23		lat = cordlist[0];
24		long = cordlist[1];
25	}
26		
27	getAddress(lat, long).then(function (data) {
28		if (data.geoloc != undefined) {
29			var cityState = data.geoloc.CITY + ", " + data.geoloc.STATE; 
30			createGeoLS(lat, long, cityState, data.geoloc.ZIP);
31		} else if (getCookie("Geo") != null && getCookie("Geo") !== "") {
32			processGeoCookie(getCookie("Geo"));
33			var cordlist = getCookie("initlatlng").split('|');
34			lat = cordlist[0];
35			long = cordlist[1];
36			createGeoLS(lat, long, address, getCookie("initzip"));
37		}
38	
39	});
40	var setGeoDealer = $("#dlbSetDealer").data("value");
41	if ( setGeoDealer ){
42		findSetDealer(pos, lat, long);
43	}
44}
45
46
47function showError(error) {
48	switch (error.code) {
49	case error.PERMISSION_DENIED:
50		console.log("User denied the request for Geolocation.");
51		showPositions();
52		break;
53	case error.POSITION_UNAVAILABLE:
54		console.log("Location information is unavailable.");
55		showPositions();
56		break;
57	case error.TIMEOUT:
58		console.log("The request to get user location timed out.");
59		showPositions();
60		break;
61	case error.UNKNOWN_ERROR:
62		console.log("An unknown error occurred.");
63		showPositions();
64		break;
65	}
66}
67
68function setUserBrowserGeoLocationInCookie() {
69	var userGeoLatitude = getCookie("userGeoLatitude");
70	var userGeoLongitude = getCookie("userGeoLongitude");
71	if (!userGeoLatitude || !userGeoLongitude) { 
72		getLongLat();
73	}	
74}
75
76function setInitVals() {
77	var geocookie = getCookie("Geo");
78	var initlatlng = getCookie("initlatlng");
79	
80	if ( geocookie && !initlatlng ) {
81		processGeoCookie(geocookie);
82	} else if ( !geocookie && initlatlng ) {
83		processGeoCookie(getCookie("initlatlng") + "|" + getCookie("initzip"));
84	}
85}
86
87jQuery(document).ready(function($) {
88
89	// starts the app.
90	var d = getGeoLS();
91	
92	setInitVals();
93	
94	if (!d) {
95		getLongLat();
96	} else {
97		// console.log(JSON.stringify(d, undefined, 2));
98	}
99
100
101});
102
103
104/*******************************************************************************
105 * get the address of the lat/long from google maps api
106 * 
107 * @PROMISE resolves an object that holds a lot of information about the lat and
108 *          long.
109 * @param lat;
110 *            the latitude of the users location
111 * @param long;
112 *            The longitude of the users location
113 * 
114 * 
115 ******************************************************************************/
116function getAddress(lat, long) {
117    var newSearch = "";
118    if(jQuery("#jsVars").attr("data-newSearch") == "true")
119		newSearch = "&newSearch="+jQuery("#jsVars").attr("data-newSearch");
120	return new Promise(function (resolve, reject) {
121		jQuery.ajax({
122			url: "/bin/boating-sites/geoloc?lat=" + lat + "&long=" + long + newSearch,
123			dataType: 'json',
124			success: function (data) {
125				resolve(data);
126			},
127			error: function (request, error) {
128				reject(request, error);
129			}
130		});
131	});
132}
133
134/*******************************************************************************
135 * This creates a local storage, of the long, lat, and address.
136 * 
137 * @param lat;
138 *            the latitude of the users location
139 * @param long;
140 *            The longitude of the users location
141 * @param address;
142 *            The returned address from google maps.
143 * 
144 ******************************************************************************/
145function createGeoLS(lat, long, address, searchAddress) {
146	localStorage.setItem("lat", lat);
147	localStorage.setItem("long", long);
148	localStorage.setItem("address", address);
149	if ( searchAddress == undefined ){
150		localStorage.setItem("searchAddress", "");
151	} else {
152		localStorage.setItem("searchAddress", searchAddress);
153	}
154	setCookie("userGeoLatitude", lat, 365);
155	setCookie("userGeoLongitude", long, 365);
156	setCookie("userGeoZip", searchAddress, 365);
157
158}
159
160
161/*******************************************************************************
162 * Returns an obj of what is stored in local storage.
163 * 
164 * @return geoObj, an object that contains the lat, long, and address if it is
165 *         in local storage.
166 ******************************************************************************/
167function getGeoLS() {
168	lat = localStorage.lat;
169	long = localStorage.long;
170	address = localStorage.address;
171	searchAddress = localStorage.searchAddress;
172	if (lat) {
173		var geoObj = {
174				lat: lat,
175				long: long,
176				address: address,
177				searchAddress: searchAddress
178		};
179		return geoObj;
180	} else {
181		return;
182	}
183}
184
185/*******************************************************************************
186 * Returns an obj of what is stored in local storage.
187 * 
188 * @return geoObj, an object that contains the lat, long, and address if it is
189 *         in local storage.
190 ******************************************************************************/
191function getStoredLat() {
192	return localStorage.lat;
193}
194
195/*******************************************************************************
196 * Returns an obj of what is stored in local storage.
197 * 
198 * @return geoObj, an object that contains the lat, long, and address if it is
199 *         in local storage.
200 ******************************************************************************/
201function getStoredLong() {
202	return localStorage.long;
203}
204
205/*******************************************************************************
206 * Returns an obj of what is stored in local storage.
207 * 
208 * @return geoObj, an object that contains the lat, long, and address if it is
209 *         in local storage.
210 ******************************************************************************/
211function getStoredSearchAddress() {
212	return localStorage.searchAddress;
213}
214'use strict';
215
216jQuery(".buttonPlaceHolder").remove();
217
218jQuery(".country-select button").each(function () {
219    if (jQuery(this).attr("data-country") == countrySelected) {
220        jQuery(this).removeClass("country-not-active").addClass("country-active");
221        jQuery(this).find(".fas").addClass("fa-angle-down");
222        var toAfter = jQuery(this).siblings();
223        jQuery(this).after(toAfter);
224    }
225});
226
227jQuery(".countryButton").each(function () {
228
229
230    jQuery(this).on("click", function () {
231
232        if (jQuery(this).hasClass("country-active") && (jQuery(this).hasClass("past"))) {
233            //This keeps the selected country the same.
234            jQuery(this).siblings().addClass("country-not-active").css({
235                "margin-top": "1rem"
236            });
237            jQuery(this).removeClass("past").css({
238                "margin-bottom": "1rem"
239            });
240            jQuery(this).find(".fas").addClass("fa-angle-down");
241            jQuery(this).siblings().find(".fas").removeClass("fa-angle-down");
242            countrySelected = jQuery(this).attr("data-country");
243            setCookie("country", countrySelected, "365", protocol);
244             return;
245        }
246        if (jQuery(this).hasClass("country-active") && (!jQuery(this).hasClass("past"))) {
247            //this just opens the choices but sets nothing.
248            jQuery(this).siblings().removeClass("country-not-active").css({
249                "margin-top": "0px",
250                "margin-bottom": "5px"
251            });
252            jQuery(this).addClass("past").css({
253                "margin-bottom": "0px",
254                "margin-top": "0px"
255            });
256            return;
257        } else {
258            //This changes the selected country.
259            // setTimeout(function () {
260                jQuery(this).siblings().addClass("country-not-active").css({
261                    "margin-top": "1rem",
262                    "margin-bottom": "1rem"
263                }).removeClass("past").removeClass("country-active").css({
264                    "margin-bottom": "1rem",
265                    "margin-top": "1rem"
266                });
267            // }, 500);
268                var toAfter = jQuery(this).siblings();
269                jQuery(this).after(toAfter);
270                jQuery(this).find(".fas").addClass("fa-angle-down");
271                jQuery(this).siblings().find(".fas").removeClass("fa-angle-down");
272                jQuery(this).addClass("country-active");
273                countrySelected = jQuery(this).attr("data-country");
274                checkCanadaLock();
275
276
277                if (canadianPricing === "true") {
278                    setCookie("currency", countrySelected, "365", protocol);
279                    dealerSearchSetup();
280                    if (countrySelected == "CAD") {
281                        jQuery(".metric").show();
282                        jQuery(".standard").hide();
283                        jQuery(".price-currency").text("CAD");
284                        jQuery(".active-standard").removeClass("active").addClass("inactive");
285                        jQuery(".active-metric").removeClass("inactive").addClass("active");
286
287                        if (url.indexOf(".ca") <= -1) {
288                            window.location.href = url.replace(".html", ".ca.html");
289                        }
290
291                    } else {
292                        jQuery(".metric").hide();
293                        jQuery(".standard").show();
294                        jQuery(".price-currency").text("USD");
295                        jQuery(".active-metric").removeClass("active").addClass("inactive");
296                        jQuery(".active-standard").removeClass("inactive").addClass("active");
297
298                        if (url.indexOf(".ca") > -1) {
299                            window.location.href = url.replace(".ca.html", ".html");
300                        }
301
302                    }
303                } else {
304                    setCookie("currency", "USD", "365", protocol);
305                }
306           
307        }
308
309    });
310});
311"use strict";
312
313var input;
314var autocomplete; //set up for google auto complete.
315
316// map vars
317var map; //global access to the map
318var markers = []; //the markers on the map
319var idleListen;
320
321var numDealers; //this is used to define the max dealers without corrupting the maxResults.
322var maxResult = jQuery("#jsVars").attr("data-mMin"); //The default maximum number of results. Possibly set by the site settings.
323//	maxResult = jQuery(".searchMax").attr("data-searchMax"); //The default maximum number of results. Possibly set by the site settings.
324
325// result vars
326var carriedSegments; //global of the carried segments in case this needs to be accessed by another function.
327var dealerLocation; //the text displayed on the search results.
328
329function clearMarkers() {
330	for (var i = 0; i < markers.length; i++) {
331		markers[i].setMap(null);
332	}
333
334}
335
336// google API runs this automatically
337function initMap() {
338	var lat = getStoredLat();
339	var lng = getStoredLong();
340    //getLongLat();
341    window.infowindow = new google.maps.InfoWindow();
342	var showDealers = false;
343	var options = {
344			types: ['(regions)'],
345			componentRestrictions: {
346				country: ["US","CA"]
347			}
348	};
349	if(document.getElementById('load-more'))
350        document.getElementById('load-more').style.display="none";
351	if ( document.getElementById("map-location") ){
352        if(getStoredSearchAddress() != "undefined"){
353			$(".input-field").val( getStoredSearchAddress() );
354        }
355        else if(getCookie("userGeoZip"))
356            $(".input-field").val(getCookie("userGeoZip"));
357
358		// it the uses doesn't have their lat long set then we aren't going to show the map
359		if ( !lat ){
360			lat = Number(37.1796151);
361			lng = Number(-93.2966805);
362		} else {
363			showDealers = true;
364		}
365
366		//lat and long are coming from geolocation.js as global variables but will be updated with a search.
367		if (document.getElementById("map-location")) {
368
369			map = new google.maps.Map(document.getElementById("map-location"), {
370				center: {
371					lat: Number(lat),
372					lng: Number(lng)
373				},
374				zoom: 4
375			});
376
377		}
378
379		if ( showDealers ){
380			var ll = lat + "," + lng;
381            if(document.getElementById('radius-input'))
382            	fetchDealerListByRadius(ll);
383            else
384				fetchDealerList(ll);
385		} else {
386//			fetchAllDealer();
387		}
388
389	}
390
391	// places = new google.maps.places.PlacesService(map);
392	// From GOOGLE on saving money: IMPORTANT: To avoid paying for data that you don't need, be sure to use Autocomplete.setFields() to specify only the place data that you will use.
393	// https://developers.google.com/maps/documentation/javascript/places-autocomplete
394	if ( document.getElementById('search-term') ){
395		document.getElementById("search-term").focus();
396		input = document.getElementById('search-term');
397		autocomplete = new google.maps.places.Autocomplete(input, options);
398		autocomplete.setFields(['place_id','geometry.location']);
399		autocomplete.addListener('place_changed', onPlaceChanged);
400	}
401
402    if($('#dealer-select-modal-container').is(':visible')){
403         if(document.getElementById('modal-radius')){
404                 if(getStoredSearchAddress() != "undefined"){
405                    $("#search-pf").val( getStoredSearchAddress() );
406                }
407                else if(getCookie("userGeoZip"))
408                    $("#search-pf").val(getCookie("userGeoZip"));
409                 var latlng = lat + "," + lng;
410                fetchPFDealerListByRadius(latlng);
411          }
412    }
413    else{
414		jQuery(document).on('open.zf.reveal', '#dealer-select-modal-container[data-reveal]', function () {
415            if(document.getElementById('modal-radius')){
416                 if(getStoredSearchAddress() != "undefined"){
417                    $("#search-pf").val( getStoredSearchAddress() );
418                }
419                else if(getCookie("userGeoZip"))
420                    $("#search-pf").val(getCookie("userGeoZip"));
421                 var lat = getStoredLat();
422				 var lng = getStoredLong();
423                 var latlng = lat + "," + lng;
424                fetchPFDealerListByRadius(latlng);
425            }
426
427			input = document.getElementById('search-pf');
428			autocomplete = new google.maps.places.Autocomplete(input, options);
429			autocomplete.setFields(['place_id','geometry.location']);
430			autocomplete.addListener('place_changed', onPFPlaceSelect);
431
432		});
433	}
434
435}
436
437
438//function runs when the place is changed in the search.
439function onPFPlaceSelect() {
440
441	var place = autocomplete.getPlace();
442	var placeId = place.place_id;
443	if (!placeId) {
444		selectFirstPFResult();
445	} else {
446		
447		var latitude = place.geometry.location.lat();
448		var longitude = place.geometry.location.lng(); 
449		var newll = latitude + "," + longitude;
450		localStorage.setItem("lat", latitude);
451		localStorage.setItem("long", longitude);
452		localStorage.setItem("address", $("#search-pf").val());
453		localStorage.setItem("searchAddress", $("#search-pf").val());
454		// get dealers by latitude and longitude
455		jQuery(".results").html("");
456        if(document.getElementById('modal-radius'))
457            fetchPFDealerListByRadius(newll);
458        else    
459			fetchPFDealerList(newll);
460	}
461}
462
463//function runs when the place is changed in the search.
464function onPlaceChanged() {
465	var place = autocomplete.getPlace();
466	var placeId = place.place_id;
467
468	if (!placeId) {
469		selectFirstResult();
470	} else {
471		var latitude = place.geometry.location.lat();
472		var longitude = place.geometry.location.lng(); 
473		var newll = latitude + "," + longitude;
474		localStorage.setItem("lat", latitude);
475		localStorage.setItem("long", longitude);
476		localStorage.setItem("address", $("#search-term").val());
477		localStorage.setItem("searchAddress", $("#search-term").val());
478		// get dealers by latitude and longitude
479		jQuery(".results").html("");
480        if(document.getElementById('radius-input')){
481            $(".input-field").val($("#search-term").val());
482            fetchDealerListByRadius(newll);
483        }
484        else    
485			fetchDealerList(newll);
486	}
487}
488
489//hit GO and it will take you to the first result in the list.
490jQuery(".dealerSearchButton").on("touchstart click", function (e) {
491    e.preventDefault();
492	var selectFirstOption = jQuery(".pac-item").first().text();
493	jQuery(input).val(selectFirstOption);
494	jQuery(input).focus();
495	google.maps.event.trigger(input, 'keydown', {
496		keyCode: 13
497	});
498});
499
500
501//hit enter and it will take you to the first result in the list.
502function selectFirstResult() {
503
504	var firstResult = jQuery(".pac-container .pac-item:first").text();
505	var stringMatched = jQuery(".pac-container .pac-item:first").find(".pac-item-query").text();
506
507    // NEW JS FIX FOR ZIP STRING FORMAT.
508	var stringMatchedParent = document.querySelectorAll(".pac-container .pac-item")[0];
509	var stringMatchedValue = stringMatchedParent.querySelectorAll(".pac-item-query")[0].innerText;
510	var isValidZip = /^((\d{5}-\d{4})|(\d{5})|([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]\s?\d[A-Za-z]\d)|([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]))$/i.test(stringMatchedValue);
511
512	if (isValidZip) {
513		var pacContainer = document.querySelectorAll(".pac-container")[0];
514		var pacItem = pacContainer.querySelectorAll(".pac-item")[0];
515		var pacMatched = pacItem.querySelectorAll(".pac-item-query")[0].innerText;
516		var pacUnmatchedString = pacItem.querySelectorAll("span")[3].innerHTML;
517
518		var pacArr = pacUnmatchedString.split(" ");
519		pacArr.splice(-1, 0, pacMatched);
520		var pacJoined = pacArr.join(" ");
521		console.log(pacJoined);
522		firstResult = pacJoined;
523	} else {
524		firstResult = firstResult.replace(stringMatched, stringMatched + " ");
525	}
526    // \NEW JS FIX FOR ZIP STRING FORMAT.
527
528	var geocoder = new google.maps.Geocoder();
529	geocoder.geocode({
530		"address": firstResult
531	}, function (results, status) {
532		if (status == google.maps.GeocoderStatus.OK) {
533			var latitude = results[0].geometry.location.lat();
534			var longitude = results[0].geometry.location.lng();
535			var ll = latitude + "," + longitude;
536			localStorage.setItem("lat", latitude);
537			localStorage.setItem("long", longitude);
538			localStorage.setItem("address", $("#search-term").val());
539			localStorage.setItem("searchAddress", $("#search-term").val());
540
541			//firstResult = firstResult.replace(stringMatched, stringMatched + " ");
542
543            jQuery(input).val(firstResult);
544			jQuery(".results").html("");
545            if(document.getElementById('radius-input')){
546                $(".input-field").val(firstResult);
547                localStorage.setItem("searchAddress",firstResult);
548           		fetchDealerListByRadius(ll);
549            }
550        	else    
551				fetchDealerList(ll);
552		}
553	});
554}
555
556//hit enter and it will take you to the first result in the list.
557function selectFirstPFResult() {
558
559	var firstResult = jQuery(".pac-container .pac-item:first").text();
560	var stringMatched = jQuery(".pac-container .pac-item:first").find(".pac-item-query").text();
561
562	var geocoder = new google.maps.Geocoder();
563	geocoder.geocode({
564		"address": firstResult
565	}, function (results, status) {
566		if (status == google.maps.GeocoderStatus.OK) {
567			var latitude = results[0].geometry.location.lat();
568			var longitude = results[0].geometry.location.lng();
569			var ll = latitude + "," + longitude;
570			localStorage.setItem("lat", latitude);
571			localStorage.setItem("long", longitude);
572			localStorage.setItem("address", $("#search-pf").val());
573			localStorage.setItem("searchAddress", $("#search-pf").val());
574			firstResult = firstResult.replace(stringMatched, stringMatched + " ");
575			jQuery(input).val(firstResult);
576			jQuery(".results").html("");
577			if(document.getElementById('modal-radius')){
578				localStorage.setItem("searchAddress",firstResult);
579            	fetchPFDealerListByRadius(ll);
580            }
581       		else    
582				fetchPFDealerList(ll);
583		}
584	});
585}
586
587function pinSymbol(fcolor) {
588	return {
589		path: 'M 9.94186047,0 C4.46016715,0 0,4.70252703 0,10.4850101 C0,16.047308 9.0383939,30.5467663 9.42364099,31.1601394 C9.53797238,31.3436271 9.7330814,31.4550303 9.94186047,31.4550303 C10.1506395,31.4550303 10.3445058,31.3436271 10.4600799,31.1601394 C10.845327,30.5467663 19.8837209,16.047308 19.8837209,10.4850101 C19.8837209,4.70252703 15.4235538,0 9.94186047,0 z',
590		fillColor: fcolor,
591		fillOpacity: 1,
592		strokeColor: '#000000',
593		strokeOpacity: 0.125,
594		strokeWeight: 2,
595		scale: 1,
596		labelOrigin: new google.maps.Point(10, 10),
597		anchor: new google.maps.Point(10, 32),
598		origin: (0, 0)
599	};
600
601}
602
603
604// function to set users location marker/pin
605function setUserPin(lat , lng ) {
606
607	var latLng;
608
609	if ( lat === undefined ){
610		latLng = {lat: Number("37.37"), lng: Number("-93.09")};
611	} else {
612		latLng = {lat: Number(lat), lng: Number(lng)};
613	}
614
615
616	var pin = new google.maps.Marker({
617		position: latLng
618		, map: map
619		, icon: pinSymbol('#4489f1')
620		, zIndex: 0
621	});
622
623	return pin;
624}
625
626function resetMarkers(){
627	for (var i = 0; i < markers.length; i++) {
628		markers[i].setIcon(pinSymbol('#FFCC04'));
629	}
630}
631
632
633// function to show all dealer pins with out listing under map
634function showAllDealers(){
635
636	clearMarkers();
637	$("#search-term").val("");
638	var latlng = "37.1796151,-93.2966805";
639	jQuery(".results").html("");
640	fetchAllDealer(latlng, undefined, 600);
641	jQuery("#showAllDealers").hide();
642
643}
644
645
646//method to get all the boat centers on page load
647function fetchAllDealer() {
648
649	var latlng = "37.1796151,-93.2966805";
650	var point = latlng.split(",");
651	var brand = jQuery("#jsVars").attr("data-brand");
652
653	$.ajax({
654		url: "/bin/boating-sites/findadealer?countryCode=us,ca&maxResult=600&location=" + latlng + "&brand=" + brand,
655		data: {
656			format: "json"
657		},
658		type: "GET",
659		error: function () {
660			console.log("fetchAllDealer error");
661		},
662		success: function (result) {
663			var obj = JSON.parse(result.result);
664			var dealerOBJ = obj.DEALERS;
665			var dealers = Object.keys(dealerOBJ).map(function (k) {
666				return dealerOBJ[k];
667			});
668			numDealers = dealers.length - 1;
669			var pin;
670			clearMarkers();
671			markers = [];
672			if (map) {
673				map.setCenter({
674					lat: Number(point[0]),
675					lng: Number(point[1])
676				});
677			}
678			var bounds = new google.maps.LatLngBounds();
679
680
681			for (var i = 0; i <= numDealers; i++) {
682				if ( dealers[i].LAT && dealers[i].LONG){
683					var storeHours;
684					var salesPhone;
685					var serviceHours;
686					var ll = {
687							lat: dealers[i].LAT,
688							lng: dealers[i].LONG
689					}
690	
691					//this is the marker set up code.
692					var dealer_i = new google.maps.LatLng(ll);
693					var pin = new google.maps.Marker({
694						position: dealer_i
695						, map: map
696						, zIndex: i + 10
697						, optimized: false
698						, icon: pinSymbol('#FFCC04')
699						, url: "#dealer-" + (i + 1)
700						, title: dealers[i].NAME
701					});
702					bounds.extend(dealer_i);
703					//this adds a listener to the markers to allow you to click locate lower on the page.
704					(function (i) {
705						google.maps.event.addListener(
706							pin,
707							'click',
708							(function (marker) {
709								return function () {
710									resetMarkers();
711									marker.setIcon(pinSymbol('#EE3037'));
712									$('#dealer-search-results').find('div.result-entry').each(function () {
713										$(this).addClass('hide');
714									});
715									$(this.url).removeClass("hide");
716									var targetPin = $(this.url);
717									var pos = targetPin.offset().top;
718									$('html, body').animate({
719										scrollTop: pos
720									}, 1000);
721								};
722							})(pin));
723					})(i);
724					markers.push(pin)
725	
726					//sales phone number
727					if (dealers[i].SECONDPHONE !== "") {
728						salesPhone = '<h6>Call</h6>' +
729						'<span class="hide-for-large"><a href="tel:+' + dealers[i].SECONDPHONE + '">' + dealers[i].SECONDPHONE + '</a></span>' +
730						'<span class="show-for-large">' + dealers[i].SECONDPHONE + '</span>';
731					} else {
732						salesPhone = '<h6>Call</h6>' +
733						'<span class="hide-for-large"><a href="tel:+' + dealers[i].PHONE + '">' + dealers[i].PHONE + '</a></span>' +
734						'<span class="show-for-large">' + dealers[i].PHONE + '</span>';						
735					}
736					//store hours
737					if (!isEmpty(dealers[i].STOREHOURS[1])) {
738						storeHours = '<h6>Store Hours</h6>';
739						if (!isEmpty(dealers[i].STOREHOURS[1][1][0])) {
740							storeHours += dealers[i].STOREHOURS[1][1][0].DAY + ': ' + dealers[i].STOREHOURS[1][1][0].TIME + '<br/>';
741						}
742						if (!isEmpty(dealers[i].STOREHOURS[1][1][1])) {
743							storeHours += dealers[i].STOREHOURS[1][1][1].DAY + ': ' + dealers[i].STOREHOURS[1][1][1].TIME + '<br/><br/>';
744						}
745					} else {
746						storeHours = '';
747					}
748					//service hours
749					if (!isEmpty(dealers[i].STOREHOURS[2])) {						
750						serviceHours = '<h6>Service Hours</h6>' +
751						dealers[i].STOREHOURS[2][1][0].DAY + ': ' + dealers[i].STOREHOURS[2][1][0].TIME + '<br/>';
752						if (!isEmpty(dealers[i].STOREHOURS[2][1][1])) {
753							serviceHours += dealers[i].STOREHOURS[2][1][1].DAY + ': ' + dealers[i].STOREHOURS[2][1][1].TIME + '<br/>';
754						}
755						if (!isEmpty(dealers[i].STOREHOURS[2][1][2])) {
756							serviceHours += dealers[i].STOREHOURS[2][1][2].DAY + ': ' + dealers[i].STOREHOURS[2][1][2].TIME + '<br/><br/>';
757						}
758					} else {
759						serviceHours = '';
760					}
761					var googleQ = dealers[i].NAME + "+" + dealers[i].ADDRESS + "+" + dealers[i].CITY + "+" + dealers[i].STATE + "+" + dealers[i].ZIPCODE;
762					var googleDirection = "https://www.google.com/maps?q="+ googleQ.replace(/ /g, "+");
763	
764					dealerLocation = 
765						'<div id="dealer-' + (i + 1) + '" class="result-entry hide" data-dealerCountry ="' + dealers[i].COUNTRY_CODE + '" data-dealer-id="' + dealers[i].DEALERID + '" >' +
766						'	<div class="grid-x grid-margin-x">' +
767						'		<div class="cell small-2 large-1">' +
768						'			<span class="fa-stack">' +
769						'	        	<i class="map-marker fas fa-map-marker fa-stack-2x"></i>' +
770						'   	    	<i class="map-marker-counter fa-stack-1x"></i>' +
771						'      		</span>' +
772						'	    </div>' +
773						'   	<div class="cell small-10 large-11">' +
774						'      		<div class="grid-x grid-margin-x">' +
775						'        		<div class="cell small-12 medium-12 large-12">' +					
776						'					<div class="dealer-name tiny-bottom">' + dealers[i].NAME + '</div>' +					
777						'        		</div>' +					
778						'        		<div class="cell small-12 medium-12 large-4 medium-bottom">' +
779						'          			<div class="links small-bottom links">' +
780						'		            	<div><a href="'+googleDirection+'" target="_blank">Get Directions</a></div>';
781if (dealers[i].WEB != ''){
782		dealerLocation += '       		    	<div><a href="' + dealers[i].WEB + '" target="_blank">Visit Website</a></div>';
783}
784		dealerLocation += '       			</div>' +
785						'		        	<div data-dealer-id="' + dealers[i].DEALERID + '" data-dealerCountry ="' + dealers[i].COUNTRY_CODE + '"><a class="button primary" style="text-decoration:none;">Set As My Dealer</a></div>' +
786						'		       	</div>' +
787						'				<div class="cell small-12 medium-6 large-4">' +
788						'					<div class="other-info">' +
789						'						<h6>Address</h6>' +
790						' 						<div class="address">' + dealers[i].ADDRESS + '</div>' +
791						'						<div class="city-state-zip">' + dealers[i].CITY + ', ' + dealers[i].STATE + ' ' + dealers[i].ZIPCODE + '</div>' +
792						'		            	<div><a href="'+googleDirection+'" target="_blank" class="links">Get Directions</a></div>' +
793						'<br/>' +
794						salesPhone + 
795						' 					</div>' +
796						' 				</div>' +
797						' 				<div class="cell small-12 medium-6 large-4">' +
798						'					<div class="other-info">' +
799						storeHours +
800						'  ' +
801						serviceHours +
802						' 					</div>' +
803						'				</div>' +
804						'			</div>' +
805						'		</div>' +
806						'	</div>' +
807						'</div>';
808	
809					jQuery(".results").append(dealerLocation);
810					$('#bCenter-dealer-search-results').find('div.result-entry').each(function () {
811						$(this).addClass('hide');
812					});
813					
814					checkMyStoreInDealerSearchResults();
815				}
816
817			}
818
819			jQuery(".dealer-search-map").show();
820			map.fitBounds(bounds);
821		}
822	});
823}
824
825
826
827
828function fetchPFDealerList( latlng ) {
829	var brand = jQuery("#jsVars").attr("data-brand");
830	var max = jQuery("#jsVars").attr("data-searchmax");
831	if ( latlng != undefined){
832		jQuery("#showAllDealers").show();
833		
834		// call to servlet gets the dealers.
835		$.ajax({
836			url: "/bin/boating-sites/findadealer?countryCode=us,ca&location=" + latlng + "&brand=" + brand + "&maxResult=" + max,
837			data: {
838				format: "json"
839			},
840			type: "GET",
841			error: function () {
842				console.log("fetchPFDealerList error");
843			},
844			success: function (result) {
845				var obj = JSON.parse(result.result);
846				var dealerOBJ = obj.DEALERS;
847				var dealers = Object.keys(dealerOBJ).map(function (k) {
848					return dealerOBJ[k];
849				});
850				numDealers = dealers.length - 1;
851				
852				for (var i = 0; i <= numDealers; i++) {
853					if ( dealers[i].LAT && dealers[i].LONG){
854
855						var phone;
856						var rndDistance = Math.floor(dealers[i].DISTANCE);
857						var ll = {
858								lat: dealers[i].LAT,
859								lng: dealers[i].LONG
860						}
861						
862						//sales phone number
863						if (dealers[i].SECONDPHONE !== "") {
864							phone = dealers[i].SECONDPHONE;
865						} else {
866							phone = dealers[i].PHONE;				
867						}
868						dealerLocation = 
869								'<div class="cell medium-6 large-3">' +
870								'	<div class="result-entry">' +
871								'		<div class="dealer-result-name">' + dealers[i].NAME + '</div>' +
872								'		<div class="dealer-result-distance">' +
873								'			' + rndDistance + ' miles away' +
874								'		</div>' +
875								'		<div class="dealer-result-info">' +
876								'			<div class="dealer-result-address1">' + dealers[i].ADDRESS + '</div>' +
877								'			<div class="dealer-result-address2">' +
878								'			</div>' +
879								'			<div class="dealer-result-city-state-zip">' + dealers[i].CITY + ', ' + dealers[i].STATE + ' ' + dealers[i].ZIPCODE + '</div>' +
880								'			<div class="dealer-result-phone">' + phone + '</div>' +
881								'		</div>' +
882								'		<button class="button small dealerSelect" type="button" data-close data-dealerCountry ="' + dealers[i].COUNTRY_CODE + '" data-dealer-id="' + dealers[i].DEALERID + '">SELECT</button>' +
883								'	</div>' +
884								'</div>';
885						
886						jQuery(".results").append(dealerLocation);
887					}
888				}
889
890				jQuery(".results").fadeIn("800");
891				
892				jQuery(".dealerSelect").on("click", function(){
893					console.log("here" );
894					var dealerID = jQuery(this).attr("data-dealer-id");
895					var dealerCountry = jQuery(this).attr("data-dealerCountry");
896					console.log(dealerCountry)
897					var currencyCookie = getCookie("currency");
898					var boatID = jQuery(".boatID").attr("data-boatID");
899					setCookie("dc", dealerCountry,"365",protocol)
900					setCookie("dealer", dealerID, "365", protocol);
901					setAsMyStore(dealerID);
902					getSelectedDealer(dealerID, currencyCookie, boatID)
903				});
904
905			}
906		});
907	}
908}
909
910function fetchDealerList( latlng ) {
911	var boatInventoryPath = $(".dealer-search").attr("data-boatInventory");
912	var offRoadInventoryPath = $(".dealer-search").attr("data-offRoadInventory");
913	var brand = jQuery("#jsVars").attr("data-brand");
914	var max = jQuery("#jsVars").attr("data-searchmax");
915	if ( latlng != undefined){
916		jQuery("#showAllDealers").show();
917		// Call servlet by Ajax.
918		var point = latlng.split(",");
919		//call to servlet gets the dealers.
920		$.ajax({
921			url: "/bin/boating-sites/findadealer?countryCode=us,ca&location=" + latlng + "&brand=" + brand + "&maxResult=" + max,
922			data: {
923				format: "json"
924			},
925			type: "GET",
926			error: function () {
927				console.log("fetchDealerList error");
928			},
929			success: function (result) {
930                console.log(result);
931				var obj = JSON.parse(result.result);
932				var dealerOBJ = obj.DEALERS;
933				var dealers = Object.keys(dealerOBJ).map(function (k) {
934					return dealerOBJ[k];
935				});
936				numDealers = dealers.length - 1;
937				var pin;
938				clearMarkers();
939				markers = [];
940				markers.push(
941						setUserPin( Number(point[0]), Number(point[1]) )
942					);
943				if (map) {
944					map.setCenter({
945						lat: Number(point[0]),
946						lng: Number(point[1])
947					});
948				}
949					var bounds = new google.maps.LatLngBounds();
950
951
952				for (var i = 0; i <= numDealers; i++) {
953					if ( dealers[i].LAT && dealers[i].LONG){
954
955						var storeHours;
956						var salesPhone;
957						var serviceHours;
958						var ll = {
959								lat: dealers[i].LAT,
960								lng: dealers[i].LONG
961						}
962	
963						//this is the marker set up code.
964						var dealer_i = new google.maps.LatLng(ll);
965						var pin = new google.maps.Marker({
966							position: dealer_i
967							, map: map
968							, zIndex: i + 10
969							, optimized: false
970							, icon: pinSymbol('#FFCC04')
971							, url: "#dealer-" + (i + 1)
972							, title: dealers[i].NAME
973							, label: {
974								text: (i + 1).toString()
975								, color: "#fff"
976								, fontSize: "14px"
977								, fontWeight: "bold"
978								, fontFamily: "oswaldbold"
979							}
980						});
981						markers.push(pin)
982						bounds.extend(dealer_i);
983	
984						//this adds a listener to the markers to allow you to click locate lower on the page.
985						(function (i) {
986							google.maps.event.addListener(markers[i+1], 'click', function () {
987								$('#bCenter-dealer-search-results').find('div.result-entry').each(function () {
988									$(this).addClass('hide');
989								});
990								$(this.url).removeClass("hide");
991								var targetPin = $(this.url);
992								var pos = targetPin.offset().top;
993								$('html, body').animate({
994									scrollTop: pos
995								}, 1000);
996							});
997						})(i);
998						//sales phone number
999						if (dealers[i].SECONDPHONE !== "") {
1000							salesPhone = '<h6>Call</h6>' +
1001							'<span class="hide-for-large"><a href="tel:+' + dealers[i].SECONDPHONE + '">' + dealers[i].SECONDPHONE + '</a></span>' +
1002							'<span class="show-for-large">' + dealers[i].SECONDPHONE + '</span>';
1003						} else {
1004							salesPhone = '<h6>Call</h6>' +
1005							'<span class="hide-for-large"><a href="tel:+' + dealers[i].PHONE + '">' + dealers[i].PHONE + '</a></span>' +
1006							'<span class="show-for-large">' + dealers[i].PHONE + '</span>';						
1007						}
1008						//store hours
1009						if (!isEmpty(dealers[i].STOREHOURS[1])) {
1010							storeHours = '<h6>Store Hours</h6>';
1011							if (!isEmpty(dealers[i].STOREHOURS[1][1][0])) {
1012								storeHours += dealers[i].STOREHOURS[1][1][0].DAY + ': ' + dealers[i].STOREHOURS[1][1][0].TIME + '<br/>';
1013							}
1014							if (!isEmpty(dealers[i].STOREHOURS[1][1][1])) {
1015								storeHours += dealers[i].STOREHOURS[1][1][1].DAY + ': ' + dealers[i].STOREHOURS[1][1][1].TIME + '<br/><br/>';
1016							}
1017						} else {
1018							storeHours = '';
1019						}
1020						//service hours
1021						if (!isEmpty(dealers[i].STOREHOURS[2])) {
1022							serviceHours = '<h6>Service Hours</h6>' +
1023							dealers[i].STOREHOURS[2][1][0].DAY + ': ' + dealers[i].STOREHOURS[2][1][0].TIME + '<br/>';
1024							if (!isEmpty(dealers[i].STOREHOURS[2][1][1])) {
1025								serviceHours += dealers[i].STOREHOURS[2][1][1].DAY + ': ' + dealers[i].STOREHOURS[2][1][1].TIME + '<br/>';
1026							}
1027	
1028							if (!isEmpty(dealers[i].STOREHOURS[2][1][2])) {
1029								serviceHours += dealers[i].STOREHOURS[2][1][2].DAY + ': ' + dealers[i].STOREHOURS[2][1][2].TIME + '<br/><br/>';
1030							}
1031						} else {
1032							serviceHours = '';
1033						}
1034						var googleQ = dealers[i].NAME + "+" + dealers[i].ADDRESS + "+" + dealers[i].CITY + "+" + dealers[i].STATE + "+" + dealers[i].ZIPCODE;
1035						var googleDirection = "https://www.google.com/maps?q="+ googleQ.replace(/ /g, "+");
1036						dealerLocation = 
1037						'<div id="dealer-' + (i + 1) + '" class="result-entry" data-dealer-id="' + dealers[i].DEALERID + '" data-dealerCountry ="' + dealers[i].COUNTRY_CODE + '">' +
1038						'	<div class="grid-x grid-margin-x">' +
1039						'		<div class="cell small-2 large-1">' +
1040						'			<span class="fa-stack">' +
1041						'	        	<i class="map-marker fas fa-map-marker fa-stack-2x"></i>' +
1042						'   	    	<i class="map-marker-counter fa-stack-1x"></i>' +
1043						'      		</span>' +
1044						'	    </div>' +
1045						'   	<div class="cell small-10 large-11">' +
1046						'      		<div class="grid-x grid-margin-x">' +
1047						'        		<div class="cell small-12 medium-12 large-12">' +					
1048						'					<div class="dealer-name tiny-bottom">' + dealers[i].NAME + '</div>' +					
1049						'        		</div>' +					
1050						'        		<div class="cell small-12 medium-12 large-4 medium-bottom">' +
1051	                    '          			<div class="links small-bottom links">' +
1052	                    '		            	<div><a href="'+googleDirection+'" target="_blank">Get Directions</a></div>';
1053if (dealers[i].WEB != ''){
1054		dealerLocation += '       		    	<div><a href="' + dealers[i].WEB + '" target="_blank">Visit Website</a></div>';
1055}
1056		dealerLocation += '       			</div>' +
1057	                    '		        	<div data-dealer-id="' + dealers[i].DEALERID + '" data-dealerCountry ="' + dealers[i].COUNTRY_CODE + '"><a class="button primary" style="text-decoration:none;">Set As My Dealer</a></div>' +
1058	                    '		       	</div>' +
1059						'				<div class="cell small-12 medium-6 large-4">' +
1060						'					<div class="other-info">' +
1061						'						<h6>Address</h6>' +
1062						' 						<div class="address">' + dealers[i].ADDRESS + '</div>' +
1063						'						<div class="city-state-zip">' + dealers[i].CITY + ', ' + dealers[i].STATE + ' ' + dealers[i].ZIPCODE + '</div>' +
1064						'		            	<div><a href="'+googleDirection+'" target="_blank" class="links">Get Directions</a></div>' +
1065												'<br/>' +
1066												salesPhone + 
1067						' 					</div>' +
1068						' 				</div>' +
1069						' 				<div class="cell small-12 medium-6 large-4">' +
1070						'					<div class="other-info">' +
1071												storeHours +
1072												'  ' +
1073												serviceHours +
1074						' 					</div>' +
1075						'				</div>' +
1076						'			</div>' +
1077						'		</div>' +
1078						'	</div>' +
1079						'</div>';
1080	
1081						jQuery(".results").append(dealerLocation);
1082						$('#bCenter-dealer-search-results').find('div.result-entry').each(function () {
1083							$(this).addClass('hide');
1084						});
1085						checkMyStoreInDealerSearchResults();	
1086					}
1087				}
1088	
1089				jQuery(".dealer-search-map").show();
1090				jQuery(".results").fadeIn("800");
1091				if ( document.getElementById("map-location") ){
1092					map.fitBounds(bounds);
1093				}
1094			}
1095		});
1096	}	
1097
1098}
1099
1100function checkMyStoreInDealerSearchResults () {
1101	if($('#dealer-search-results').length){	
1102
1103		var storeData = getMyStore();
1104		if (storeData && storeData.dealerId != "" ){							
1105			var dealerId = storeData.dealerId;
1106			$( "#dealer-search-results .result-entry" ).each(function( index ) {
1107				var nearbyStoreDealerId = $(this).attr("data-dealer-id");
1108				if (nearbyStoreDealerId != null && nearbyStoreDealerId == dealerId) {
1109					// update button to my store text
1110					$(this).find(".button").replaceWith('<a class="store-set inactive" style="text-decoration:none;"><i class="fas fa-heart fa-s icon-alert"></i> My Dealer</a>');
1111				} 
1112			});	
1113		}
1114		
1115		$("#dealer-search-results .button").unbind('click');
1116		$("#dealer-search-results .button").click({param1: "fromDealerSearchResults"}, dealerSearchResultsSetAsMyStoreClick);
1117	}
1118
1119}
1120
1121function dealerSearchResultsSetAsMyStoreClick(event) {
1122	var dealerId = $(event.target).parent().attr("data-dealer-id");
1123	var dealerCountry = $(event.target).parent().attr("data-dealerCountry");
1124    console.log(canadianPricing);
1125    setCookie("dc", dealerCountry,"365",protocol);
1126    if (dealerCountry == "CA" && canadianPricing == "true") {
1127    			setCookie("currency", "CAD", "365", protocol);
1128    }
1129	setAsMyStore(dealerId);
1130	//displayCanadianPricing();
1131	// Change heart to button
1132	$("#dealer-search-results .store-set").replaceWith('<a class="button primary" style="text-decoration:none;">Set As My Dealer</a>');
1133
1134	// Change clicked button to heart
1135	$(event.target).replaceWith('<a href="#" class="store-set inactive" style="text-decoration:none;"><i class="fas fa-heart fa-s icon-alert"></i> My Dealer</a>');
1136
1137
1138	$("#dealer-search-results .button").unbind('click');
1139	$("#dealer-search-results .button").click({param1: "fromDealerSearchResults"}, dealerSearchResultsSetAsMyStoreClick);
1140
1141}
1142
1143
1144function isEmpty(obj) {
1145	for (var key in obj) {
1146		if (obj.hasOwnProperty(key)){
1147			return false;
1148		}
1149	}
1150  return true;
1151}
1152
1153
1154//Global varables defined used by the functions
1155var infowindow;
1156var search;
1157var ifAutosugest;
1158var dealerList = [];
1159var dealerListModal = [];
1160var template = "";
1161var searchDefautltHtml = '<div class="new-search">'+
1162 					' <div class="grid-x align-middle">'+
1163                       ' <div class="cell">'+
1164                           ' <div class="new-search-text">'+
1165                              '  Perform Search Above'+
1166                           ' </div>'+
1167                       ' </div>'+
1168				 	'</div>'+
1169
1170                        '</div>';
1171var loadMoreContent = '<div class="load-more text-center">'+
1172            			'<a id="load-more" class="hollow button loadMore" onClick="loadMore();">Load More</a>'+
1173            		  '</div>';
1174var daysOfWeek = {
1175    "Mon": 2,
1176    "Tue": 3,
1177    "Wed": 4,
1178    "Thu": 5,
1179    "Fri": 6,
1180    "Sat": 7,
1181    "Sun": 1
1182};
1183
1184//Function called on page load to populate the auto-suggest for Dealer names
1185 $( function() {
1186	if(jQuery("#jsVars").attr("data-newSearch") == "true"  && (document.getElementById('radius-input') || document.getElementById('modal-radius'))){
1187        template = Handlebars.compile($('#template').html());
1188     	Handlebars.registerHelper('eq', function(value1, value2) {
1189            return value1 === value2;
1190        });
1191        Handlebars.registerHelper('or', function(value1, value2) {
1192            return value1 || value2;
1193        });
1194        Handlebars.registerHelper('not', function(value1, value2){
1195            if (value1 !== value2) {
1196                return true;
1197            }
1198        });
1199    }
1200    if(document.getElementById('radius-input') && jQuery("#jsVars").attr("data-searchByName") == "true"){ 
1201		var element = document.getElementById("dealer-search-term");
1202        var styles = window.getComputedStyle(element);
1203        var displayValue = styles.getPropertyValue("display");
1204        if(displayValue == "block"){
1205            $(".arrow-icon").css("display", "none");
1206        	$(".miles").css("display", "none");
1207            $(".use-location").css("display", "none");
1208            jQuery(".results-text").html("");
1209        }
1210        var lat = "";
1211        var lng = "";
1212        if(getStoredLat() != undefined)
1213        	lat = getStoredLat();
1214        if(getStoredLong() != undefined)
1215			lng = getStoredLong();
1216        var brand = jQuery("#jsVars").attr("data-brand");
1217        var maxDealerNames = jQuery("#jsVars").attr("data-maxDealerNames");
1218        var availableTags = [];
1219        $.ajax({
1220            url: "/bin/boating-sites/dealersList?countryCode=us,ca&maxRecords="+maxDealerNames+"&longitude="+lng+"&latitude="+lat + "&brandName=" + brand,
1221            data: {
1222                format: "json"
1223            },
1224            type: "GET",
1225            error: function () {
1226                console.log("fetchAllDealer error");
1227            },
1228            success: function (result) {
1229                var response = JSON.parse(JSON.stringify(result));
1230					var dealerOBJ = JSON.parse(response.result);
1231					var dealers = Object.keys(dealerOBJ).map(function (k) {
1232						return dealerOBJ[k];
1233					});
1234                numDealers = dealers.length - 1;
1235                for (var i = 0; i <= numDealers; i++) {
1236                    availableTags.push({label:dealers[i].dealerName, id:dealers[i].id});
1237                }
1238            }
1239        });
1240    
1241        $( "#dealer-search-term" ).autocomplete({
1242            source: availableTags,
1243            select: function( event, ui ) {
1244                       $(".input-field-dealer").val(ui.item.label);
1245                		jQuery("#dealer-search-term").attr("dealer-id",ui.item.id);
1246                        ifAutosugest = "true";
1247                       fetchDealerByDealerName();
1248                    }
1249        });
1250	 }
1251  });
1252
1253function onRadiusChange(){
1254	var lat = getStoredLat();
1255	var lng = getStoredLong();
1256    var ll = lat + "," + lng;
1257    fetchDealerListByRadius(ll);
1258}
1259
1260//Function used to clear the map markers and setting the default zoom
1261function clearMarkersV2() {
1262	for (var i = 0; i < markers.length; i++) {
1263		markers[i].setMap(null);
1264	}
1265    map = new google.maps.Map(document.getElementById("map-location"), {
1266				center: {
1267					lat: Number(37.1796151),
1268					lng: Number(-93.2966805)
1269				},
1270        		maxZoom: 10,
1271				zoom: 4
1272	});
1273}
1274
1275//Function called when set my current location is called
1276jQuery(".currentLocation").on("click", function (e) {
1277  	getLongLat();
1278    setTimeout(initMap,500);
1279    $("#searchByMenu").val("location");
1280    $(".input-field-dealer").css("display", "none");
1281        $(".input-field").css("display", "block");
1282        $(".miles").css("display", "block");
1283        $(".arrow-icon").css("display", "block");
1284});
1285
1286
1287//Function called on change of radius in the Change Dealer Modal
1288jQuery("#modal-radius").on("change", function (e) {
1289	var lat = getStoredLat();
1290	var lng = getStoredLong();
1291    var latlng = lat + "," + lng;
1292    fetchPFDealerListByRadius(latlng);
1293});
1294
1295
1296
1297//Function called on the keyup of Dealer name input field of Search Dealer
1298jQuery(".input-field-dealer").on("keyup", function (e) {
1299    if (e.key === 'Enter' || e.keyCode === 13) {
1300        if(ifAutosugest != "true"){
1301            jQuery("#dealer-search-term").attr("dealer-id","");
1302            $(this).autocomplete("close");
1303        	fetchDealerByDealerName();
1304        }
1305    }
1306});
1307
1308//Setting of variable on change of dealer name, this is used to autocomplete
1309jQuery(".input-field-dealer").on("change", function (e) {
1310	ifAutosugest = "";
1311    jQuery("#dealer-search-term").attr("dealer-id","");
1312    $(this).autocomplete("close");
1313});
1314
1315//Function called for dealer search by radius from Change Dealer Modal
1316function fetchPFDealerListByRadius(latlng){
1317    var brand = jQuery("#jsVars").attr("data-brand");
1318	var max = jQuery("#jsVars").attr("data-maxDealersOnModal");
1319    var radius = '';
1320    if(document.getElementById('modal-radius')){
1321        radius = document.getElementById('modal-radius').value;
1322    }
1323    if ( radius != '' && latlng != undefined ){
1324        dealerListModal = [];
1325       	jQuery(".results").html("");
1326        var storeData = getMyStore();
1327        var selectedDealerId = "";
1328        if (storeData && storeData.dealerId != "" ){
1329            selectedDealerId = storeData.dealerId;
1330        }
1331        var point = latlng.split(",");
1332		// call to servlet gets the dealers.
1333		$.ajax({
1334			url: "/bin/boating-sites/dealersList?longitude="+point[1]+"&latitude="+point[0]+"&radius="+radius+"&brandName="+brand+"&maxRecords="+max+"&countryCode=us,ca",
1335			data: {
1336				format: "json"
1337			},
1338			type: "GET",
1339			error: function () {
1340				console.log("fetchPFDealerList error");
1341			},
1342			success: function (result) {
1343				var response = JSON.parse(JSON.stringify(result));
1344					var dealerOBJ = JSON.parse(response.result);
1345					var dealers = Object.keys(dealerOBJ).map(function (k) {
1346						return dealerOBJ[k];
1347					});
1348				numDealers = dealers.length - 1;
1349
1350				for (var i = 0; i <= numDealers; i++) {
1351					var address = JSON.parse(JSON.stringify(dealers[i].address));
1352                    var addressInfo = {};
1353                    for (const [key, value] of Object.entries(address)) {
1354                        addressInfo[key] = value;
1355                    }
1356
1357                    var labels = JSON.parse(JSON.stringify(dealers[i].dealerLabels));
1358			   		var labelsMap = [];
1359			        for (var item of labels) {
1360                		labelsMap.push({name:item.name, cssClass:item.cssClass, iconCssClass:item.iconCssClass, infoText:item.infoText});
1361        			}
1362			        
1363                	if ( dealers[i].latitude && dealers[i].longitude){
1364
1365						dealerListModal.push({index:(i + 1),
1366                             dealerInfo:dealers[i],
1367                             labelsMap:labelsMap,
1368                             addressInfo:addressInfo,
1369                             selectedDealerId:selectedDealerId                
1370                            });
1371
1372					}
1373				}
1374                $('#dealer-search-results').html(template({ dealerListModal }));
1375
1376				jQuery(".results").fadeIn("800");
1377				getSelectedDealer(selectedDealerId, getCookie("currency"), jQuery(".boatID").attr("data-boatID"));
1378				//initialiseTooltip();
1379				jQuery(".dealerSelect").on("click", function(){
1380					var dealerID = jQuery(this).attr("data-dealer-id");
1381					var dealerCountry = jQuery(this).attr("data-dealerCountry");
1382					var currencyCookie = getCookie("currency");
1383					var boatID = jQuery(".boatID").attr("data-boatID");
1384					setCookie("dc", dealerCountry,"365",protocol)
1385					setCookie("dealer", dealerID, "365", protocol);
1386					setAsMyStore(dealerID);
1387					getSelectedDealer(dealerID, currencyCookie, boatID)
1388				});
1389
1390			}
1391		});
1392	}
1393}
1394
1395
1396//Function called when dealer search by Location and radus
1397function fetchDealerListByRadius(latlng){
1398	var boatInventoryPath = $(".dealer-search").attr("data-boatInventory");
1399	var offRoadInventoryPath = $(".dealer-search").attr("data-offRoadInventory");
1400	var brand = jQuery("#jsVars").attr("data-brand");
1401	var max = jQuery("#jsVars").attr("data-maxDealerSearchRadius");
1402    if(document.getElementById('load-more'))
1403        document.getElementById('load-more').style.display="none";
1404    var radius = '';
1405    if(document.getElementById('radius-input')){
1406        radius = document.getElementById('radius-input').value;
1407        var element = document.getElementById("dealer-search-term");
1408        var styles = window.getComputedStyle(element);
1409        var displayValue = styles.getPropertyValue("display");
1410        if ( radius != '' && latlng != undefined && displayValue != "block"){
1411            var numbers = /^[0-9]+$/;
1412            if(radius.match(numbers)){
1413                jQuery("#showAllDealers").show();
1414                // Call servlet by Ajax.
1415                var point = latlng.split(",");
1416                //call to servlet gets the dealers.
1417                $.ajax({
1418                    url: "/bin/boating-sites/dealersList?longitude="+point[1]+"&latitude="+point[0]+"&radius="+radius+"&brandName="+brand+"&maxRecords="+max+"&countryCode=us,ca",
1419                    data: {
1420                        format: "json"
1421                    },
1422                    type: "GET",
1423                    error: function () {
1424                        console.log("fetchDealerList error");
1425                    },
1426                    success: function (result) {
1427                        jQuery(".results").html("");
1428                        var response = JSON.parse(JSON.stringify(result));
1429                        if(response.result != undefined){
1430                            var dealerOBJ = JSON.parse(response.result);
1431                            var dealers = Object.keys(dealerOBJ).map(function (k) {
1432                                return dealerOBJ[k];
1433                            });
1434        
1435                            dealerDisplay(dealers,point);
1436                        }
1437                        else
1438                            noDealerFound();
1439                    }
1440    
1441                });
1442            }
1443            else
1444                alert("Radius should be a numeric value");
1445        }
1446	}
1447}
1448
1449//Function called when dealer is searched by Dealer Name
1450function fetchDealerByDealerName(){
1451    var brand = jQuery("#jsVars").attr("data-brand");
1452    var max = jQuery("#jsVars").attr("data-maxDealerSearchRadius");
1453    var inputDealerName = document.getElementById('dealer-search-term').value;
1454    dealerList = [];
1455    var lat = getStoredLat();
1456    var lng = getStoredLong();
1457	var position = "";
1458
1459    if(lat != "" && lat != undefined && lng != "" && lng != undefined)
1460    	position = "&latitude=" +lat + "&longitude=" + lng;
1461
1462    var latlng = lat + "," + lng;
1463    var point = latlng.split(",");
1464    var dealerId = "";
1465    if(jQuery("#dealer-search-term").attr("dealer-id") != "")
1466		dealerId = "&dealerId="+jQuery("#dealer-search-term").attr("dealer-id");
1467    jQuery(".results").html(searchDefautltHtml);
1468    if(inputDealerName != ""){
1469			$.ajax({
1470			url: "/bin/boating-sites/dealersList?countryCode=us,ca&dealerName=" + inputDealerName + "&brandName=" + brand + "&maxResult=" + max + position + dealerId,
1471			data: {
1472				format: "json"
1473			},
1474			type: "GET",
1475			error: function () {
1476				console.log("fetchPFDealerList error");
1477			},
1478			success: function (result) {
1479
1480                 var response = JSON.parse(JSON.stringify(result));
1481                if(response.result != undefined){
1482					var dealerOBJ = JSON.parse(response.result);
1483					var dealers = Object.keys(dealerOBJ).map(function (k) {
1484						return dealerOBJ[k];
1485					});
1486                    if(dealers.length > 0){
1487						jQuery(".results").html("");
1488                    }
1489                	dealerDisplay(dealers,point);
1490                }
1491                else
1492                   noDealerFound();
1493            }
1494        });
1495
1496    }
1497}
1498
1499
1500//Function called when no dealer is found.
1501function noDealerFound(){
1502	clearMarkersV2();
1503    jQuery(".results-text").html('');
1504    var noDataContent = '<div class="no-results">'+
1505        '	<div class="grid-x align-middle">'+
1506            '		<div class="cell small-6">'+
1507                '			<div class="no-results-text">'+
1508                    '				No Dealers Found (0)'+
1509                        '			</div>'+
1510                            '		</div>'+
1511                                '		<div class="cell small-6 text-right">'+
1512                                    '			<a href="#" class="hollow button tiny" onClick="reset();">Reset Search</a>'+
1513                                        '		</div>'+
1514                                            '	</div>'+
1515                                                '</div>';
1516    jQuery(".results").html(noDataContent);
1517}
1518
1519//Function called on Search dealer page to set localstorage with the dealers output from the servlet call
1520function dealerDisplay(dealers,point){
1521 	if(dealers.length > 0)
1522 	{
1523        localStorage.setItem('dealersInfo',JSON.stringify(dealers));
1524        
1525        numDealers = dealers.length - 1;
1526        var pin;
1527        clearMarkersV2();
1528        markers = [];
1529        dealerList = [];
1530        markers.push(
1531            setUserPin( Number(point[0]), Number(point[1]) )
1532        );
1533        if (map) {
1534            map.setCenter({
1535                lat: Number(point[0]),
1536                lng: Number(point[1])
1537            });
1538        }
1539        
1540        document.getElementById('dealersCount').value = numDealers;
1541        var display = document.getElementById('displayCount').value;
1542        if(display >= numDealers)
1543            display = numDealers+1;
1544        jQuery(".results-text").html('Viewing 1 - '+display+' of '+ (parseInt(numDealers) + 1) +' results');
1545        loadContent(0,display);
1546    }
1547    else
1548        noDealerFound();
1549
1550}
1551
1552
1553//Function to display the results both search by location and search by dealer name
1554function loadContent(startPoint,display){
1555    var dealers = JSON.parse(localStorage.getItem('dealersInfo'));
1556    var bounds = new google.maps.LatLngBounds();
1557	for (var i = parseInt(startPoint); i < parseInt(display); i++) { 
1558        var address = JSON.parse(JSON.stringify(dealers[i].address));
1559        var addressInfo = {};
1560        for (const [key, value] of Object.entries(address)) {
1561            addressInfo[key] = value;
1562        }
1563   		
1564   		var labels = JSON.parse(JSON.stringify(dealers[i].dealerLabels));
1565   		var labelsMap = [];
1566        for (var item of labels) {
1567            labelsMap.push({name:item.name, cssClass:item.cssClass, iconCssClass:item.iconCssClass, infoText:item.infoText});
1568        }
1569
1570        var links = JSON.parse(JSON.stringify(dealers[i].links));
1571        var linksMap = [];
1572        for (var item of links) { 
1573            linksMap.push({name:item.name, url:item.url, iconCssClass:item.iconCssClass, doNewWindow:item.doNewWindow, doModalPopup:item.doModalPopup, modalContentDivId:item.modalContentDivId, id:dealers[i].id});
1574        }
1575         var contactLinks = JSON.parse(JSON.stringify(dealers[i].contactButton));
1576        var contactInfo = {};
1577        for (const [key, value] of Object.entries(contactLinks)) {
1578            contactInfo[key] = value;
1579        }
1580    
1581        var segments = JSON.parse(JSON.stringify(dealers[i].brandSegments));
1582        var segmentMap = [];
1583        for (var item of segments) {
1584                segmentMap.push({name:item.name});
1585        }
1586    
1587   		var hours = JSON.parse(JSON.stringify(dealers[i].operatingHourCategories));
1588        var hoursMap = [];
1589        for (var item of hours) {                
1590            hoursMap.push({name:item.name, times:item.operatingHours, upcomingTimeDisplay:item.upcomingTimeDisplay, status:item.openStatus});
1591        }
1592        
1593    	if ( dealers[i].latitude && dealers[i].longitude){
1594            var ll = {
1595                lat: dealers[i].latitude,
1596                lng: dealers[i].longitude
1597            }
1598            //this is the marker set up code.
1599            var dealer_i = new google.maps.LatLng(ll);
1600            var pin = new google.maps.Marker({
1601                position: dealer_i
1602                , map: map
1603                , zIndex: i + 10
1604                , optimized: false
1605                , icon: pinStyle()
1606                , url: "#dealer-" + (i + 1)
1607                , title: dealers[i].dealerName
1608                , label: {
1609                text: (i+1).toString()
1610                , color: "#fff"
1611                , fontSize: "14px"
1612                , fontWeight: "bold"
1613                , fontFamily: "oswaldbold"
1614            }
1615                                             });
1616            markers.push(pin);
1617            bounds.extend(dealer_i);
1618            
1619            
1620            //this adds a listener to the markers to allow you to click locate lower on the page.
1621            (function (i) {
1622                
1623                google.maps.event.addListener(markers[i+1], 'click', function () {
1624                    $("#dealer-search-results .currentSelection").removeClass('currentSelection');
1625                    
1626                    $('#bCenter-dealer-search-results').find('div.result-entry').each(function () {
1627                        $(this).addClass('hide');
1628                    });
1629                    $(this.url).removeClass("hide");
1630                    var targetPin = $(this.url);
1631                    var pos = targetPin.offset().top;
1632                    
1633                    var dealerPin = 'dealer-' + (i + 1);
1634                    document.getElementById(dealerPin).scrollIntoView({behavior: "smooth", block: "center", inline: "start"});
1635                    document.getElementById(dealerPin).classList.add('currentSelection');
1636                    
1637                });
1638                google.maps.event.addListener(markers[i+1], 'mouseover', function () {
1639                    hideAllInfoWindows(map);
1640                    openMapPin(i,"0");
1641                });
1642                function hideAllInfoWindows(map) {
1643                    markers.forEach(function(marker) {
1644                        if(infowindow.getMap())
1645                            infowindow.close(map,marker);
1646                    }); 
1647                }
1648            })(i);
1649            
1650            
1651            dealerList.push({index:(i + 1), num:i,
1652                             dealerInfo:dealers[i],
1653                             dealerCountry:addressInfo.countryCode,
1654                             linksMap:linksMap,
1655                             labelsMap:labelsMap,
1656                             addressInfo:addressInfo,
1657                             contactInfo:contactInfo,
1658                             segmentMap:segmentMap,
1659                             hoursMap: hoursMap, 
1660                             segmentMap:segmentMap
1661                            });
1662
1663    	}
1664	}
1665	$('#dealer-search-results').html(template({ dealerList }));
1666    if(dealers.length > display)
1667     	jQuery(".results").append(loadMoreContent);                                          
1668    var focusId = 'dealer-' + (parseInt(startPoint) + 1);
1669    document.getElementById(focusId).scrollIntoView({behavior: "smooth", block: "end", inline: "start"});
1670    jQuery(".dealer-search-map").show();
1671    jQuery(".results").fadeIn("800");
1672	if ( document.getElementById("map-location") ){
1673       map.fitBounds(bounds);
1674    }
1675	var $accordion = new Foundation.Accordion($('.accordion'), {
1676   			slideSpeed: 600, multiExpand: true
1677		});
1678    //initialiseTooltip();
1679    checkMyStore();	
1680	document.getElementById('startPoint').value = display;
1681    display = parseInt(display) + parseInt(document.getElementById('displayCount').value);
1682    document.getElementById('count').value = display;
1683}
1684
1685
1686//Function called on click of load more button
1687function loadMore() {
1688    var num = document.getElementById('dealersCount').value;
1689    num = parseInt(num) + 1;
1690    var display = document.getElementById('count').value;
1691	var startPoint = document.getElementById('startPoint').value;
1692    if(num <= display){
1693        display = num;
1694        loadContent(startPoint,display);
1695        document.getElementById('load-more').style.display="none";
1696        jQuery(".results-text").html('Viewing 1 - '+display+' of '+num+' results');
1697    }
1698    else{ 
1699        loadContent(startPoint,display);
1700		jQuery(".results-text").html('Viewing 1 - '+display+' of '+num+' results');
1701    }
1702}
1703
1704//Function called on click of the pin in the map
1705function openMapPin(id,num){
1706    var dealers = JSON.parse(localStorage.getItem('dealersInfo'));
1707    var address = JSON.parse(JSON.stringify(dealers[id].address));
1708    var addressInfo = {};
1709    for (const [key, value] of Object.entries(address)) {
1710        addressInfo[key] = value;
1711    }
1712
1713    var contentString = '<div id="contents">'+
1714        '<div id="sitenotice">'+
1715            '</div>'+
1716                '<div class="grid-x info-window align-middle align-center text-center">'+
1717                    '<div class="cell small-12">'+
1718                        '   <p>'+dealers[id].dealerName+'</p>'+
1719                            ' </div>';
1720    if(dealers[id].distance != undefined){
1721        contentString +=  ' <div class="cell small-5">'+
1722            '  <p class="bold">'+dealers[id].distanceDisplay+'</p>'+
1723                ' </div><div class="break">|</div>';
1724    }
1725    contentString +=   ' <div class="cell small-5">'+
1726        '  <a href="'+addressInfo.mapUrl+'" target="_blank" class="info-directions">'+addressInfo.directionsLinkText+'</a>'+
1727            ' </div>'+
1728                ' </div>'+
1729                    '</div>';
1730
1731	infowindow.setContent(contentString);
1732    infowindow.open({
1733       anchor: markers[id+1],
1734        map,
1735     });
1736        if(num == 1){
1737            var dealerPin = 'dealer-' + (id + 1);
1738            $("#dealer-search-results").find(".currentSelection").removeClass('currentSelection');
1739            document.getElementById(dealerPin).classList.add('currentSelection');
1740    }
1741}
1742
1743//Funtion to call foundation tooltip elements        
1744function initialiseTooltip(){
1745	if($('#dealer-search-results').length){	
1746        $( "#dealer-search-results .result-entry" ).each(function( index ) {
1747            if($(this).find(".toolTip"))
1748            	var elem = new Foundation.Tooltip($(this).find(".toolTip"));
1749        
1750    	});
1751    }
1752}
1753
1754//Function called to highlight the selected store        
1755function checkMyStore () {
1756	if($('#dealer-search-results').length){	
1757		var storeData = getMyStore();
1758		if (storeData && storeData.dealerId != "" ){							
1759			var dealerId = storeData.dealerId;
1760			$( "#dealer-search-results .result-entry" ).each(function( index ) {
1761				var nearbyStoreDealerId = $(this).attr("data-dealer-id");
1762				if (nearbyStoreDealerId != null && nearbyStoreDealerId == dealerId) {
1763                	var dealerCountry = $(this).attr("data-dealerCountry");
1764                    setCookie("dc", dealerCountry,"365",protocol);
1765                    if (dealerCountry == "CA" && canadianPricing == "true") {
1766                                setCookie("currency", "CAD", "365", protocol);
1767                    }
1768					// update button to my store text
1769					setAsMyStore(nearbyStoreDealerId);
1770					$(this).find(".set-dealer-container").addClass("my-dealer-container");
1771					$(this).find(".set-dealer-container").removeClass("set-dealer-container");
1772					var labelFor = $(this).find(".favorite").attr('for');
1773					 $(this).find(".favorite").attr('for', labelFor.replace('set','my'));
1774					var inputId = $(this).find(".dealerRadio").attr('id');
1775					 $(this).find(".dealerRadio").attr('id', inputId.replace('set','my'))
1776         			$(this).find(".dealerRadio").attr('name', 'my-dealer');
1777					$(this).find(".dealerProp").replaceWith('<span id="favorite-1" class="uppercase store-set"> MY DEALER</span>');
1778					$(this).find(".checkmark").removeClass("set-dealer-checkmark");
1779        			$(this).find(".checkmark").addClass("my-dealer-checkmark");
1780                    $(this).find(".checkbox").prop("checked",true);
1781                    $(this).find(".checkbox").prop("disabled",true);
1782                    $(this).find(".checkbox").addClass( "checked" );
1783
1784
1785                } 
1786			});	
1787		}
1788
1789		$("#dealer-search-results .dealerProp").unbind('click');
1790        $("#dealer-search-results .checkbox").unbind('click');
1791        $("#dealer-search-results .dealerProp").click({param1: "fromDealerSearchResults"}, setAsMyStoreClick);
1792		$("#dealer-search-results .checkbox").click({param1: "fromDealerSearchResults"}, setAsMyStoreClick);
1793	}
1794
1795}
1796
1797
1798//Function called on click of the 'Set As My Dealer' button
1799function setAsMyStoreClick(event) {
1800	var dealerId = $(event.target).parent().attr("data-dealer-id");
1801	var dealerCountry = $(event.target).parent().attr("data-dealerCountry");
1802    console.log(canadianPricing);
1803    setCookie("dc", dealerCountry,"365",protocol);
1804    if (dealerCountry == "CA" && canadianPricing == "true") {
1805    			setCookie("currency", "CAD", "365", protocol);
1806    }
1807	setAsMyStore(dealerId);
1808	//displayCanadianPricing();
1809    $(event.target).parent().find(".checkbox").prop("checked",true);
1810	$(event.target).parent().find(".checkbox").prop("disabled",true);
1811
1812
1813	// Change heart to button
1814	$("#dealer-search-results .store-set").replaceWith('<span id="favorite-1" class="uppercase dealerProp">SET AS MY DEALER</span>');
1815	//$("#dealer-search-results .checked").prop("checked",false);
1816    $("#dealer-search-results .checked").prop("disabled",false);
1817    $("#dealer-search-results .checked").removeClass("checked");
1818    var labelFor = $("#dealer-search-results .my-dealer-container").find(".favorite").attr('for');
1819	if(labelFor != undefined)
1820        $("#dealer-search-results .my-dealer-container").find(".favorite").attr('for', labelFor.replace('my','set'));
1821    var inputId = $("#dealer-search-results .my-dealer-container").find(".dealerRadio").attr('id');
1822    if(inputId != undefined)
1823		$("#dealer-search-results .my-dealer-container").find(".dealerRadio").attr('id', inputId.replace('my','set'));
1824    $("#dealer-search-results .my-dealer-container").find(".dealerRadio").attr('name', 'set-dealer');
1825	$("#dealer-search-results .my-dealer-container").addClass("set-dealer-container");
1826    $("#dealer-search-results .my-dealer-container").removeClass("my-dealer-container");
1827	 $("#dealer-search-results .set-dealer-container").find(".checkmark").addClass("set-dealer-checkmark");
1828     $("#dealer-search-results .set-dealer-container").find(".checkmark").removeClass("my-dealer-checkmark");
1829
1830    // Change clicked button to heart
1831    $(event.target).parent().find(".checkbox").addClass("checked");
1832	$(event.target).parent().find(".dealerProp").replaceWith('<span id="favorite-1" class="uppercase store-set"> MY DEALER</span>');
1833	$( "#dealer-search-results .result-entry" ).each(function( index ) {
1834				var nearbyStoreDealerId = $(this).attr("data-dealer-id");
1835				if (nearbyStoreDealerId != null && nearbyStoreDealerId == dealerId) {
1836					$(this).find(".set-dealer-container").addClass("my-dealer-container");
1837					$(this).find(".set-dealer-container").removeClass("set-dealer-container");
1838                    var labelFor = $(this).find(".favorite").attr('for');
1839					if(labelFor != undefined)
1840					 	$(this).find(".favorite").attr('for', labelFor.replace('set','my'));
1841					var inputId = $(this).find(".dealerRadio").attr('id');
1842                    if(inputId != undefined)
1843					 $(this).find(".dealerRadio").attr('id', inputId.replace('set','my'));
1844                     $(this).find(".dealerRadio").attr('name', 'my-dealer');
1845                    $(this).find(".checkmark").removeClass("set-dealer-checkmark");
1846        			$(this).find(".checkmark").addClass("my-dealer-checkmark");
1847                    $(this).find(".checkbox").prop("checked",true);
1848                    $(this).find(".checkbox").prop("disabled",true);
1849                }
1850        		else
1851                    $(this).removeClass("my-dealer-border");
1852        			$(this).addClass("set-dealer-container");
1853	});
1854
1855	$("#dealer-search-results .dealerProp").unbind('click');
1856	$("#dealer-search-results .dealerProp").click({param1: "fromDealerSearchResults"}, setAsMyStoreClick);
1857
1858}
1859
1860//Function called on change of location/DealerName dropdown
1861jQuery(".searchBy-dropdown").on("change", function (e) {
1862    if($("#searchByMenu").val() == "dealerName"){
1863        $(".loadMore").css("display", "none");
1864        jQuery(".results-text").html("");
1865		$(".input-field-dealer").css("display", "block");
1866        $(".arrow-icon").css("display", "none");
1867        $(".input-field").css("display", "none");
1868        $(".miles").css("display", "none");
1869        $(".use-location").css("display", "none");
1870        clearMarkersV2();
1871        //if($(".input-field-dealer").val() != "")
1872			fetchDealerByDealerName();
1873    }
1874    if($("#searchByMenu").val() == "location"){
1875		$(".input-field-dealer").css("display", "none");
1876        $(".input-field").css("display", "block");
1877        $(".input-field").val(localStorage.getItem("searchAddress"));
1878        $(".miles").css("display", "block");
1879        $(".arrow-icon").css("display", "block");
1880        $(".use-location").css("display", "block");
1881		 jQuery(".results-text").html("");
1882        initMap();
1883
1884    }
1885
1886});
1887
1888
1889//Function for setting map pin attributes
1890function pinStyle() {
1891	var fcolor = jQuery("#jsVars").attr("data-pinColor");
1892	if(fcolor == "" || fcolor == undefined)
1893		fcolor = "#FFCC04";
1894	return {
1895		path: 'M 9.94186047,0 C4.46016715,0 0,4.70252703 0,10.4850101 C0,16.047308 9.0383939,30.5467663 9.42364099,31.1601394 C9.53797238,31.3436271 9.7330814,31.4550303 9.94186047,31.4550303 C10.1506395,31.4550303 10.3445058,31.3436271 10.4600799,31.1601394 C10.845327,30.5467663 19.8837209,16.047308 19.8837209,10.4850101 C19.8837209,4.70252703 15.4235538,0 9.94186047,0 z',
1896		fillColor: fcolor,
1897		fillOpacity: 1,
1898		strokeColor: '#000000',
1899		strokeOpacity: 0.125,
1900		strokeWeight: 2,
1901		scale: 1.25,
1902		labelOrigin: new google.maps.Point(10, 10),
1903		anchor: new google.maps.Point(10, 32),
1904		origin: (0, 0)
1905	};
1906
1907}
1908
1909//Function called on click of reset search button
1910function reset(){
1911	$("#search-term").val("");
1912    $(".input-field-dealer").val("");
1913    clearMarkersV2();
1914    jQuery(".results").html(searchDefautltHtml);
1915}
1916
1917//Update dealerId in the Contact Dealer Modal
1918function updateModal(dealer,keyword){
1919    if(keyword == ""){
1920        $('#dealerIdSelect').val(dealer);
1921        $('#dealer-form').css("display", "block");
1922        $('#form-service-inquiry').css("display", "none");
1923        $('#thank-you').css("display", "none");
1924        $('#loader').css("display", "none");  
1925    }
1926    else{
1927        $('#dealerIdServiceSelect').val(dealer);
1928        $('#form-service-inquiry').css("display", "block");
1929        $('#dealer-form').css("display", "none");
1930        $('#thank-you').css("display", "none");
1931        $('#loader').css("display", "none");  
1932    }
1933
1934
1935}
1936
1937function getSelectedDealer(dealerID, currency, boatID) {
1938
1939	var dealerCountry = getCookie("dc");
1940	if (dealerCountry == "CA") {
1941		dealerCountry = "CAD"
1942		//setCookie("currency", "CAD", "365", protocol);
1943        //if (url.indexOf(".ca") <= -1) {
1944            //window.location.href = url.replace(".html", ".ca.html");
1945        //}
1946	} else {
1947		dealerCountry = "USD"
1948		//jQuery(".price-currency").text("USD");
1949		//if (url.indexOf(".ca") > -1) {
1950           // window.location.href = url.replace(".ca.html", ".html");
1951        //}
1952	}
1953	console.log(dealerCountry)
1954	//if (dealerCountry == currency) {
1955		jQuery.ajax({
1956			url: "/bin/boating-sites/dealerboatpricing",
1957			data: "dealerId=" + dealerID + "&boatId=" + boatID + "&currency=" + currency.toLowerCase(),
1958			type: "POST",
1959			error: function () {
1960				console.log("error");
1961			},
1962			success: function (result) {
1963				var resultJson = JSON.parse(result.result)
1964				var prep = parseInt(resultJson.prepCost);
1965				var freight = parseInt(resultJson.zoneCost)
1966				var selectedDealer = '<table class="dealerSelected">' +
1967				'<tr>' +
1968				'	<td class="dealer-name">' + resultJson.name + '</td>' +
1969				'	<td class="dealer-name-link">' +
1970				'		<a data-open="dealer-select-modal-container">Change Dealer</a>' +
1971				'	</td>' +
1972				'</tr>' +
1973				'</table>';
1974				var prepFreight = '<table class="dealerSelected">' +
1975				'<tr>' +
1976				'	<td class="prep-label">Prep:</td>' +
1977				'	<td>' +
1978				'		<div class="prep-value">$' + prep + '</div>' +
1979				'	</td>' +
1980				'</tr>' +
1981				'<tr>' +
1982				'	<td class="freight-label">Freight:</td>' +
1983				'	<td>' +
1984				'		<div class="freight-value">$' + freight + '</div>' +
1985				'	</td>' +
1986				'</tr>' +
1987				'</table>';
1988				jQuery("#pfdealer").html(selectedDealer);
1989				jQuery(".priceResult").html(prepFreight);
1990				jQuery(".your-price").show();
1991				var totalCost = addCommas(resultJson.totalCost);
1992				jQuery(".totalCost").html("$" + totalCost);
1993				jQuery(".showPrep").each(function () {
1994					var prepFreight = prep + freight;
1995					var price = parseInt(jQuery(this).attr("data-price"));
1996					var promo = jQuery(this).attr("data-promo");
1997					var final = prepFreight + price;
1998					var currencyCookie = getCookie("currency");
1999					if (currencyCookie == "CAD") {
2000						var currency = "CAD"
2001					} else {
2002						currency = "USD"
2003					}
2004					if (promo == "true") {
2005						jQuery(this).html("<div class='price promoPrice addComma' style='display:inline-block;'>$" + addCommas(final) + " </div>&nbsp;<div class='price-currency' style='display:inline-block;'>" + currency + "</div>")
2006					} else {
2007						jQuery(this).html("<div class='price addComma' style='display:inline-block;'>$" + addCommas(final) + " </div>&nbsp;<div class='price-currency' style='display:inline-block;'>" + currency + "</div>")
2008
2009					}
2010
2011				});
2012
2013			}
2014		})
2015	//} else {
2016		//setCookie("dealer", "", "365", protocol);
2017	//}
2018}
2019
2020//function to set the dealer id for a store into local storage
2021function setAsMyStore(dealerId) {
2022    var newSearch = "";
2023    if(jQuery("#jsVars").attr("data-newSearch") == "true")
2024        newSearch = "&newSearch="+jQuery("#jsVars").attr("data-newSearch");
2025	if (typeof(Storage) !== "undefined" && dealerId) {
2026		var dealerInfoUrl = "/bin/boating-sites/dealer-info?dealerId=" + dealerId + newSearch;
2027		if (getCookie("userGeoLatitude") && getCookie("userGeoLatitude") != "" && getCookie("userGeoLongitude") && getCookie("userGeoLongitude") != "") {
2028			dealerInfoUrl += "&lat=" + getCookie("userGeoLatitude") + "&long=" + getCookie("userGeoLongitude");
2029		} else if (getCookie("initlatlng") != null && getCookie("initlatlng") !== "") {
2030			var cordlist = getCookie("initlatlng");
2031			var cordlist = getCookie("initlatlng").split('|');
2032			var akamaiLat = cordlist[0];
2033			var akamaiLong = cordlist[1];
2034			dealerInfoUrl += "&lat=" + akamaiLat + "&long=" + akamaiLong;
2035		} else if (long && lat) {
2036			dealerInfoUrl += "&lat=" + lat + "&long=" + long;
2037		}
2038		$.ajax({
2039			url: dealerInfoUrl,
2040			data: {
2041				format: "json"
2042			},
2043			type: "GET",
2044			error: function() {
2045				console.log("error");
2046			},
2047			success: function(result) {
2048				var resultObj = result.result;
2049				if (typeof(resultObj) !== 'undefined' && typeof(resultObj.dealerId) !== 'undefined' 
2050						&& typeof(resultObj.dealerName) !== 'undefined' 
2051						&& typeof(resultObj.websiteUrl) !== 'undefined'
2052					){
2053
2054					setCookie("dealer", resultObj.dealerId, 365);
2055					resultObj.timestamp = Date.now();
2056					localStorage.setItem('myStore', JSON.stringify(resultObj));
2057					showStoreOptions(resultObj);
2058				}
2059			}
2060		});
2061	}
2062	//displayCanadianPricing();
2063}
2064
2065//get dealer data from local storage if set
2066function getMyStore() {
2067	var myStore;
2068	if (typeof(Storage) !== "undefined" && localStorage.myStore) {
2069		myStore = JSON.parse(localStorage.getItem('myStore'));
2070
2071		//if the timestamp is over 30 days, pull fresh
2072		var currentTime = Date.now();
2073		var expiryTimeMillis = 24 * 60 * 60 * 1000
2074		if (currentTime - myStore.timestamp >= expiryTimeMillis) {
2075			setAsMyStore(myStore.dealerId);
2076			myStore = JSON.parse(localStorage.getItem('myStore'));
2077		}
2078	}
2079	return myStore;
2080}
2081
2082//function that returns a boolean for if passed dealer id matches one in local storage
2083function isMyStore(dealerId) {
2084	if (dealerId && typeof(Storage) !== "undefined" && localStorage.myStore) {
2085		var myStore = JSON.parse(localStorage.getItem('myStore'));
2086
2087		if (myStore && myStore.dealerId) {
2088			if (myStore.dealerId == dealerId) {
2089				return true;
2090			}
2091		}
2092	}
2093	return false;
2094}
2095
2096jQuery(document).ready(function($) {
2097    // check to see if dealer info is in storage
2098    var dealerInformation = getMyStore();
2099    var setGeoDealer = $("#dlbSetDealer").data("value");
2100   //setCookie("Geo", "32.9480367|-96.7292871|75081-60626+60628-60634;path=/;Expires=Wed, Jan 01 2021 2:02:02 GM", 1);
2101
2102	if (dealerInformation != null) {
2103		showStoreOptions(dealerInformation);
2104    }
2105    else if(getCookie("userGeoLatitude") !== "undefined" && getCookie("userGeoLatitude") != null && getCookie("userGeoLongitude") !== "undefined" && getCookie("userGeoLongitude") != null && setGeoDealer == true){
2106			
2107            findSetDealer("", getCookie("userGeoLatitude"), getCookie("userGeoLongitude"));
2108      }
2109
2110	else if( typeof(getCookie("initlatlng")) !== "undefined" && getCookie("initlatlng") != null && setGeoDealer == true || getCookie("initlatlng") != "" && setGeoDealer == true){
2111			var initlatlng = getCookie("initlatlng").split("|");
2112			findSetDealer("", initlatlng[0], initlatlng[1]);
2113	}
2114
2115
2116});
2117
2118function findSetDealer(pos, lat, long){
2119	
2120	if ( typeof(pos) !== "undefined" && pos != ""){
2121		showLocation(pos);
2122	} else {
2123		showLocationWithLatLong(lat, long);
2124	}
2125}
2126
2127// Grab the user location and call backend
2128function showLocation(position) {
2129    var lat = position.coords.latitude;
2130    var long = position.coords.longitude;
2131    var newSearch = "";
2132    if(jQuery("#jsVars").attr("data-newSearch") == "true")
2133		newSearch = "&newSearch="+jQuery("#jsVars").attr("data-newSearch");
2134    var brand = ""
2135    if(jQuery("#jsVars").attr("data-brand") != "undefined")
2136        brand = "&brand=" + jQuery("#jsVars").attr("data-brand");
2137    var userGeoLatitude, userGeoLongitude, userGeoZip;
2138    if ((typeof(lat) !== "undefined" && lat) && (typeof(long) !== "undefined" && long)) {
2139
2140        var browserLocationAccess = getCookie("browserLocationAccess");
2141        userGeoLatitude = getCookie("userGeoLatitude");
2142        userGeoLongitude = getCookie("userGeoLongitude");
2143        userGeoZip = getCookie("userGeoZip");
2144        if ((!userGeoLatitude || userGeoLatitude == "") || (!userGeoLongitude || userGeoLongitude == "")) {
2145            setCookie("userGeoLatitude", lat, 365);
2146            setCookie("userGeoLongitude", long, 365);
2147        }
2148        // check if the browser has given access to the user location.
2149        // reload the page only if its on inventory page
2150        if ((typeof(browserLocationAccess) === 'undefined' || browserLocationAccess === null || browserLocationAccess == "") && window.location.href.indexOf("s-for-sale") > -1) {
2151            setCookie("browserLocationAccess", 'true', 365);
2152        } else {
2153            setCookie("browserLocationAccess", 'false', 365);
2154        }
2155		if (typeof(userGeoZip) === 'undefined' || userGeoZip === null || userGeoZip == "") {
2156            getAddress(lat, long).then(function(data) {
2157                if (data.results != undefined && data.results.length > 0) {
2158                    var addressData = data.results[0].address_components;
2159                    for (var i in addressData) {
2160                        var type = addressData[i].types[0];
2161                        if (type == "postal_code") {
2162                            var zip = addressData[i].short_name;
2163                            setCookie("userGeoZip", zip, 365);
2164                        }
2165                    }
2166                }
2167				// Call servlet to get the store information
2168				var dealerInfoUrl = "/bin/boating-sites/dealer-info?lat=" + lat + "&long=" + long + newSearch + brand;
2169				processAjaxCall(dealerInfoUrl);
2170            });
2171		} else {
2172			// Call servlet to get the store information
2173			var dealerInfoUrl = "/bin/boating-sites/dealer-info?lat=" + lat + "&long=" + long + newSearch + brand;
2174			processAjaxCall(dealerInfoUrl);
2175        }
2176
2177    }
2178}
2179
2180function showLocationWithLatLong(passedLat, passedLong) {
2181		var lat = passedLat;
2182		var long = passedLong;
2183        var newSearch = "";
2184        if(jQuery("#jsVars").attr("data-newSearch") == "true")
2185            newSearch = "&newSearch="+jQuery("#jsVars").attr("data-newSearch");
2186        var brand = ""
2187        if(jQuery("#jsVars").attr("data-brand") != "undefined")
2188            brand = "&brand=" + jQuery("#jsVars").attr("data-brand");
2189		var userGeoLatitude, userGeoLongitude, userGeoZip;
2190		if ((typeof(lat) !== "undefined" && lat) && (typeof(long) !== "undefined" && long)) {
2191
2192			//var browserLocationAccess = getCookie("browserLocationAccess");
2193			userGeoLatitude = getCookie("userGeoLatitude");
2194			userGeoLongitude = getCookie("userGeoLongitude");
2195			userGeoZip = getCookie("userGeoZip");
2196			if ((!userGeoLatitude || userGeoLatitude == "") || (!userGeoLongitude || userGeoLongitude == "")) {
2197				setCookie("userGeoLatitude", lat, 365);
2198				setCookie("userGeoLongitude", long, 365);
2199			}
2200			if (typeof(userGeoZip) === 'undefined' || userGeoZip === null || userGeoZip == "") {
2201				getAddress(lat, long).then(function(data) {
2202					if (data.geoloc.ZIP != undefined) {
2203						setCookie("userGeoZip", data.geoloc.ZIP, 365);
2204					}
2205					// Call servlet to get the store information
2206					var dealerInfoUrl = "/bin/boating-sites/dealer-info?lat=" + lat + "&long=" + long + newSearch + brand;
2207					processAjaxCall(dealerInfoUrl);
2208				});
2209			} else {
2210				// Call servlet to get the store information
2211				var dealerInfoUrl = "/bin/boating-sites/dealer-info?lat=" + lat + "&long=" + long + newSearch + brand;
2212				processAjaxCall(dealerInfoUrl);
2213			}
2214		}
2215	}
2216
2217function errorHandler(err) {
2218    var newSearch = "";
2219    if(jQuery("#jsVars").attr("data-newSearch") == "true")
2220        newSearch = "&newSearch="+jQuery("#jsVars").attr("data-newSearch");
2221    var brand = ""
2222    if(jQuery("#jsVars").attr("data-brand") != "undefined")
2223        brand = "&brand=" + jQuery("#jsVars").attr("data-brand");
2224    if (err.code == 1 || err.code == 2) {
2225			// alert("Error: Access is denied!");
2226			// alert("Error: Position is unavailable!");
2227			if ((typeof(browserLocationAccess) === 'undefined' ||
2228					browserLocationAccess === null ||
2229					browserLocationAccess == "") &&
2230					window.location.href.indexOf("s-for-sale") > -1) {
2231            setCookie("browserLocationAccess", 'false', 365);
2232//				location.reload();
2233        } else {
2234            setCookie("browserLocationAccess", 'false', 365);
2235        }
2236        if (getCookie("Geo") != null && getCookie("Geo") !== "") {
2237            var cordlist = getCookie("Geo").split('|');
2238            var dealerInfoUrl = processGeoCookie(cordlist);
2239            processAjaxCall(dealerInfoUrl);
2240        } else if (getCookie("initlatlng") != null && getCookie("initlatlng") !== "") {
2241            var cordlist = getCookie("initlatlng");
2242            var cordlist = getCookie("initlatlng").split('|');
2243            var lat = cordlist[0];
2244            var long = cordlist[1];
2245            var dealerInfoUrl = "/bin/boating-sites/dealer-info?lat=" + lat + "&long=" + long + newSearch + brand;
2246            processAjaxCall(dealerInfoUrl);
2247
2248        }
2249    }
2250}
2251
2252function processGeoCookie(geoVars) {
2253    var newSearch = "";
2254    if(jQuery("#jsVars").attr("data-newSearch") == "true")
2255        newSearch = "&newSearch="+jQuery("#jsVars").attr("data-newSearch");
2256    var brand = ""
2257    if(jQuery("#jsVars").attr("data-brand") != "undefined")
2258        brand = "&brand=" + jQuery("#jsVars").attr("data-brand");
2259	var cordlist = geoVars.split('|');
2260    if (cordlist.length > 2) {
2261        var akamaiLat = cordlist[0];
2262        var akamaiLong = cordlist[1];
2263        var akamaiZipRange = cordlist[2];
2264        var akamaiZip = "";
2265        // Method to get the zip value from a variety of possibilities
2266        if (akamaiZipRange != null && akamaiZipRange !== "") {
2267            if (akamaiZipRange.indexOf('+') > -1) {
2268                // checking for data like
2269                // "60601-60626+60628-60634+60636-60641+60643-60647"
2270                var zipRangeWithPlusArray = akamaiZipRange.split('+');
2271                if (zipRangeWithPlusArray[0].indexOf('-') > -1) {
2272                    var zipWithMinusArray = zipRangeWithPlusArray[0].split('-');
2273                    akamaiZip = zipWithMinusArray[0];
2274                } else {
2275                    // Checking for data like "m3h+m3h"
2276                    akamaiZip = zipRangeWithPlusArray[0];
2277                }
2278            }
2279            // Checking for data like "60601-60601
2280            else if (akamaiZipRange.indexOf('-') > -1) {
2281                var zipRangeWithMinusArray = akamaiZipRange.split('-');
2282                akamaiZip = zipRangeWithMinusArray[0];
2283            }
2284            // Checking for data like "60601"
2285            else {
2286                akamaiZip = akamaiZipRange;
2287            }
2288        }
2289        var akamaiLatLongCookie = getCookie("initlatlng");
2290        var akamaiZipCookie = getCookie("initzip");
2291        if (!akamaiLatLongCookie || akamaiLatLongCookie == "") {
2292            var akamaiLatLong = akamaiLat + "|" + akamaiLong;
2293            setCookie("initlatlng", akamaiLatLong, 365);
2294        }
2295        if (!akamaiZipCookie || akamaiZipCookie == "") {
2296            setCookie("initzip", akamaiZip, 365);
2297        }
2298        var dealerInfoUrl = "/bin/boating-sites/dealer-info?lat=" + akamaiLat + "&long=" + akamaiLong + newSearch + brand;
2299        return dealerInfoUrl;
2300    }
2301}
2302
2303function processAjaxCall(dealerInfoUrl) {
2304    $.ajax({
2305        url: dealerInfoUrl,
2306        data: {
2307            format: "json"
2308        },
2309        type: "GET",
2310        error: function() {
2311            console.log("error");
2312        },
2313        success: function(result) {
2314            	var resultObj = result.result;
2315            	if (typeof(resultObj) !== 'undefined' && typeof(resultObj.dealerId) !== 'undefined' && typeof(resultObj.dealerName) !== 'undefined' &&
2316            			typeof(resultObj.websiteUrl) !== 'undefined') {
2317            		
2318            		resultObj.timestamp = Date.now();
2319            		localStorage.setItem('myStore', JSON.stringify(resultObj));
2320            	}
2321            	var dealerInfo = getMyStore();
2322            	if (dealerInfo != null) {
2323            		showStoreOptions(dealerInfo);
2324            	}
2325        }
2326    });
2327}
2328
2329function showStoreOptions(dealerInfo) {
2330    $('.mini-nav').show();
2331    var boatID = jQuery(".boatID").attr("data-boatID");
2332    if (dealerInfo.phone1) {
2333        var phoneHref = 'tel:' + dealerInfo.phone1.replace(/[()-\s]/g, '');
2334        $('#dealerNavPhone a').attr("href", phoneHref);
2335        $('#dealerNavPhone .number-digits').html(dealerInfo.phone1);
2336    }
2337
2338    if (dealerInfo.dealerName) {
2339        $('.your-store .store-name').html(dealerInfo.dealerName);
2340    }
2341    if (dealerInfo.dealerId && !(window.location.href).includes("dealer")) {
2342    	setCookie('dealer',dealerInfo.dealerId);
2343    }
2344    if (!getCookie('dc')  && dealerInfo.address.countryCode)
2345		setCookie('dc',dealerInfo.address.countryCode);
2346    if (dealerInfo.dealerId && boatID != "" && boatID != null && boatID != "undefined" ){
2347		getSelectedDealer(dealerInfo.dealerId, getCookie('currency'), boatID);
2348    }
2349
2350    var websiteUrl = dealerInfo.websiteUrl;
2351    $(".dealerNavProfile .button").click(function(e) {
2352        e.preventDefault();
2353        window.location.href = websiteUrl;
2354    });
2355    prefillDealerSearchInput();
2356
2357}
2358function prefillDealerSearchInput(){
2359	if(getCookie("userGeoLatitude") !== "undefined" && getCookie("userGeoLatitude") != null && getCookie("userGeoLongitude") !== "undefined" && getCookie("userGeoLongitude") != null && (window.location.href).includes("dealer") && !getCookie('dealer')){
2360            var latlng = getCookie("userGeoLatitude") + "," + getCookie("userGeoLongitude");
2361        if(getCookie("userGeoZip") !== "undefined" && getCookie("userGeoZip") != null && getCookie("userGeoZip") != ""){
2362            $(".input-field").val(getCookie("userGeoZip"));
2363            fetchDealerListByRadius(latlng);
2364        }
2365    }
2366}
2367
2368

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.