(function($) {

	/************************
	Google Event Tracking
	************************/
	$(document).ready(function() {
		$('[data-tracking]').each(function(index) {
			var $thisLink = $(this);
			$thisLink.click( function() {
				$attribs = $thisLink.attr("data-tracking").split(",");
				ga('global.send', 'event', $attribs[0], $attribs[1], $attribs[2]);
				ga('local.send', 'event', $attribs[0], $attribs[1], $attribs[2]);
        		ga('client.send', 'event', $attribs[0], $attribs[1], $attribs[2]);
		  });
		});
	});

})(window.jQuery);

// Custom string.format()
if (!String.prototype.format) {
	String.prototype.format = function() {
        var args = arguments;
        if (typeof args[0] === typeof ({})) args = args[0];
		/*return this.replace(/{(\w+)}/gi,
			function(match, number) {
                console.log(match);
				var index = match.substring(1, match.length - 1);
				return typeof args[index] != 'undefined'
					? args[index]
					: match;
            });*/
        var result = this;
        $.each(args, (name, value) => {
            result = result.replace("\{" + name + "\}", value)
        });
        return result;
	};
}

class MergeModel {
	constructor(name) {
		this.name = name;
		this.patterns = [];
	}

	merge(data) {
		if (typeof data !== typeof ({})) throw new TypeError("You must use a dictionary!");

		var masterPattern = "";
        this.patterns.forEach((p) => masterPattern += p);
        masterPattern = masterPattern.replace(/\./g, ".").replace(/\,/g, ",").replace(/\\/g, "\\");
		return masterPattern.format(data);
	}
}

class TableHeader {
	constructor(name, isTitle, isSubtitle, isFooter, isActionLinks, footerPattern = undefined, mergeModel = undefined) {
		this.name = name;
		this.isTitle = isTitle;
		this.isSubtitle = isSubtitle;
		this.isFooter = isFooter;
        this.isActionLinks = isActionLinks;
        this.footerPattern = footerPattern;
		this.mergeModel = mergeModel;
	}
}

function tableToCards() {
    $("table.table").each(function (j, table) {
	    if (table.hasAttribute("data-card-ignore")) return;

		const tableId = $(this).attr("id");
		if (tableId === undefined) {
			console.error("All tables need an ID for tableToCards to work properly!");
		}

		$(`div.table-card-deck#${tableId}`).remove();

		var cardWidth = $(this).attr("data-card-width");
		if (cardWidth === undefined) cardWidth = 991;
		if ($(window).width() > cardWidth) {
			$(this).show();
			return;
		}

		var headers = [];
		var mergeModels = {};

		// Parse merge models
		$(this).find("thead tr th").each((i, th) => {
			if (!th.hasAttribute("data-card-merge-name") || !th.hasAttribute("data-card-merge-index")) return;

			var mergeName = $(th).attr("data-card-merge-name"),
				mergeIndex = $(th).attr("data-card-merge-index"),
				mergePattern = $(th).attr("data-card-merge-pattern");

			if (mergePattern === undefined) mergePattern = "{0} ";
			if (mergeModels[mergeName] === undefined) mergeModels[mergeName] = new MergeModel(mergeName);

			mergePattern = mergePattern.replace(/\{0\}/g, "{" + th.innerHTML.replace(/\s/g, "_") + "}");
			mergeModels[mergeName].patterns[mergeIndex] = mergePattern;
		});

		// Parse headers
		$(this).find("thead tr th").each((i, th) => {
			headers.push(new TableHeader(
				th.innerHTML.replace(/(^\s+|\s+$)/g, ""),
				th.hasAttribute("data-card-title"),
				th.hasAttribute("data-card-subtitle"),
				th.hasAttribute("data-card-footer"),
                th.hasAttribute("data-card-action-links"),
                $(th).attr("data-card-footer-pattern"),
				mergeModels[$(th).attr("data-card-merge-name")]
			));
		});

		// Generate cards
		var cards = [];
		$(this).find("tbody tr").each(function() {
			var cardTitle = $("<h5>").addClass("card-title");
			var cardSubtitles = [];
			var cardText = $("<p>").addClass("card-text");
			var cardFooters = $("<div>").addClass("card-footer text-muted");
			var actionLinks = [];

			var appliedFormats = [];
			var rowData = {};

			$(this).children("td").each((i, td) => rowData[headers[i].name.replace(/\s/g, "_")] = td.innerHTML.replace(/(^\s+|\s+$)/g, ""));

			$(this).children("td").each(function(i, td) {
				var header = headers[i];
				if (header.isActionLinks) {
					// Action links
					$(this).find("a").each((i, a) => actionLinks.push(
						$("<a>").addClass("card-link").html(a.innerHTML).attr("href", $(a).attr("href"))
                    ));
					return;
				}
				if (header.isTitle) {
					// Title field
					cardTitle.html(td.innerHTML);
					return;
				}
				if (header.isSubtitle) {
					// Subtitle field
					cardSubtitles.push(
						$("<h6>").addClass("card-subtitle mb-2 text-muted").html(td.innerHTML)
					);
					return;
				}
				if (header.isFooter) {
                    //Footer field
                    let pattern = headers[i].footerPattern;
                    if (pattern === undefined) pattern = "{0}";

					cardFooters.append(
                        $("<span>").html(pattern.format(td.innerHTML, headers[i].name) + " ")
					);
					return;
				}
				if (header.mergeModel === undefined) {
					// console.log(cardText);
					// Data field without merge
					// Fix for : in card!!!
						cardText.append(
							$("<span>").append(
								$("<b>").html(header.name + ": ")
							).append(td.innerHTML).append($("<br>"))
						);

				} else {

					// Formatted data field
					if (appliedFormats.indexOf(header.mergeModel.name) === -1) {
						// Format not yet applied -> do so now
						cardText.append(
							$("<span>").append(
								$("<b>").html(header.mergeModel.name + ": ")
							).append(header.mergeModel.merge(rowData)).append("<br>")
						);
						appliedFormats.push(header.mergeModel.name);
					}
				}
			});

            if (cardTitle.html() === "") cardTitle = undefined;
            if (cardFooters.html() === "") cardFooters = undefined;

			cards.push(
				$("<div>").addClass("card mb-3").append(
					$("<div>").addClass("card-body")
					.append(cardTitle)
					.append(cardSubtitles)
                    .append(cardText)
					.append(actionLinks)
                ).append(cardFooters)
			);
        });

		// Instantiate cards, hide table
		var cardWrapper = $("<div>").addClass("table-card-deck").attr("id", tableId);
		cards.forEach(card => {
			cardWrapper.append(card);
		});

		$(this).parent().append(cardWrapper);
		$(this).hide();
	});
}

$(window).resize(tableToCards);
$(window).ready(tableToCards);

(function($) {

  // Prevent main nav dropdown click
	$(document).on('click touchstart touchend','nav ul#menu > li > a.no-click',function(e){
		if (this.href.indexOf('#') != -1) {
			e.preventDefault();
			e.stopPropagation();
    }
	});


	function mobDrop() {
		$('#mobile-menu .dropdown, #slideout-menu .dropdown').each(function(){
			var x = $(this).find('ul').length;
			if (x <= 0){
				$(this).find('.arrow').css({'display':'none'});
			}
		});

	}

	// Detect touch device
	function is_touch_device() {
			return !!('ontouchstart' in window) || (!!('onmsgesturechange' in window) && !!window.navigator.maxTouchPoints);
	}


	// Dropdown menu links
	function dropLinkPath() {
		winW = $(window).width();
		if (!is_touch_device()) {
			if (winW > 768) {
				$('header .menu li.dropdown').each(function(){
					var path = $(this).find('ul li:first-child a').attr('href');
					if (path != undefined) {
						$(this).find('>:first-child').attr('href',path)
					}
				});
			} else {
				$('header .menu li.dropdown').each(function(){
					var isDropdown = $(this).find('ul').length;
					if (isDropdown > 0) {
						$(this).find('>:first-child').removeAttr("href");
					}
				});
			}
		}
	}
	$(document).ready(dropLinkPath);
	$(window).resize(dropLinkPath);


	// Menu slide
	function menu_slide() {
			$(".menu-slide-container").prepend('<a class="close-menu" href="#">&times</a>');
			$(".menu-button").on("click", function(e) {
				e.preventDefault();
				$(".menu-slide-container").toggleClass("menu-open");
				$("#header, #header-sticky").toggleClass("header-hidden");
			});
			$(".close-menu").on("click", function(e) {
				e.preventDefault();
				$(".menu-slide-container").removeClass("menu-open");
				$("#header, #header-sticky").removeClass("header-hidden");
			});
			$(".menu-slide li").each(function() {
				if ($(this).hasClass('dropdown') || $(this).hasClass('megamenu')) {
					$(this).append('<div class="arrow"></div>');
				}
			});
			$(".menu-slide li.dropdown > div").on("click", function(e) {
				e.preventDefault();
				$(this).toggleClass("open").prev("ul").slideToggle(300);
			});
			$(".menu-slide li.megamenu > div").on("click", function(e) {
				e.preventDefault();
				$(this).toggleClass("open").prev("div").slideToggle(300);
			});
		}

	// Show/hide mobile menu
	function show_hide_mobile_menu() {

			$("#mobile-menu-button,#sticky-menu-button").on("click", function(e) {
				e.preventDefault();
				$("#mobile-menu").slideToggle(300);
			});

		}

	// Mobile menu - this creates the mobile menu
	function mobile_menu() {
			var mms = $('#header-container').data('mms');
			if ($(window).width() < mms) {
				if ($("#menu").length < 1) {
					$("#header").append('<ul id="menu" class="menu-2">');
					$("#menu-left").clone().children().appendTo($("#menu"));
					$("#menu-right").clone().children().appendTo($("#menu"));
				}
				if ($("#menu").length > 0) {
					if ($("#mobile-menu").length < 1) {
						$("#menu").clone().attr({
							id: "mobile-menu",
							class: ""
						}).insertAfter("#header");
						$("#mobile-menu li").each(function() {
							if ($(this).hasClass('dropdown') || $(this).hasClass('megamenu')) {
								$(this).append('<div class="arrow"></div>');
							}
						});
						$("#mobile-menu .megamenu .arrow").on("click", function(e) {
							e.preventDefault();
							$(this).toggleClass("open").prev("div").slideToggle(300);
						});
						$("#mobile-menu .dropdown .arrow").on("click", function(e) {
							e.preventDefault();
							$(this).toggleClass("open").prev("ul").slideToggle(300);
						});
					}
				}
			} else {
				$("#mobile-menu").hide();
				$(".menu-2").hide();
			}


		}


// Slideout menu
	function slideout_menu() {
			if ($('body').hasClass("slideout")) {

				var slidePos = $('#logo').height();
				$('.slideout #header nav, .slideout #header-sticky nav').css('height',slidePos).css('width',slidePos);
			    $('#slideout-menu').css('padding-top',slidePos);


				if ($("#menu").length < 1) {
					$("#header").append('<ul id="menu" class="menu-2">');
					$("#menu-left").clone().children().appendTo($("#menu"));
					$("#menu-right").clone().children().appendTo($("#menu"));
					$(this).css('color', 'var(--stickyburger-color)');
				}

				if ($("#menu").length > 0) {
					if ($("#slideout-menu").length < 1) {
						$(this).css('color', 'var(--hamburger-color)');
						$("#menu").clone().attr({
							id: "slideout-menu",
							class: ""
						}).insertAfter("#header");
						$("#slideout-menu li").each(function() {
							if ($(this).hasClass('dropdown') || $(this).hasClass('megamenu')) {
								$(this).append('<div class="arrow"></div>');
							}
						});
						$("#slideout-menu .megamenu .arrow").on("click", function(e) {
							e.preventDefault();
							$(this).toggleClass("open").prev("div").slideToggle(300);
						});
						$("#slideout-menu .dropdown .arrow").on("click", function(e) {
							e.preventDefault();
							$(this).toggleClass("open").prev("ul").slideToggle(300);

						});

						$('#slideout-menu').wrapAll('<div id="slideoutWrapper"></div>');
						$("#super-header .agent-phone, #super-header .agent-email, #login-account").detach().appendTo('#slideout-menu');
						$('#login-account').wrapAll('<li class="dropdown"></li>');
					}
				}
			}

			}


		$("#mobile-menu-button").on("click", function() {
				slideout_menu();
				$('#slideout-menu').toggle("slide", {direction: "right" }, 300);
				$(this).find('span').toggleClass("icon-menu icon-close");

		});

		// $("#mobile-menu-button").each(function() {
		//     $(this).on("click", function(){
		//         slideout_menu();
		// 		$('#slideout-menu').toggle("slide", {direction: "right" }, 300);
		// 		$(this).find('span').toggleClass("icon-menu icon-close");
		//     });
		// });



	// Header Positioning

	$('#header').ready(function() {


		// Slim menu
			function slim_menu() {
				if ($('body').hasClass("slim")) {
				var slimPos = $('#header .right').height();
				var slimscrollPos = $('#header.scrolled .right').height();
				$('.menu li.dropdown ul').css('top',slimPos);
				$('#header.scrolled .menu li.dropdown ul').css('top',slimscrollPos);

				}
			}
			slim_menu();


			// Centered menu
			function centernav_menu() {
				if ($('body').hasClass("centernav")) {
				var slimPos = $('#header .right').height();
				var slimscrollPos = $('#header.scrolled .right').height();
				$('.menu li.dropdown ul').css('top',slimPos);
				$('#header.scrolled .menu li.dropdown ul').css('top',slimscrollPos);

				}
			}
			centernav_menu();

		// IDX Header Content Wrapper

		function idx_menu() {
		  var SuperHeader = $('#super-header').height();
		  var Header = $('#header').height();
		   $('.secondary #content-wrapper, #homes-for-sale-search-advanced #content-wrapper,#email-alerts #content-wrapper,#homes-for-sale-details #content-wrapper,#homes-for-sale-sold-details #content-wrapper,#homes-for-sale-sold-details #content-wrapper,#homes-for-sale-results #content-wrapper,#homes-for-sale-search #content-wrapper,#homes-for-sale-toppicks #content-wrapper,#market-report #content-wrapper,#listing-report #content-wrapper,#open-home-report #content-wrapper,#open-home-search #content-wrapper,#pending-featured-listing #content-wrapper,#sold-featured-listing #content-wrapper,#supplemental-listing #content-wrapper').css('padding-top',SuperHeader+Header);
			}
			idx_menu();
		})



	// Sticky header
	function sticky() {
			var sticky_point = 80;
			var logoSrc = $('#logo img').data('main');
			var logoAltSrc = $('#logo img').data('alt');
			$("#header").clone().attr({
				id: "header-sticky",
				class: ""
			}).insertAfter("header");
			$(window).on("scroll", function() {
				var scroll = $(window).scrollTop();
				var idxHeader = $('.ihf-top-nav').length;
		       var stickyHeight = $('#header-sticky').height();
		       var slimscrollPos = $('#header.scrolled .right').height();
		       $('.slim #header-sticky .menu > li.dropdown ul').css('top',slimscrollPos);

				if ($(window).scrollTop() > sticky_point && idxHeader == 0) {
						$('#logo img').attr('src',logoAltSrc);
						$("#header-sticky").addClass("header-sticky");
						$("#header-sticky").css({'top':0});
						// $(".slideout #mobile-menu-button").css({'position':'fixed'});
						$(".slideout #mobile-menu-button span.icon-menu").css({'color':'var(--stickyburger-color)'});
						$("#header .menu ul, #header .menu .megamenu-container").css({"visibility": "hidden"});
				} else if ($(window).scrollTop() > sticky_point && idxHeader > 0) {
					var idxHeaderOffset = $('.ihf-top-nav').offset().top;
					var offset = idxHeaderOffset - stickyHeight;

					if (scroll >= offset) {

						// $('#logo img').attr('src',logoSrc);
						var hSh = 0-parseInt($("#header-sticky").outerHeight());
						$("#header-sticky").removeClass("header-sticky"); $("#header-sticky").css({'top':hSh});
						// $(".slideout #mobile-menu-button").css({'position':'absolute'});
						$(".slideout #mobile-menu-button span.icon-menu").css({'color':'var(--hamburger-color)'});
						$("#header .menu ul, #header .menu .megamenu-container").css({"visibility": "visible"});
					} else {

							$('#logo img').attr('src',logoAltSrc);
							$("#header-sticky").addClass("header-sticky");
							$("#header-sticky").css({'top':0});
							// $(".slideout #mobile-menu-button").css({'position':'fixed','top':'44px'});
							$(".slideout #mobile-menu-button span.icon-menu").css({'color':'var(--stickyburger-color)'});
							$("#header .menu ul, #header .menu .megamenu-container").css({"visibility": "hidden"});
					}
				} else {
					$('#logo img').attr('src',logoSrc);
					var hSh = 0-parseInt($("#header-sticky").outerHeight());
					$("#header-sticky").removeClass("header-sticky"); $("#header-sticky").css({'top':'-150px'});
					// $(".slideout #mobile-menu-button").css({'position':'absolute'});
					$(".slideout #mobile-menu-button span.icon-menu").css({'color':'var(--hamburger-color)'});
					$("#header .menu ul, #header .menu .megamenu-container").css({
						"visibility": "visible"
					});
				}
			});
		}

	// Show/hide scroll up


	function show_hide_scroll_top() {

		if ($(window).width() < 992) {
			if ($(window).scrollTop() > $(window).height() / 2) {
				$("#scroll-up").fadeIn(300);
			} else {
				$("#scroll-up").fadeOut(300);
			}
		}

		}

	// Scroll up
	function scroll_up() {
			$("#scroll-up").on("click", function() {
				$("html, body").animate({
					scrollTop: 0
				}, 800);
				return false;
			});
		}

	// Document ready
	$(document).ready(function() {

		// Sticky
		if ($("body").hasClass("sticky-header")) {
			sticky();
		}

		// Menu
		// if (typeof $.fn.superfish !== 'undefined') {
		// 	$(".menu").superfish({
		// 		delay: 500,
		// 		animation: {
		// 		opacity: 'show',
		// 		height: 'show'
		// 	},
		// 		speed: 'fast',
		// 		autoArrows: true
		// 	});
		// }

		menu_slide();
		show_hide_mobile_menu();
		mobile_menu();
		slideout_menu();
		mobDrop();

		// Parallax
		if (typeof $.fn.stellar !== 'undefined') {
			multilayer_parallax();
			if (!is_touch_device()) {
				$(window).stellar({
					horizontalScrolling: false,
					verticalScrolling: true,
					responsive: true
				});
			} else {
				$(".parallax").addClass("parallax-disable");
			}
		}

		show_hide_scroll_top();
		scroll_up();

		// Fullpage
		if (typeof $.fn.fullpage !== 'undefined') {
			$('.fullpage').fullpage({
				scrollBar: true,
				fitToSection: false,
				scrollOverflow: true,
				keyboardScrolling: false
			});
		}
	});

	// Window scroll
	$(window).on("scroll", function() {
		show_hide_scroll_top();
	});

	// Window resize
	$(window).resize(function() {
		mobile_menu();
	});





})(window.jQuery);

(function($) {
	$('.shareBlock .shareTitle').off('click');
	$('.shareBlock .shareTitle').on('click',function(){
		$('.shareBlock').toggleClass('show');
	});
})(jQuery);				
				