(function ($) { "use strict"; /* ----------- START OF LOCATIONS SELECT BOXES CODE ----------- */ if (typeof realhomesLocationsData !== 'undefined') { const hierarchicalLocations = realhomesLocationsData.all_locations; /* All locations */ const selectBoxesIDs = realhomesLocationsData.select_names; /* Select boxes names that can be used as ids */ const selectBoxesCount = parseInt(realhomesLocationsData.select_count); /* Number of select boxes to manage */ const multiSelect = realhomesLocationsData.multi_select_locations; /* Location boxes are multiselect or not */ const anyText = realhomesLocationsData.any_text; /* "Any" text as it could be translated */ const anyValue = realhomesLocationsData.any_value; /* "any" value */ const slugsInQueryParams = realhomesLocationsData.locations_in_params; /* parameters related to location boxes */ const consoleLogEnabled = false; /* A flag to enable disable console logging while development OR troubleshooting */ /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('realhomesLocationsData.locations_in_params: '); console.log(slugsInQueryParams); } /** * Initialize Locations Select Boxes * * Following function automatically runs to initialize locations boxes */ (function () { /* prepare select boxes */ prepareSelectBoxes(); let parentLocations = []; for (let selectIndex = 0; selectIndex < selectBoxesCount; selectIndex++) { const currentSelect = $('#' + selectBoxesIDs[selectIndex]); /* loop's current select box */ const currentIsLast = (selectBoxesCount === (selectIndex + 1)); /* check if current select box is last */ if (selectIndex === 0) { /* First iteration */ parentLocations = addParentLocations(currentSelect, currentIsLast); } else { /* later iterations */ /* If parents locations array is not empty then there could be children to add in current select box */ if (parentLocations.length > 0) { let currentLocations = []; const previousSelect = $('#' + selectBoxesIDs[selectIndex - 1]); /* loop through all if value is "any" */ if (previousSelect.val() === anyValue) { for (let i = 0; i < parentLocations.length; i++) { let tempLocations = addChildrenLocations(currentSelect, parentLocations[i].children, '', currentIsLast); if (tempLocations.length > 0) { currentLocations = $.merge(currentLocations, tempLocations); } } } else { /* Otherwise add only children of previous selected location, It there are any. */ let previousLocation = searchLocation(previousSelect.val(), hierarchicalLocations); if (previousLocation && previousLocation.children.length > 0) { currentLocations = addChildrenLocations(currentSelect, previousLocation.children, '', currentIsLast); } } /* hook up updateChildSelect function with previous select change event */ previousSelect.change(updateChildSelect); /* currentLocations variable is passed to parentLocations for code below and for next iteration */ parentLocations = currentLocations; } } /* If parentLocations is empty */ if (parentLocations.length === 0) { /* disable current select and children selects if any */ disableSelect(currentSelect); /* No need for further iterations */ break; } else { /* Select the right option within current select based on query parameters */ selectParamOption(currentSelect); } } /* end of loop */ })(); /* Run the function immediately after declaration */ /** * Adds top level locations to given select box, If addAllChildren is true then it adds all children locations as well * @param targetSelect * @param addAllChildren * @returns {*[]} */ function addParentLocations(targetSelect, addAllChildren) { let addedLocations = []; let insertionCounter = 0; /* loop through top level locations */ hierarchicalLocations.forEach(function (currentLocation, index, locationsArray) { targetSelect.append(''); addedLocations[insertionCounter++] = currentLocation; /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('addParentLocations: ' + currentLocation.slug + ' in ' + targetSelect.attr('id')); } if (addAllChildren && currentLocation.children.length) { addChildrenLocations(targetSelect, currentLocation.children, '- ', addAllChildren); } }); return addedLocations; } /** * Adds top level locations form given childrenLocations array to targetSelect box, If addAllChildren is true then it adds all children locations as well * @param targetSelect * @param childrenLocations * @param prefix * @param addAllChildren * @returns {*[]} */ function addChildrenLocations(targetSelect, childrenLocations, prefix, addAllChildren) { let addedChildrenLocations = []; let insertionCounter = 0; /* loop through all children locations */ childrenLocations.forEach(function (currentLocation, index, locationsArray) { targetSelect.append(''); addedChildrenLocations[insertionCounter++] = currentLocation; /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log(prefix + 'addChildrenLocations: ' + currentLocation.slug + ' in ' + targetSelect.attr('id')); } /* If a current location has children then add those as well */ if (addAllChildren && currentLocation.children.length) { let tempLocations = addChildrenLocations(targetSelect, currentLocation.children, prefix + '- ', addAllChildren); if (tempLocations.length > 0) { /* merge newly added children locations with existing children locations array */ addedChildrenLocations = $.merge(addedChildrenLocations, tempLocations); } } }); return addedChildrenLocations; } /** * Search a location from given locations array for given slug * @param slug * @param locations * @returns {boolean} location OR false if no location is found */ function searchLocation(slug, locations) { let targetLocation = false; for (let index = 0; index < locations.length; index++) { let currentLocation = locations[index]; if (currentLocation.slug === slug) { /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('searchLocation: Found'); console.log(currentLocation); } targetLocation = currentLocation; break; } if (currentLocation.children.length > 0) { targetLocation = searchLocation(slug, currentLocation.children); if (targetLocation) { break; } } } return targetLocation; } /** * Update child select box based on change in selected value of parent select box * @param event */ function updateChildSelect(event) { let selectedSlug = $(this).val(); let currentSelectIndex = selectBoxesIDs.indexOf($(this).attr('id')); /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('updateChildSelect: ' + $(this).attr('id') + ' select box is changed to ' + selectedSlug + ' slug '); } /* When "any" is selected, Also no need to run this on last select box */ if (selectedSlug === anyValue && (currentSelectIndex > -1) && (currentSelectIndex < (selectBoxesCount - 1))) { for (let s = currentSelectIndex; s < (selectBoxesCount - 1); s++) { /* check if child select is Last */ let childSelectIsLast = (selectBoxesCount === (s + 2)); /* find child select box, empty it and add any options to it */ let childSelect = $('#' + selectBoxesIDs[s + 1]); childSelect.empty(); addAnyOption(childSelect); /* loop through select options to find and add children locations into next select */ let anyChildLocations = []; $('#' + selectBoxesIDs[s] + ' > option').each(function () { if (this.value !== anyValue) { let relatedLocation = searchLocation(this.value, hierarchicalLocations); if (relatedLocation && relatedLocation.children.length > 0 ) { let tempChildrenLocations = addChildrenLocations(childSelect, relatedLocation.children, '', childSelectIsLast); if (tempChildrenLocations.length > 0) { anyChildLocations = $.merge(anyChildLocations, tempChildrenLocations); } } } }); /* enable next select if options are added otherwise disable it */ if (anyChildLocations.length > 0) { enableSelect(childSelect); } else { disableSelect(childSelect); break; } } /* end of for loop */ } else { /* In case of valid location selection */ let selectedParentLocation = searchLocation(selectedSlug, hierarchicalLocations); if (selectedParentLocation) { let childLocations = []; for (let childSelectIndex = currentSelectIndex + 1; childSelectIndex < selectBoxesCount; childSelectIndex++) { /* check if child select is Last */ let childSelectIsLast = (selectBoxesCount === (childSelectIndex + 1)); /* find and empty child select box */ let childSelect = $('#' + selectBoxesIDs[childSelectIndex]); childSelect.empty(); /* First iteration */ if (childLocations.length === 0 ) { if (selectedParentLocation.children.length > 0) { addAnyOption(childSelect); let tempLocations = addChildrenLocations(childSelect, selectedParentLocation.children, '', childSelectIsLast); if (tempLocations.length > 0) { childLocations = tempLocations; } } } else if (childLocations.length > 0) { /* 2nd and later iterations */ let currentLocations = []; for (let i = 0; i < childLocations.length; i++) { let tempChildLocation = childLocations[i]; if (tempChildLocation.children.length > 0) { addAnyOption(childSelect); let tempLocations = addChildrenLocations(childSelect, tempChildLocation.children, '', childSelectIsLast); if (tempLocations.length > 0) { currentLocations = $.merge(currentLocations, tempLocations); } } } /* If there are current locations OR none, assign current locations array to child locations*/ childLocations = currentLocations; } if (childLocations.length > 0) { enableSelect(childSelect); } else { disableSelect(childSelect); break; } } /* end of for loop */ } else { /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('updateChildSelect: Not Found ' + selectedSlug + ' slug in hierarchicalLocations!'); console.log(hierarchicalLocations); } } } } /** * Adds Any value and select index based place holder text to given select box. * @param targetSelect */ function addAnyOption(targetSelect) { if (targetSelect.has('option').length > 0){ return; } let targetSelectIndex = selectBoxesIDs.indexOf(targetSelect.attr('id')); /* current select box index */ /* For location fields in search form */ if (targetSelect.parents('.rh_prop_search__select').hasClass('rh_location_prop_search_' + targetSelectIndex)) { let targetSelectPlaceholder = targetSelect.parents('.rh_prop_search__select').data('get-location-placeholder'); targetSelect.append(''); /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('addAnyOption: to select box: ' + targetSelect.attr('id')); } /* For location fields in dashboard property form */ } else if (targetSelect.parents('.rh_prop_loc__select').hasClass('rh_location_prop_loc_' + targetSelectIndex)) { targetSelect.append(''); /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('addAnyOption: to select box: ' + targetSelect.attr('id')); } } } /** * Disable a select box and next select boxes if exists * @param targetSelect */ function disableSelect(targetSelect) { let targetSelectID = targetSelect.attr('id'); /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('disableSelect: ' + targetSelectID); } targetSelect.empty(); targetSelect.closest('.option-bar').addClass('disabled'); if (targetSelect.is(':enabled')) { targetSelect.prop('disabled', true); targetSelect.parents('.rh_prop_search__select').addClass('rh_disable_parent'); } let targetSelectIndex = selectBoxesIDs.indexOf(targetSelectID); // target select box index let nextSelectBoxesCount = selectBoxesCount - (targetSelectIndex + 1); /* Disable next select box as well */ if (nextSelectBoxesCount > 0) { let nextSelect = $('#' + selectBoxesIDs[targetSelectIndex + 1]); disableSelect(nextSelect); } } /** * Enable a select box * @param targetSelect */ function enableSelect(targetSelect) { let targetSelectID = targetSelect.attr('id'); /* logging while development OR troubleshooting */ if (consoleLogEnabled) { console.log('enableSelect: ' + targetSelectID); } if (targetSelect.is(':disabled')) { targetSelect.prop('disabled', false); } // remove class from parents targetSelect.parents('.rh_prop_search__select').map(function (){ if( $(this).hasClass('rh_disable_parent')){ $(this).removeClass('rh_disable_parent'); } }); /* Remove .option-bar's disabled class */ let optionWrapper = targetSelect.closest('.option-bar'); if (optionWrapper.hasClass('disabled')) { optionWrapper.removeClass('disabled'); // todo: remove the following line after testing //optionWrapper.parents('.rh_prop_search__select').removeClass('rh_disable_parent'); } // for classic property submit/edit form's locations fields // targetSelect.siblings('.btn').removeClass('disabled'); /* Remove .bootstrap-select disabled class - especially for classic */ // let bootstrapSelect = targetSelect.closest('.bootstrap-select'); // if (bootstrapSelect.hasClass('disabled')) { // bootstrapSelect.removeClass('disabled'); // } } /** * Mark the current value in query params as selected in related select box * @param currentSelect */ function selectParamOption(currentSelect) { if (Object.keys(slugsInQueryParams).length > 0) { let selectName = currentSelect.attr('name'); selectName = selectName.replace(/[\[\]]+/g,''); /* remove box brackets as for multi select location brackets comes with name */ if (typeof slugsInQueryParams[selectName] !== 'undefined') { let tempValue = slugsInQueryParams[selectName]; if (Array.isArray(tempValue)){ for (let i = 0; i < tempValue.length; i++) { currentSelect.find('option[value="' + tempValue[i] + '"]').prop('selected', true); } } else { currentSelect.find('option[value="' + tempValue + '"]').prop('selected', true); } } } } /** * Append options with Any value or None value depending on conditions */ function prepareSelectBoxes(){ /* Loop through select boxes and prepare them with basic option */ for (let selectIndex = 0; selectIndex < selectBoxesCount; selectIndex++) { let currentSelectId = selectBoxesIDs[selectIndex]; let currentSelect = $('#' + currentSelectId); /* For location fields in search form */ if ((multiSelect === 'no') && (currentSelect.has('option').length === 0) && (currentSelect.parents('.rh_prop_search__select').hasClass('rh_location_prop_search_' + selectIndex))) { if(consoleLogEnabled){ console.log('prepareSelectBoxes 1st if: ' + currentSelectId); } addAnyOption(currentSelect); } /* For location fields in dashboard property form */ if ((currentSelect.has('option').length === 0) && (currentSelect.parents('.rh_prop_loc__select').hasClass('rh_location_prop_loc_' + selectIndex))) { if(consoleLogEnabled){ console.log('prepareSelectBoxes 2nd if: ' + currentSelectId); } addAnyOption(currentSelect); } } } } /* ----------- END OF LOCATIONS SELECT BOXES CODE ----------- */ })(jQuery);; (function ($) { "use strict"; /** * Initializes the similar properties filters. * * @since 3.13 */ function similarPropertiesFilters() { const similarPropertiesFiltersWrap = $( '#similar-properties-filters-wrapper' ); if ( similarPropertiesFiltersWrap.length ) { const similarPropertiesFilters = similarPropertiesFiltersWrap.find( 'a' ), similarPropertiesWrapper = $( '#similar-properties-wrapper' ), similarProperties = $( '#similar-properties' ), similarPropertiesHtml = similarProperties.html(), similarNonce = similarPropertiesFiltersWrap.data( 'similar-properties-request-nonce' ); // Check for localized similar properties data if ( typeof similarPropertiesData !== "undefined" ) { const design = similarPropertiesData.design; let buttonClass = 'rh-btn rh-btn-primary'; let buttonClassCurrent = 'rh-btn rh-btn-secondary'; if ( 'classic' === design ) { buttonClass = ''; buttonClassCurrent = 'current'; } similarPropertiesFiltersWrap.on( 'click', 'a', function ( event ) { event.preventDefault(); const self = $( this ); const propertyFilter = self.data( 'similar-properties-filter' ); // Update UI for the selected filter button similarPropertiesFilters.removeClass( buttonClassCurrent ).addClass( buttonClass ); self.removeClass( buttonClass ).addClass( buttonClassCurrent ); // Handle recommended properties (no AJAX required) if ( 'recommended' === propertyFilter ) { similarProperties.html( similarPropertiesHtml ); return; } // Make AJAX request to filter similar properties $.ajax( { url : ajaxurl, type : 'post', dataType : 'json', // Expect JSON response data : { action : 'realhomes_filter_similar_properties', property_id : similarPropertiesData.propertyId, properties_per_page : similarPropertiesData.propertiesPerPage, property_filter : propertyFilter, design : design, nonce : similarNonce }, beforeSend : function () { similarPropertiesWrapper.addClass( 'loading' ); }, success : function ( response ) { similarPropertiesWrapper.removeClass( 'loading' ); if ( response.success ) { similarProperties.html( response.data ); } else { console.warn( response.data.message || 'An unknown error occurred.' ); similarProperties.html( '
' + ( response.data.message || 'An error occurred while fetching similar properties.' ) + '
' ); } }, error : function ( jqXHR, textStatus, errorThrown ) { // Remove loading state similarPropertiesWrapper.removeClass( 'loading' ); // Handle HTTP errors (e.g., 404, 500, timeout) console.error( 'AJAX Error:', textStatus, errorThrown ); similarProperties.html( '
An error occurred while loading similar properties. Please try again later.
' ); } } ); } ); } else { // Hide filters when no data available similarPropertiesFiltersWrap.hide(); } } } /** * Adds css class in body to stack the floating features div if the property agent sticky bar exists in DOM. * * @since 3.14 */ function agentStickyBarHandler() { const agentStickyBar = $('#property-agent-contact-methods-wrapper'); if (767 > $(window).width() && agentStickyBar.length) { $('body').addClass('has-agent-sticky-bar'); } } $(document).ready(function () { // Elementor Based Membership Packages Page let getStarted = document.querySelectorAll( '#membership-plans' ); if ( typeof getStarted !== 'undefined' ) { let loginModel = $( 'body' ).find( '.rh_login_modal_wrapper' ); let membershipPage = dashboardData.membershipPage; let redirectTo = document.querySelector( '.rh_login_modal_wrapper input[name="redirect_to"]' ); if ( ! loginModel.length && typeof membershipPage !== 'undefined' ) { getStarted.forEach( function ( link ) { link.setAttribute( 'href', membershipPage + '&submodule=checkout&package_id=' + link.getAttribute( "href" ).replace( '#', '' ) ); } ) } else { getStarted.forEach( function ( link ) { link.addEventListener( 'click', function () { if ( loginModel.length ) { redirectTo.setAttribute( 'value', membershipPage + '&submodule=checkout&package_id=' + link.getAttribute( "href" ).replace( '#', '' ) ); } } ) } ); } } // End of Membership Packages var $window = $(window), $body = $('body'), isRtl = $body.hasClass('rtl'); similarPropertiesFilters(); agentStickyBarHandler(); // TODO: need to find a way to run this code only on property single page. $window.on('resize', function () { agentStickyBarHandler(); }); // Stop propagation of click event on favorites button when user is not logged in. $('.add-favorites-without-login, .save-search-without-login').on('click', function (event) { event.stopPropagation(); }); /*-----------------------------------------------------------------*/ /* Save Searches for Email Alerts /*-----------------------------------------------------------------*/ $('#rh_save_search_btn').on('click', function (e) { e.preventDefault(); let button = $(this); let $form = button.closest('form'); let searchArguments = $form.find('.rh_wp_query_args').val(); let searchURL = $form.find('.rh_url_query_str').val(); let icon = button.find('i'); let savedLabel = button.data('saved-label'); icon.addClass('fa-spin'); if (button.hasClass('require-login')) { // Prepare new alert object to store in local storage. let currentTime = $form.find('.rh_current_time').val(); let newSavedSearch = { 'wp_query_args': searchArguments, 'query_str': searchURL, 'time': currentTime }; // Add new alert to the local storage. var oldSavedSearches = window.localStorage.getItem('realhomes_saved_searches'); if (oldSavedSearches) { allSavedSearches = JSON.parse(oldSavedSearches); allSavedSearches.push(newSavedSearch); window.localStorage.setItem('realhomes_saved_searches', JSON.stringify(allSavedSearches)); } else { window.localStorage.setItem('realhomes_saved_searches', JSON.stringify([newSavedSearch])); } // Update the save alert button. button.addClass('search-saved'); icon.removeClass('fa-spin'); button.html('' + savedLabel); // Open the login/register dialoage box. var loginModel = $('body').find('.rh_login_modal_wrapper'); if (loginModel.length) { $('.rh_login_modal_wrapper').css("display", "flex").hide().fadeIn(500); } else { window.location = button.data('login'); } } else { let nonce = $form.find('.rh_save_search_nonce').val(); $.post(ajaxurl, { nonce: nonce, action: 'inspiry_save_search', search_args: searchArguments, search_url: searchURL, }, function (response) { response = JSON.parse(response); if (response.success) { // Update the save search button. button.addClass('search-saved'); icon.removeClass('fa-spin'); button.html('' + savedLabel); } } ); } }); /* * Migrate saved searches from local to server. */ var allSavedSearches = JSON.parse(window.localStorage.getItem('realhomes_saved_searches')); if (allSavedSearches && $('body').hasClass('logged-in')) { var migrateSavedSearches = { type: 'post', url: ajaxurl, data: { action: 'realhomes_saved_searches_migration', saved_searches: allSavedSearches, }, success: function (response) { if ('true' === response) { // Clear all saved searches from local storage. window.localStorage.removeItem('realhomes_saved_searches'); } } }; $.ajax(migrateSavedSearches); } /*-----------------------------------------------------------------*/ /* Mortgage Calculator /*-----------------------------------------------------------------*/ if ($('.rh_property__mc_wrap').length) { let mc_reassign_fields = function ($this = null) { if ('object' === typeof $this && typeof $this.closest('.rh_property__mc')) { $this = $this.closest('.rh_property__mc'); mcState.fields = { 'term': $this.find('select.mc_term'), 'interest_text': $this.find('.mc_interset'), 'interest_slider': $this.find('.mc_interset_slider'), 'price_text': $this.find('.mc_home_price'), 'price_slider': $this.find('.mc_home_price_slider'), 'downpayment_text': $this.find('.mc_downpayment'), 'downpayment_text_p': $this.find('.mc_downpayment_percent'), 'downpayment_slider': $this.find('.mc_downpayment_slider'), 'tax': $this.find('.mc_cost_tax_value'), 'hoa': $this.find('.mc_cost_hoa_value'), 'currency_sign': $this.find('.mc_currency_sign'), 'sign_position': $this.find('.mc_sign_position'), 'info_term': $this.find('.mc_term_value'), 'info_interest': $this.find('.mc_interest_value'), 'info_cost_interst': $this.find('.mc_cost_interest span'), 'info_cost_total': $this.find('.mc_cost_total span'), 'graph_interest': $this.find('.mc_graph_interest'), 'graph_tax': $this.find('.mc_graph_tax'), 'graph_hoa': $this.find('.mc_graph_hoa'), } if ($('.mc_cost_over_graph').length > 0) { mcState.fields.info_cost_total = $this.find('.mc_cost_over_graph'); } } } let mc_only_numeric = function (data) { if ('string' === typeof data) { return (data.replace(/[^0-9-.]/g, '')).replace(/^\./, ''); // leave only numeric value. } return data; } let mc_input_focus = function () { $(this).val(mc_only_numeric($(this).val())); // leave only numeric value. } let mc_input_blur = function () { // percentage value. mcState.fields.interest_text.val(mc_only_numeric(mcState.fields.interest_text.val()) + '%'); mcState.fields.downpayment_text_p.val(mc_only_numeric(mcState.fields.downpayment_text_p.val()) + '%'); // formatted amount value. mcState.fields.price_text.val(mc_format_amount(mcState.fields.price_text.val())); mcState.fields.downpayment_text.val(mc_format_amount(mcState.fields.downpayment_text.val())); } let mc_format_amount = function (amount) { if ('after' === mcState.values.sign_position) { return new Intl.NumberFormat('en-us').format(mc_only_numeric(amount)) + mcState.values.currency_sign; } return mcState.values.currency_sign + new Intl.NumberFormat('en-us').format(mc_only_numeric(amount)); } let mc_update_fields_values = function () { const $this = $(this); mc_reassign_fields($this); mcState.values = mc_get_input_values(); // get all input values to be used for the calculation. if ('range' === $this.attr('type')) { if ($this.hasClass('mc_interset_slider')) { // Interest slider changed. mcState.fields.interest_text.val($this.val() + '%'); // update interest percentage text field value. } else if ($this.hasClass('mc_home_price_slider')) { // Price slider changed. mcState.fields.price_text.val(mc_format_amount($this.val())); // update price text field value. // update downpayment amount text field value according to the selected percentage. let home_price = $this.val(); let dp_percent = mcState.values.downpayment_percent; let downpayment = Math.round((home_price * dp_percent) / 100); mcState.fields.downpayment_text.val(mc_format_amount(downpayment)); } else if ($this.hasClass('mc_downpayment_slider')) { // Downpayment slider. mcState.fields.downpayment_text_p.val($this.val() + '%'); let home_price = mcState.values.price; let dp_percent = $this.val(); let downpayment = Math.round((home_price * dp_percent) / 100); mcState.fields.downpayment_text.val(mc_format_amount(downpayment)); } } else if ('text' === $this.attr('type')) { if ($this.hasClass('mc_interset')) { mcState.fields.interest_slider.val(mcState.values.interest); } else if ($this.hasClass('mc_home_price')) { mcState.fields.price_slider.val(mcState.values.price); let home_price = mcState.values.price; let dp_percent = mcState.values.downpayment_percent; let downpayment = Math.round((home_price * dp_percent) / 100); mcState.fields.downpayment_text.val(mc_format_amount(downpayment)); } else if ($this.hasClass('mc_downpayment_percent')) { mcState.fields.downpayment_slider.val(mcState.values.downpayment_percent); let home_price = mcState.values.price; let dp_percent = mcState.values.downpayment_percent; let downpayment = (home_price * dp_percent) / 100; mcState.fields.downpayment_text.val(mc_format_amount(downpayment)); } else if ($this.hasClass('mc_downpayment')) { let home_price = mcState.values.price; let downpayment = mcState.values.downpayment; let price = (home_price < downpayment) ? downpayment : home_price; let dp_percent = ((downpayment * 100) / price).toFixed(2).replace(/[.,]00$/, ""); mcState.fields.downpayment_text_p.val(dp_percent + '%'); mcState.fields.downpayment_slider.val(dp_percent); } } mc_calculate(); } let mc_get_input_values = function () { let interest = mc_only_numeric(mcState.fields.interest_text.val()); let price = mc_only_numeric(mcState.fields.price_text.val()); let downpayment = mc_only_numeric(mcState.fields.downpayment_text.val()); let downpayment_percent = mc_only_numeric(mcState.fields.downpayment_text_p.val()); let tax = mc_only_numeric(mcState.fields.tax.val()); let hoa = mc_only_numeric(mcState.fields.hoa.val()); let currency_sign = mcState.fields.currency_sign.val(); let sign_position = mcState.fields.sign_position.val(); let mcInputVals = { term: parseInt(mcState.fields.term.val()), interest: ('' === interest.replace('-', '')) ? 0 : parseFloat(interest), price: ('' === price.replace('-', '')) ? 0 : parseFloat(price), downpayment: ('' === downpayment.replace('-', '')) ? 0 : parseFloat(downpayment), downpayment_percent: ('' === downpayment_percent.replace('-', '')) ? 0 : parseFloat(downpayment_percent), tax: ('' === tax.replace('-', '')) ? 0 : parseFloat(tax), hoa: ('' === hoa.replace('-', '')) ? 0 : parseFloat(hoa), currency_sign: ('' === currency_sign) ? '$' : currency_sign, sign_position: ('' === sign_position) ? 'before' : sign_position, }; return mcInputVals; } let mc_get_principle_interest = function () { let home_price = parseFloat(mcState.values.price); let downpayment = parseFloat(mcState.values.downpayment); let loanBorrow = home_price - downpayment; let totalTerms = 12 * mcState.values.term; if (0 === parseInt(mcState.values.interest)) { return loanBorrow / totalTerms; } let interestRate = parseFloat(mcState.values.interest) / 1200; return Math.round(loanBorrow * interestRate / (1 - (Math.pow(1 / (1 + interestRate), totalTerms)))); } let mc_get_payment_per_month = function () { let principal_interest = parseFloat(mcState.princial_interest); let property_tax = parseFloat(mcState.values.tax); let hoa_dues = parseFloat(mcState.values.hoa); return Math.round(principal_interest + property_tax + hoa_dues); } let mc_get_data_percentage = function () { let principal_interest = mcState.princial_interest; let property_tax = mcState.values.tax; let hoa_dues = mcState.values.hoa; let p_i = (principal_interest * 100) / mcState.payment_per_month; let tax = (property_tax * 100) / mcState.payment_per_month; let hoa = (hoa_dues * 100) / mcState.payment_per_month; let data_percentage = { p_i, tax, hoa }; return data_percentage; } let mc_render_information = function () { // Update calculated information. mcState.fields.info_term.text(mcState.values.term); mcState.fields.info_interest.text(mcState.values.interest); mcState.fields.info_cost_interst.text(mc_format_amount(Math.round(mcState.princial_interest))); if ($('.mc_cost_over_graph').length > 0) { // Update circle graph and total cost. let cost_prefix = mcState.fields.info_cost_total.attr('data-cost-prefix'); mcState.fields.info_cost_total.html('' + mc_format_amount(mcState.payment_per_month) + '' + cost_prefix); var $circle = mcState.fields.graph_interest; var circle_pct = mcState.percentage.p_i; var r = $circle.attr('r'); var c = Math.PI * (r * 2); if (circle_pct < 0) { circle_pct = 0; } if (circle_pct > 100) { circle_pct = 100; } var pct = ((100 - circle_pct) / 100) * c; $circle.css({strokeDashoffset: pct}); var $circle = mcState.fields.graph_tax; var circle_pct = mcState.percentage.tax + mcState.percentage.p_i; var r = $circle.attr('r'); var c = Math.PI * (r * 2); if (circle_pct < 0) { circle_pct = 0; } if (circle_pct > 100) { circle_pct = 100; } var pct = ((100 - circle_pct) / 100) * c; $circle.css({strokeDashoffset: pct}); var $circle = mcState.fields.graph_hoa; var circle_pct = mcState.percentage.hoa + mcState.percentage.tax + mcState.percentage.p_i; var r = $circle.attr('r'); var c = Math.PI * (r * 2); if (circle_pct < 0) { circle_pct = 0; } if (circle_pct > 100) { circle_pct = 100; } var pct = ((100 - circle_pct) / 100) * c; $circle.css({strokeDashoffset: pct}); } else { // Update bar graph and total cost. mcState.fields.info_cost_total.text(mc_format_amount(mcState.payment_per_month)); mcState.fields.graph_interest.css('width', (mcState.percentage.p_i) + '%'); mcState.fields.graph_tax.css('width', (mcState.percentage.tax) + '%'); mcState.fields.graph_hoa.css('width', (mcState.percentage.hoa) + '%'); } } let mc_calculate = function () { mcState.values = mc_get_input_values(); // get all input vaues to be used for the calculation. mcState.princial_interest = mc_get_principle_interest(); // caclcualte and get the principle and interest amount. mcState.payment_per_month = mc_get_payment_per_month(); // calculate and get the per month payment to be paid. mcState.percentage = mc_get_data_percentage(); // calculate and get the percentages of the data for the graph display. mc_render_information(); // Display the information on frontend side. } const mcState = {}; mcState.fields = { 'term': $('select.mc_term'), 'interest_text': $('.mc_interset'), 'interest_slider': $('.mc_interset_slider'), 'price_text': $('.mc_home_price'), 'price_slider': $('.mc_home_price_slider'), 'downpayment_text': $('.mc_downpayment'), 'downpayment_text_p': $('.mc_downpayment_percent'), 'downpayment_slider': $('.mc_downpayment_slider'), 'tax': $('.mc_cost_tax_value'), 'hoa': $('.mc_cost_hoa_value'), 'currency_sign': $('.mc_currency_sign'), 'sign_position': $('.mc_sign_position'), 'info_term': $('.mc_term_value'), 'info_interest': $('.mc_interest_value'), 'info_cost_interst': $('.mc_cost_interest span'), 'info_cost_total': $('.mc_cost_total span'), 'graph_interest': $('.mc_graph_interest'), 'graph_tax': $('.mc_graph_tax'), 'graph_hoa': $('.mc_graph_hoa'), } if ($('.mc_cost_over_graph').length > 0) { mcState.fields.info_cost_total = $('.mc_cost_over_graph'); } mc_calculate(); // Initiate Mortgage Calculator. mc_input_blur(); // Format the amounts in the text fields. // Apply calculation action on calculator values change. $('.rh_mc_field select, .rh_mc_field input[type=range]').on('change', mc_update_fields_values); $('.rh_mc_field input[type=range]').on('input', mc_update_fields_values); $('.rh_mc_field input[type=text]').on('keyup', mc_update_fields_values); // Add focus and blur actions on text input fields. $('.rh_mc_field input[type=text]').on('focus', mc_input_focus); $('.rh_mc_field input[type=text]').on('blur', mc_input_blur); } /*-----------------------------------------------------------------------------------*/ /* Language Switcher /*-----------------------------------------------------------------------------------*/ $body.on( 'click', '.inspiry-language', function ( e ) { if ( $( '.inspiry-language-switcher' ) .find( '.rh_languages_available' ) .children( '.inspiry-language' ).length > 0 ) { const wrapper_language_switcher = $( '.rh_wrapper_language_switcher' ); wrapper_language_switcher.toggleClass( 'parent_open' ); if ( wrapper_language_switcher.hasClass( 'parent_open' ) ) { $( this ).addClass( 'open' ); $( '.rh_languages_available' ).fadeIn( 200 ); } else { $( this ).removeClass( 'open' ); $( '.rh_languages_available' ).fadeOut( 200 ); } } e.stopPropagation(); } ); $('html').on('click', function () { $('.rh_wrapper_language_switcher').removeClass('parent_open'); $('html .inspiry-language').removeClass('open'); $('.rh_languages_available').fadeOut(200); }); /*-----------------------------------------------------------------------------------*/ /* Partners Carousel /*-----------------------------------------------------------------------------------*/ if (jQuery().owlCarousel) { $('.brands-owl-carousel').owlCarousel({ nav: true, dots: false, navText: ['', ''], loop: true, autoplay: true, autoplayTimeout: 4500, autoplayHoverPause: true, margin: 0, rtl: isRtl, responsive: { 0: { items: 1 }, 480: { items: 2 }, 768: { items: 3 }, 992: { items: 4 }, 1199: { items: 5 } } }); } /*-----------------------------------------------------------------------------------*/ /* Agent form's validation script for property detail page. /*-----------------------------------------------------------------------------------*/ function inspiryValidateForm(form) { var $form = $(form), submitButton = $form.find('.submit-button'), ajaxLoader = $form.find('.ajax-loader'), messageContainer = $form.find('.message-container'), errorContainer = $form.find(".error-container"), formOptions = { beforeSubmit: function () { submitButton.attr('disabled', 'disabled'); ajaxLoader.fadeIn('fast').css("display", "inline-block"); messageContainer.fadeOut('fast'); errorContainer.fadeOut('fast'); }, success: function (ajax_response, statusText, xhr, $form) { var response = $.parseJSON(ajax_response); ajaxLoader.fadeOut('fast'); submitButton.removeAttr('disabled'); if (response.success) { $form.resetForm(); messageContainer.html(response.message).fadeIn('fast'); // call reset function if it exists if (typeof inspiryResetReCAPTCHA == 'function') { inspiryResetReCAPTCHA(); } if (typeof agentData !== 'undefined') { setTimeout(function () { window.location.replace(agentData.redirectPageUrl); }, 1000); } else { setTimeout(function () { messageContainer.fadeOut('slow') }, 3000); } } else { errorContainer.html(response.message).fadeIn('fast'); } } }; $form.validate({ errorLabelContainer: errorContainer, submitHandler: function (form) { $(form).ajaxSubmit(formOptions); } }); } if (jQuery().validate && jQuery().ajaxSubmit) { if ($body.hasClass('single-property')) { var getAgentForms = $('.agent-form'); if (getAgentForms.length) { $.each(getAgentForms, function (i, form) { var id = $(form).attr("id"); inspiryValidateForm('#' + id); }); } } } /*-----------------------------------------------------------------------------------*/ /* Login Required Function /*-----------------------------------------------------------------------------------*/ $('body').on('click', '.inspiry_submit_login_required', function (e) { e.preventDefault(); $('.rh_login_modal_wrapper').css("display", "flex").hide().fadeIn(500); }); /*-----------------------------------------------------------------------------------*/ /* Report property modal script. /*-----------------------------------------------------------------------------------*/ if ($body.hasClass('single-property')) { const reportThisProperty = $( '.report-this-property' ); if ( reportThisProperty.length ) { reportThisProperty.on('click', null,function (event) { // Target model id let targetModelID = $(this).attr('href'); let reportPropertyModal = $(targetModelID); if (reportPropertyModal.length) { const reportPropertyForm = $("#report-property-form"), ajaxLoader = reportPropertyForm.find(".ajax-loader"), submitButton = reportPropertyForm.find("#btn-submit"), responseContainer = reportPropertyForm.find('#response-container'), errorContainer = reportPropertyForm.find('#error-container'), mainOptionsContainer = reportPropertyForm.find("#report-property-form-main-options"), childOptionsContainer = reportPropertyForm.find("#report-property-form-child-options"), customMessage = reportPropertyForm.find("#feedback-custom-message"), backButton = reportPropertyForm.find("#btn-back"); reportPropertyModal.css("display", "flex").hide().fadeIn(250).addClass("show"); reportPropertyModal.find(".btn-close").on('click', function (event) { reportPropertyModal.removeClass("show").fadeOut(250, function() { reportPropertyModal.removeClass("has-response"); responseContainer.addClass("hide"); responseContainer.find(".response-title").html(''); responseContainer.find(".response-text").html(''); backButton.trigger("click"); reportPropertyForm.resetForm(); }); event.preventDefault(); }); reportPropertyForm.find("#feedback-option-custom-parent-item").on('click', function (event) { mainOptionsContainer.addClass("hide"); childOptionsContainer.removeClass("hide") backButton.removeClass("hide"); errorContainer.hide(); }); reportPropertyForm.find("#feedback-child-option-custom-child-item").on('change', function (event) { if ($(this).is(":checked")) { customMessage.removeClass("hide"); } else { customMessage.addClass("hide").removeClass('error'); errorContainer.hide(); } }); backButton.on('click', function (event) { $(this).addClass("hide"); reportPropertyForm.find("input[type='radio']").prop("checked", false); reportPropertyForm.find("input[type='checkbox']").prop("checked", false); childOptionsContainer.addClass("hide"); mainOptionsContainer.removeClass("hide"); customMessage.addClass("hide").removeClass('error'); errorContainer.hide(); }); if (jQuery().validate && jQuery().ajaxSubmit) { reportPropertyForm.validate({ rules: { "feedback-option": { required: true }, "feedback-child-options[]": { required: "#feedback-option-custom-parent-item:checked" }, "feedback-custom-message": { required: "#feedback-child-option-custom-child-item:checked" }, }, errorLabelContainer: errorContainer, submitHandler: function (form) { reportPropertyForm.ajaxSubmit({ beforeSubmit: function () { ajaxLoader.fadeIn("fast").css("display", "inline-block"); submitButton.attr("disabled", "disabled"); backButton.addClass("hide"); responseContainer.addClass("hide"); reportPropertyModal.removeClass("has-response") errorContainer.fadeOut(250); }, success: function (ajax_response, statusText, xhr, form) { const response = $.parseJSON(ajax_response); ajaxLoader.fadeOut("fast"); submitButton.removeAttr("disabled"); backButton.removeClass("hide"); reportPropertyModal.addClass("has-response"); responseContainer.removeClass("hide").fadeIn("fast"); responseContainer.find(".response-title").html(response.title); responseContainer.find(".response-text").html(response.message); if (response.success) { reportPropertyForm.resetForm(); } } }); } }); } } event.preventDefault(); }); } } /*-----------------------------------------------------------------------------------*/ /* BootStrap Select /*-----------------------------------------------------------------------------------*/ window.inspirySelectPicker = function (id) { if (jQuery().selectpicker) { jQuery(id).selectpicker({ iconBase: 'fas', width: "100%", size: 5, tickIcon: 'fa-check', selectAllText: '' + '' + '', deselectAllText: '', }); $(".rh_sort_controls .inspiry_select_picker_trigger").click(function (e) { if (!$(this).hasClass('open')) { $(this).addClass('open'); e.stopPropagation(); } else { $(this).removeClass('open'); e.stopPropagation(); } }); } }; // TODO: This commented code should be removed if it is not needed. // if ($('.dsidx-resp-search-form')) { // $('.dsidx-resp-search-form select').addClass('inspiry_select_picker_trigger inspiry_bs_default_mod inspiry_bs_green show-tick'); // // if ($('.dsidx-sorting-control')) { // $('.dsidx-sorting-control select').addClass('inspiry_select_picker_trigger inspiry_bs_default_mod inspiry_bs_green show-tick'); // } // if ($('#dsidx-search-form-main')) { // $('#dsidx-search-form-main select').addClass('inspiry_select_picker_trigger inspiry_bs_default_mod inspiry_bs_green show-tick'); // } // if ($('#dsidx.dsidx-details')) { // $('.dsidx-contact-form-schedule-date-row select').addClass('inspiry_select_picker_trigger inspiry_bs_default_mod inspiry_bs_green show-tick'); // } // // inspirySelectPicker('body .inspiry_select_picker_trigger'); // } inspirySelectPicker('body .inspiry_select_picker_trigger'); inspirySelectPicker('body .widget_categories select'); inspirySelectPicker('body .widget_archive select'); // TODO: Remove this if it is not required. // inspirySelectPicker('.inspiry_select_picker_mod'); $(".inspiry_multi_select_picker_location").on('change', function (e, clickedIndex, isSelected, previousValue) { setTimeout(function () { $('.inspiry_multi_select_picker_location').selectpicker('refresh'); }, 500); }); $(".inspiry_bs_submit_location").on('changed.bs.select', function () { $('.inspiry_bs_submit_location').selectpicker('refresh'); }); $(".inspiry_select_picker_status").on('changed.bs.select', function () { $('.inspiry_select_picker_price').selectpicker('refresh'); }); $('.inspiry_select_picker_trigger').on('show.bs.select', function () { $(this).parents('.rh_prop_search__option').addClass('inspiry_bs_is_open') }); $('.inspiry_select_picker_trigger').on('hide.bs.select', function () { $(this).parents('.rh_prop_search__option').removeClass('inspiry_bs_is_open') }); var locationSuccessList = function (data, thisParent, refreshList = false) { if (true === refreshList) { thisParent.find('option').not(':selected, .none').remove().end(); } var getSelected = $(thisParent).val(); jQuery.each(data, function (index, text) { if (getSelected) { if (getSelected.indexOf(text[0]) < 0) { thisParent.append( $('') ); } } else { thisParent.append( $('') ); } }); thisParent.selectpicker('refresh'); $(parent).find('ul.dropdown-menu li:first-of-type a').focus(); $(parent).find('input').focus(); }; var loaderFadeIn = function () { $('.rh-location-ajax-loader').fadeIn('fast'); }; var loaderFadeOut = function () { $('.rh-location-ajax-loader').fadeOut('fast'); }; var rhTriggerAjaxOnLoad = function (thisParent, fieldValue = '') { $.ajax({ url: localizeSelect.ajax_url, dataType: 'json', delay: 250, // delay in ms while typing when to perform a AJAX search data: { action: 'inspiry_get_location_options', // AJAX action for admin-ajax.php query: fieldValue, // TODO: review the commented code below and remove if it is not required. // hideemptyfields: localizeSelect.hide_empty_locations, // sortplpha: localizeSelect.sort_location, }, beforeSend: loaderFadeIn(), success: function (data) { loaderFadeOut(); locationSuccessList(data, thisParent, true); } }); }; var rhTriggerAjaxOnScroll = function (thisParent, farmControl, fieldValue = '') { var paged = 2; farmControl.on('keyup', function (e) { paged = 2; fieldValue = $(this).val(); }); $('div.inspiry_ajax_location_field div.inner').on('scroll', function () { var thisInner = $(this); var thisInnerHeight = thisInner.innerHeight(); var getScrollIndex = thisInner.scrollTop() + thisInnerHeight; if (getScrollIndex >= $(this)[0].scrollHeight) { $.ajax({ url: localizeSelect.ajax_url, dataType: 'json', delay: 250, // delay in ms while typing when to perform a AJAX search data: { action: 'inspiry_get_location_options', // AJAX action for admin-ajax.php query: fieldValue, page: paged, // TODO: review the commented code below and remove if it is not required. // hideemptyfields: localizeSelect.hide_empty_locations, // sortplpha: localizeSelect.sort_location, }, beforeSend: loaderFadeIn(), success: function (data) { loaderFadeOut(); if (!$.trim(data)) { $('.rh-location-ajax-loader').fadeTo("fast", 0); } paged++; locationSuccessList(data, thisParent, false); } }); } }); }; var inspiryAjaxSelect = function (parent, id) { var farmControl = $(parent).find('.form-control'); var thisParent = $(id); rhTriggerAjaxOnScroll(thisParent, farmControl); rhTriggerAjaxOnLoad(thisParent); farmControl.on('keyup', function (e) { var fieldValue = $(this).val(); fieldValue = fieldValue.trim(); var wordcounts = jQuery.trim(fieldValue).length; // TODO: review the commented code below and remove if it is not required. // rhTriggerAjaxLoadMore(thisParent,fieldValue); $('.rh-location-ajax-loader').fadeTo("fast", 1); if (wordcounts > 0) { $.ajax({ url: localizeSelect.ajax_url, dataType: 'json', delay: 250, // delay in ms while typing when to perform a AJAX search data: { action: 'inspiry_get_location_options', // AJAX action for admin-ajax.php query: fieldValue, // TODO: review the commented code below and remove if it is not required. // hideemptyfields: localizeSelect.hide_empty_locations, // sortplpha: localizeSelect.sort_location, }, beforeSend: loaderFadeIn(), success: function (data) { loaderFadeOut(); thisParent.find('option').not(':selected, .none').remove().end(); // TODO: review the commented code below and remove if it is not required. // var options = []; if (fieldValue && data) { locationSuccessList(data, thisParent); } else { thisParent.find('option').not(':selected, .none').remove().end(); thisParent.selectpicker('refresh'); $(parent).find('ul.dropdown-menu li:first-of-type a').focus(); $(parent).find('input').focus(); } }, }); // TODO: review the commented code below and remove if it is not required. // rhTriggerAjaxLoadMore(thisParent,fieldValue); } else { rhTriggerAjaxOnLoad(thisParent); } }); }; inspiryAjaxSelect('.inspiry_ajax_location_wrapper', 'select.inspiry_ajax_location_field'); // Show on document ready to avoid glitching screen $('.rhea_long_screen_header_temp').removeClass('rhea-hide-before-load'); $('.rh_apply_sticky_wrapper_footer').removeClass('rhea-hide-before-load'); $('.rh-custom-search-form-wrapper').removeClass('rhea-hide-before-load'); $('.ere-custom-search-form-wrapper').removeClass('rhea-hide-before-load'); $('div').removeClass('rh-hide-before-ready'); }); //Remove class that hide elements before load to avoid glitching screen $(window).on('load',function () { $('div').removeClass('rh-hide-before-load'); }); window.rhUltraTooltip = function(selector) { $(selector).tooltip({ classes: { "ui-tooltip": "rh-ultra-tooltip" }, position: { my: "center bottom-10", at: "center top", using: function( position, feedback ) { $( this ).css( position ); $( "
" ) .addClass( "arrow" ) .addClass( feedback.vertical ) .addClass( feedback.horizontal ) .appendTo( this ); } } }); } $(document).on('ready', function () { $('.inspiry_show_on_doc_ready').show(); rhUltraTooltip('.rh-ui-tooltip'); //jQuery UI tooltip }); /** * Compare property template sticky table head script * Uses Sticky-kit plugin * URL: https://github.com/leafo/sticky-kit * * @since 4.1.1 */ function comparePropertyStickyHead() { const compareHead = $( '.sticky-compare-head, .sticky-head-smart' ); if ( ! compareHead.length ) { return false; } let screenWidth = $( window ).width(); if ( 1024 <= screenWidth ) { const $body = $( 'body' ); let offsetTop = 0; if ( $body.hasClass( 'admin-bar' ) ) { offsetTop += 32; } compareHead.stick_in_parent( { offset_top : offsetTop } ) } else { compareHead.trigger( "sticky_kit:detach" ); } } // Scripts to run on window load and resize events. $(window).on( 'load resize', function () { comparePropertyStickyHead(); } ); /*-----------------------------------------------------------------------------------*/ /* Favorite Properties /*-----------------------------------------------------------------------------------*/ var addToFavorites = function (e) { e.preventDefault(); if ($(this).hasClass('require-login')) { var loginBox = $('.rh_menu__user_profile'); var loginModel = loginBox.find('.rh_modal'); if (loginModel.length) { $('.rh_login_modal_wrapper').css("display", "flex").hide().fadeIn(500); } else { window.location = $(this).data('login'); } } else { var favorite_link = $(this); var span_favorite = $(this).parent().find('span.favorite-placeholder'); var propertyID = favorite_link.data('propertyid'); var ajax_url = ajaxurl; if (propertyID !== '') { if (favorite_link.hasClass('user_logged_in')) { var add_to_favorite_options = { type: 'post', url: ajax_url, data: { action: 'add_to_favorite', property_id: propertyID, nonce: favoritesLocalizedData.favorites_nonce }, success: function (response) { if (response.success) { favorite_link.addClass('hide'); span_favorite.delay(200).removeClass('hide'); } else { console.error(response.data.message); } }, error: function (jqXHR, textStatus, errorThrown) { console.error('AJAX Error:', textStatus, errorThrown); }, }; $.ajax(add_to_favorite_options); } else { var currentIDs = window.localStorage.getItem('inspiry_favorites'); if (currentIDs) { window.localStorage.setItem('inspiry_favorites', currentIDs + ',' + propertyID); } else { window.localStorage.setItem('inspiry_favorites', propertyID); } favorite_link.addClass('hide'); span_favorite.delay(200).removeClass('hide'); } } } }; $('body').on('click', 'a.add-to-favorite', addToFavorites); var favorite_properties = window.localStorage.inspiry_favorites; // Get local favorite properties data. // Display favorited button and favorite properties on favorite page. if ( favorite_properties && ! $( 'body' ).hasClass( 'logged-in' ) ) { // To display favorited button on page load. var property_ids = favorite_properties.split( ',' ); property_ids.forEach( function ( element, index ) { var favorite_btn_wrap = $( '.favorite-btn-' + element ); var favorite_link = favorite_btn_wrap.find( 'a.add-to-favorite' ); var span_favorite = favorite_btn_wrap.find( 'span.favorite-placeholder' ); $( favorite_link ).addClass( 'hide' ); $( span_favorite ).delay( 200 ).removeClass( 'hide' ); } ); // Display favorite properties on the favorites page. var favorite_prop_page = $( '.favorite_properties_ajax' ); if ( favorite_prop_page.length ) { var design_variation = 'classic'; if ( $( 'body' ).hasClass( 'design_modern' ) ) { design_variation = 'modern'; } var favorite_prop_options = { type : 'post', dataType : 'html', url : ajaxurl, data : { action : 'display_favorite_properties', prop_ids : favorite_properties.split( ',' ), design_variation : design_variation, nonce : favoritesLocalizedData.favorites_nonce }, success : function ( response ) { if ( response.success ) { favorite_prop_page.html( response.data ); remove_from_favorite( $( 'a.remove-from-favorite' ) ); // Assuming this function exists. } else { console.error( response.message ); // Log error message if something goes wrong. } }, error : function ( jqXHR, textStatus, errorThrown ) { console.error( 'AJAX Error:', textStatus, errorThrown ); } }; $.ajax( favorite_prop_options ); } } // Migrate favorite properties from local to server. if (favorite_properties && $('body').hasClass('logged-in')) { var migrate_prop_options = { type: 'post', url: ajaxurl, data: { action: 'inspiry_favorite_prop_migration', prop_ids: favorite_properties.split(','), }, success: function (response) { if ('true' === response) { window.localStorage.removeItem('inspiry_favorites'); } } }; $.ajax(migrate_prop_options); } // Remove favorite properties. remove_from_favorite($('a.remove-from-favorite')); remove_from_favorite($('.favorite-placeholder.highlight__red')); function remove_from_favorite( remove_button ) { remove_button.on( 'click', function ( event ) { event.preventDefault(); var $this = $( this ); var property_item = $this.closest( '.favorite-btn-wrap' ); if ( ! property_item.length ) { property_item = $this.closest( 'article' ); } // If the user is not logged in, handle localStorage-based favorites. if ( ! remove_button.hasClass( 'user_logged_in' ) ) { var favorite_properties = window.localStorage.inspiry_favorites; if ( favorite_properties ) { var prop_ids = favorite_properties.split( ',' ).map( function ( value ) { return parseInt( value, 10 ); } ); const index = prop_ids.indexOf( $this.data( 'propertyid' ) ); if ( index > -1 ) { if ( $this.hasClass( 'highlight__red' ) ) { var favorite_link = property_item.find( 'a.add-to-favorite' ); var span_favorite = property_item.find( 'span.favorite-placeholder' ); $( span_favorite ).addClass( 'hide' ); $( favorite_link ).delay( 200 ).removeClass( 'hide' ); } else { property_item.delay( 200 ).remove(); } // Update localStorage after removing the property. prop_ids.splice( index, 1 ); window.localStorage.setItem( 'inspiry_favorites', prop_ids.join( ',' ) ); } } return; } // Prevent duplicate clicks by adding a "processing" class. if ( $this.hasClass( 'processing' ) ) { return; } $this.addClass( 'processing' ); var close = $( this ).find( 'i' ); close.addClass( 'fa-spin' ); // AJAX request to remove the property from favorites. var remove_favorite_request = $.ajax( { url : ajaxurl, type : "POST", data : { property_id : $this.data( 'propertyid' ), action : "remove_from_favorites", nonce : favoritesLocalizedData.favorites_nonce }, dataType : "json" } ); // Success callback for AJAX request. remove_favorite_request.done( function ( response ) { close.removeClass( 'fa-spin' ); $this.removeClass( 'processing' ); // Remove the "processing" class. if ( response.success ) { if ( $this.hasClass( 'highlight__red' ) ) { var favorite_link = property_item.find( 'a.add-to-favorite' ); var span_favorite = property_item.find( 'span.favorite-placeholder' ); $( span_favorite ).addClass( 'hide' ); $( favorite_link ).delay( 200 ).removeClass( 'hide' ); } else { property_item.delay( 200 ).remove(); } } else { console.error( response.message || "An unknown error occurred." ); } } ); // Error callback for AJAX request. remove_favorite_request.fail( function ( jqXHR, textStatus, errorThrown ) { console.log(jqXHR,textStatus,errorThrown); close.removeClass( 'fa-spin' ); $this.removeClass( 'processing' ); // Remove the "processing" class. console.error( 'AJAX Error:', textStatus, errorThrown ); } ); } ); } // Ajax Pagination Fix window.realhomes_update_favorites = function () { remove_from_favorite( $( 'a.remove-from-favorite' ) ); remove_from_favorite( $( '.favorite-placeholder.highlight__red' ) ); } // Generating agent/agency stats doughnut charts $( '.stats-wrap .tax-stats-chart' ).each( function ( index, element, b ) { let thisObj = JSON.parse( element.dataset.chartStats ), thisID = element.id, labels = thisObj.labels, values = thisObj.values, colors = thisObj.colors; const data = { labels : labels, datasets : [{ data : values, backgroundColor : colors, hoverOffset : 1 }] }; const config = { type : 'doughnut', responsive : true, data : data, options : { legend : { display : false }, // Arguments to disable tooltips on hover tooltips : { enabled : false }, hover : { mode : null } } }; new Chart( thisID, config ); } ); })(jQuery);; (function ($) { "use strict"; $(document).ready(function () { /*-----------------------------------------------------------------------------------*/ /* Contact Form Over Slider /*-----------------------------------------------------------------------------------*/ function setTelWdith() { var getNumberFieldWidth = $('.cfos_number_field').width(); $('.iti__country-list').css('width', getNumberFieldWidth + 'px'); } setTelWdith(); $(window).on('resize', setTelWdith); }); window.rhRunIntlTelInput = function(cfosID) { var rhInputIntlInput = document.querySelector(cfosID); window.intlTelInput(rhInputIntlInput, { // onlyCountries: ["al", "ad", "at", "by", "be", "ba", "bg", "hr", "cz", "dk", // "ru", "sm", "rs", "sk", "si", "es", "se", "ch", "ua", "gb"], hiddenInput: "number", initialCountry: "auto", geoIpLookup: function(success, failure) { $.get("https://ipinfo.io", function() {}, "json").always(function(resp) { var countryCode = (resp && resp.country) ? resp.country : ""; success(countryCode); }); }, utilsScript: inspiryUtilsPath.stylesheet_directory, }); } })(jQuery);; !function(){"use strict";var e,t={noop:function(){},texturize:function(e){return(e=(e=(e=(e+="").replace(/'/g,"’").replace(/'/g,"’")).replace(/"/g,"”").replace(/"/g,"”").replace(/"/g,"”").replace(/[\u201D]/g,"”")).replace(/([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g,'$1="$2"')).trim()},applyReplacements:function(e,t){if(e)return t?e.replace(/{(\d+)}/g,function(e,r){return void 0!==t[r]?t[r]:e}):e},getBackgroundImage:function(e){var t=document.createElement("canvas"),r=t.getContext&&t.getContext("2d");if(e){r.filter="blur(20px) ",r.drawImage(e,0,0);var o=t.toDataURL("image/png");return t=null,o}}},r=function(){function e(e,t){return Element.prototype.matches?e.matches(t):Element.prototype.msMatchesSelector?e.msMatchesSelector(t):void 0}function r(e,t,r,o){if(!e)return o();e.style.removeProperty("display"),e.style.opacity=t,e.style.pointerEvents="none";var a=function(i,n){var l=(performance.now()-i)/n;l<1?(e.style.opacity=t+(r-t)*l,requestAnimationFrame(()=>a(i,n))):(e.style.opacity=r,e.style.removeProperty("pointer-events"),o())};requestAnimationFrame(function(){requestAnimationFrame(function(){a(performance.now(),200)})})}return{closest:function(t,r){if(t.closest)return t.closest(r);var o=t;do{if(e(o,r))return o;o=o.parentElement||o.parentNode}while(null!==o&&1===o.nodeType);return null},matches:e,hide:function(e){e&&(e.style.display="none")},show:function(e){e&&(e.style.display="block")},fadeIn:function(e,o){r(e,0,1,o=o||t.noop)},fadeOut:function(e,o){o=o||t.noop,r(e,1,0,function(){e&&(e.style.display="none"),o()})},scrollToElement:function(e,t,r){if(!e||!t)return r?r():void 0;var o=t.querySelector(".jp-carousel-info-extra");o&&(o.style.minHeight=window.innerHeight-64+"px");var a=!0,i=Date.now(),n=t.scrollTop,l=Math.max(0,e.offsetTop-Math.max(0,window.innerHeight-function(e){var t=e.querySelector(".jp-carousel-info-footer"),r=e.querySelector(".jp-carousel-info-extra"),o=e.querySelector(".jp-carousel-info-content-wrapper");if(t&&r&&o){var a=window.getComputedStyle(r),i=parseInt(a.paddingTop,10)+parseInt(a.paddingBottom,10);return i=isNaN(i)?0:i,o.offsetHeight+t.offsetHeight+i}return 0}(t)))-t.scrollTop;function s(){a=!1}l=Math.min(l,t.scrollHeight-window.innerHeight),t.addEventListener("wheel",s),function e(){var c,u=Date.now(),d=(c=(u-i)/300)<.5?2*c*c:1-Math.pow(-2*c+2,2)/2,p=(d=d>1?1:d)*l;if(t.scrollTop=n+p,u<=i+300&&a)return requestAnimationFrame(e);r&&r(),o&&(o.style.minHeight=""),a=!1,t.removeEventListener("wheel",s)}()},getJSONAttribute:function(e,t){if(e&&e.hasAttribute(t))try{return JSON.parse(e.getAttribute(t))}catch{return}},convertToPlainText:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},stripHTML:function(e){return e.replace(/<[^>]*>?/gm,"")},emitEvent:function(e,t,r){var o;try{o=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:r||null})}catch{(o=document.createEvent("CustomEvent")).initCustomEvent(t,!0,!0,r||null)}e.dispatchEvent(o)},isTouch:function(){return"ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch}}}();function o(){var o,a,i,n,l="",s=!1,c="div.gallery, div.tiled-gallery, ul.wp-block-gallery, ul.blocks-gallery-grid, figure.wp-block-gallery.has-nested-images, div.wp-block-jetpack-tiled-gallery, a.single-image-gallery",u=".gallery-item, .tiled-gallery-item, .blocks-gallery-item, .tiled-gallery__item",d=u+", .wp-block-image",p={},m="undefined"!=typeof wpcom&&wpcom.carousel&&wpcom.carousel.stat?wpcom.carousel.stat:t.noop,g="undefined"!=typeof wpcom&&wpcom.carousel&&wpcom.carousel.pageview?wpcom.carousel.pageview:t.noop;function h(t){if(!s)switch(t.which){case 38:t.preventDefault(),p.overlay.scrollTop-=100;break;case 40:t.preventDefault(),p.overlay.scrollTop+=100;break;case 39:t.preventDefault(),e.slideNext();break;case 37:case 8:t.preventDefault(),e.slidePrev();break;case 27:t.preventDefault(),k()}}function f(){s=!0}function v(){s=!1}function y(e){e.role="button",e.tabIndex=0,e.ariaLabel=jetpackCarouselStrings.image_label}function w(){p.overlay||(p.overlay=document.querySelector(".jp-carousel-overlay"),p.container=p.overlay.querySelector(".jp-carousel-wrap"),p.gallery=p.container.querySelector(".jp-carousel"),p.info=p.overlay.querySelector(".jp-carousel-info"),p.caption=p.info.querySelector(".jp-carousel-caption"),p.commentField=p.overlay.querySelector("#jp-carousel-comment-form-comment-field"),p.emailField=p.overlay.querySelector("#jp-carousel-comment-form-email-field"),p.authorField=p.overlay.querySelector("#jp-carousel-comment-form-author-field"),p.urlField=p.overlay.querySelector("#jp-carousel-comment-form-url-field"),window.innerWidth<=760&&Math.round(window.innerWidth/760*110)<40&&r.isTouch(),[p.commentField,p.emailField,p.authorField,p.urlField].forEach(function(e){e&&(e.addEventListener("focus",f),e.addEventListener("blur",v))}),p.overlay.addEventListener("click",function(e){var t,o,a=e.target,i=!!r.closest(a,".jp-carousel-close-hint"),n=!!window.matchMedia("(max-device-width: 760px)").matches;a===p.overlay?n||k():i?k():a.classList.contains("jp-carousel-image-download")?m("download_original_click"):a.classList.contains("jp-carousel-comment-login")?(t=p.currentSlide,o=t?t.attrs.attachmentId:"0",window.location.href=jetpackCarouselStrings.login_url+"%23jp-carousel-"+o):r.closest(a,"#jp-carousel-comment-form-container")?function(e){var t=e.target,o=r.getJSONAttribute(p.container,"data-carousel-extra")||{},a=p.currentSlide.attrs.attachmentId,i=document.querySelector("#jp-carousel-comment-form-submit-and-info-wrapper"),n=document.querySelector("#jp-carousel-comment-form-spinner"),l=document.querySelector("#jp-carousel-comment-form-button-submit"),s=document.querySelector("#jp-carousel-comment-form");if(p.commentField&&p.commentField.getAttribute("id")===t.getAttribute("id"))f(),r.show(i);else if(r.matches(t,'input[type="submit"]')){e.preventDefault(),e.stopPropagation(),r.show(n),s.classList.add("jp-carousel-is-disabled");var c={action:"post_attachment_comment",nonce:jetpackCarouselStrings.nonce,blog_id:o.blog_id,id:a,comment:p.commentField.value};if(!c.comment.length)return void j(jetpackCarouselStrings.no_comment_text,!1);if(1!==Number(jetpackCarouselStrings.is_logged_in)&&(c.email=p.emailField.value,c.author=p.authorField.value,c.url=p.urlField.value,1===Number(jetpackCarouselStrings.require_name_email))){if(!c.email.length||!c.email.match("@"))return void j(jetpackCarouselStrings.no_comment_email,!1);if(!c.author.length)return void j(jetpackCarouselStrings.no_comment_author,!1)}var u=new XMLHttpRequest;u.open("POST",jetpackCarouselStrings.ajaxurl,!0),u.setRequestHeader("X-Requested-With","XMLHttpRequest"),u.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),u.onreadystatechange=function(){if(this.readyState===XMLHttpRequest.DONE&&this.status>=200&&this.status<300){var e;try{e=JSON.parse(this.response)}catch{return void j(jetpackCarouselStrings.comment_post_error,!1)}"approved"===e.comment_status?j(jetpackCarouselStrings.comment_approved,!0):"unapproved"===e.comment_status?j(jetpackCarouselStrings.comment_unapproved,!0):j(jetpackCarouselStrings.comment_post_error,!1),I(),_(a),l.value=jetpackCarouselStrings.post_comment,r.hide(n),s.classList.remove("jp-carousel-is-disabled")}else j(jetpackCarouselStrings.comment_post_error,!1)};var d=[];for(var m in c)if(m){var g=encodeURIComponent(m)+"="+encodeURIComponent(c[m]);d.push(g.replace(/%20/g,"+"))}var h=d.join("&");u.send(h)}}(e):(r.closest(a,".jp-carousel-photo-icons-container")||a.classList.contains("jp-carousel-photo-title"))&&function(e){e.preventDefault();var t=e.target,o=p.info.querySelector(".jp-carousel-info-extra"),a=p.info.querySelector(".jp-carousel-image-meta"),i=p.info.querySelector(".jp-carousel-comments-wrapper"),n=p.info.querySelector(".jp-carousel-icon-info"),l=p.info.querySelector(".jp-carousel-icon-comments");function s(){l&&l.classList.remove("jp-carousel-selected"),n.classList.toggle("jp-carousel-selected"),i&&i.classList.remove("jp-carousel-show"),a&&(a.classList.toggle("jp-carousel-show"),a.classList.contains("jp-carousel-show")?o.classList.add("jp-carousel-show"):o.classList.remove("jp-carousel-show"))}function c(){n&&n.classList.remove("jp-carousel-selected"),l.classList.toggle("jp-carousel-selected"),a&&a.classList.remove("jp-carousel-show"),i&&(i.classList.toggle("jp-carousel-show"),i.classList.contains("jp-carousel-show")?o.classList.add("jp-carousel-show"):o.classList.remove("jp-carousel-show"))}(r.closest(t,".jp-carousel-icon-info")||t.classList.contains("jp-carousel-photo-title"))&&(a&&a.classList.contains("jp-carousel-show")?r.scrollToElement(p.overlay,p.overlay,s):(s(),r.scrollToElement(p.info,p.overlay))),r.closest(t,".jp-carousel-icon-comments")&&(i&&i.classList.contains("jp-carousel-show")?r.scrollToElement(p.overlay,p.overlay,c):(c(),r.scrollToElement(p.info,p.overlay)))}(e)}),window.addEventListener("keydown",h),p.overlay.addEventListener("jp_carousel.afterOpen",function(){v(),p.slides.length<=1||(p.slides.length<=5?r.show(p.info.querySelector(".jp-swiper-pagination")):r.show(p.info.querySelector(".jp-carousel-pagination")))}),p.overlay.addEventListener("jp_carousel.beforeClose",function(){f(),document.documentElement.style.removeProperty("height"),e&&e.enable(),r.hide(p.info.querySelector(".jp-swiper-pagination")),r.hide(p.info.querySelector(".jp-carousel-pagination"))}),p.overlay.addEventListener("jp_carousel.afterClose",function(){window.history.pushState?history.pushState("",document.title,window.location.pathname+window.location.search):window.location.href="",l="",p.isOpen=!1}),p.overlay.addEventListener("touchstart",function(e){e.touches.length>1&&e.preventDefault()}))}function j(e,t){var o=p.overlay.querySelector("#jp-carousel-comment-post-results"),a="jp-carousel-comment-post-"+(t?"success":"error");o.innerHTML=''+e+"",r.hide(p.overlay.querySelector("#jp-carousel-comment-form-spinner")),p.overlay.querySelector("#jp-carousel-comment-form").classList.remove("jp-carousel-is-disabled"),r.show(o)}function b(){var e=document.querySelectorAll("a img[data-attachment-id]");Array.prototype.forEach.call(e,function(e){var t=e.parentElement,o=t.parentElement;if(!o.classList.contains("gallery-icon")&&!r.closest(o,u)&&t.hasAttribute("href")){var a=!1;t.getAttribute("href").split("?")[0]===e.getAttribute("data-orig-file").split("?")[0]&&1===Number(jetpackCarouselStrings.single_image_gallery_media_file)&&(a=!0),t.getAttribute("href")===e.getAttribute("data-permalink")&&(a=!0),a&&(y(e),t.classList.add("single-image-gallery"),t.setAttribute("data-carousel-extra",JSON.stringify({blog_id:Number(jetpackCarouselStrings.blog_id)})))}})}function S(t,r){p.isOpen?(L(r),e.slideTo(r+1)):F(t,{startIndex:r})}function L(e){(!e||e<0||e>p.slides.length)&&(e=0),p.currentSlide=p.slides[e];var o,a,i=p.currentSlide,n=i.attrs.attachmentId;H(p.slides[e]),function(e){var t=[],r=p.slides.length;if(r>1){var o=e>0?e-1:r-1;t.push(o);var a=e
"+jetpackCarouselStrings[o]+"
"+a+""}}t.innerHTML=r,t.style.removeProperty("display")}(p.slides[e].attrs.imageMeta),function(e){if(!e)return!1;var r,o=[e.attrs.origWidth,e.attrs.origHeight],a=document.createElement("a");a.href=e.attrs.src.replace(/\?.+$/,""),r=null!==a.hostname.match(/^i[\d]{1}\.wp\.com$/i)?a.href:e.attrs.origFile.replace(/\?.+$/,"");var i=p.info.querySelector(".jp-carousel-download-text"),n=p.info.querySelector(".jp-carousel-image-download");i.innerHTML=t.applyReplacements(jetpackCarouselStrings.download_original,o),n.setAttribute("href",r),n.style.removeProperty("display")}(i),1===Number(jetpackCarouselStrings.display_comments)&&(o=p.slides[e].attrs.commentsOpened,a=p.info.querySelector("#jp-carousel-comment-form-container"),1===parseInt(o,10)?r.fadeIn(a):r.fadeOut(a),_(n),r.hide(p.info.querySelector("#jp-carousel-comment-post-results")));var s=p.info.querySelector(".jp-carousel-pagination");if(s&&p.slides.length>5){var c=e+1;s.innerHTML=""+c+" / "+p.slides.length+""}jetpackCarouselStrings.stats&&((new Image).src=document.location.protocol+"//pixel.wp.com/g.gif?"+jetpackCarouselStrings.stats+"&post="+encodeURIComponent(n)+"&rand="+Math.random()),g(n),window.location.hash=l="#jp-carousel-"+n}function k(){document.body.style.overflow=a,document.documentElement.style.overflow=i,I(),f(),r.emitEvent(p.overlay,"jp_carousel.beforeClose"),window.scrollTo(window.scrollX||window.pageXOffset||0,n||0),e.destroy(),p.isOpen=!1,p.slides=[],p.currentSlide=void 0,p.gallery.innerHTML="",r.fadeOut(p.overlay,function(){r.emitEvent(p.overlay,"jp_carousel.afterClose")})}function x(e){if("object"!=typeof e&&(e={}),void 0===e.origFile)return"";if(void 0===e.origWidth||void 0===e.maxWidth)return e.origFile;if(void 0===e.mediumFile||void 0===e.largeFile)return e.origFile;var t=document.createElement("a");t.href=e.largeFile;var r=/^i[0-2]\.wp\.com$/i.test(t.hostname),o=q(e.largeFile,e.origWidth,r),a=parseInt(o[0],10),i=parseInt(o[1],10);if(e.origMaxWidth=e.maxWidth,e.origMaxHeight=e.maxHeight,void 0!==window.devicePixelRatio&&window.devicePixelRatio>1&&(e.maxWidth=e.maxWidth*window.devicePixelRatio,e.maxHeight=e.maxHeight*window.devicePixelRatio),a>=e.maxWidth||i>=e.maxHeight)return e.largeFile;var n=q(e.mediumFile,e.origWidth,r),l=parseInt(n[0],10),s=parseInt(n[1],10);if(l>=e.maxWidth||s>=e.maxHeight)return e.mediumFile;if(r){if(-1===e.largeFile.lastIndexOf("?"))return e.largeFile;if(e.origWidth>e.maxWidth||e.origHeight>e.maxHeight){var c=function(e){var t;try{t=new URL(e)}catch(t){return e}var r=["quality","ssl","filter","brightness","contrast","colorize","smooth"],o=Array.from(t.searchParams.entries());return t.search="",o.forEach(([e,o])=>{r.includes(e)&&t.searchParams.append(e,o)}),t}(e.largeFile);return e.origMaxWidth=2*e.maxWidth,e.origMaxHeight=2*e.maxHeight,c.searchParams.set("fit",e.origMaxWidth+","+e.origMaxHeight),c.toString()}return e.largeFile}return e.origFile}function q(e,t,r){var o,a=r?e.replace(/.*=([\d]+%2C[\d]+).*$/,"$1"):e.replace(/.*-([\d]+x[\d]+)\..+$/,"$1");return"9999"===(o=a!==e?r?a.split("%2C"):a.split("x"):[t,0])[0]&&(o[0]="0"),"9999"===o[1]&&(o[1]="0"),o}function A(e){return e>=1?Math.round(10*e)/10+"s":"1/"+Math.round(1/e)+"s"}function E(e){return!e.match(" ")&&e.match("_")?"":e}function _(e,t){var a=void 0===t,i=p.info.querySelector(".jp-carousel-icon-comments .jp-carousel-has-comments-indicator");if(i.classList.remove("jp-carousel-show"),clearInterval(o),e){(!t||t<1)&&(t=0);var n=p.info.querySelector(".jp-carousel-comments"),l=p.info.querySelector("#jp-carousel-comments-loading");r.show(l),a&&(r.hide(n),n.innerHTML="");var s=new XMLHttpRequest,c=jetpackCarouselStrings.ajaxurl+"?action=get_attachment_comments&nonce="+jetpackCarouselStrings.nonce+"&id="+e+"&offset="+t;s.open("GET",c),s.setRequestHeader("X-Requested-With","XMLHttpRequest");var u=function(){r.fadeIn(n),r.fadeOut(l)};s.onload=function(){if(p.currentSlide&&p.currentSlide.attrs.attachmentId===e){var c,d=s.status>=200&&s.status<300;try{c=JSON.parse(s.responseText)}catch{}if(!d||!c||!Array.isArray(c))return u();a&&(n.innerHTML="");for(var m=0;m'+g.gravatar_markup+'
'+g.author_markup+'
'+g.date_gmt+"
"+g.content+"
",n.appendChild(h),clearInterval(o),o=setInterval(function(){p.container.scrollTop+150>window.innerHeight&&(_(e,t+10),clearInterval(o))},300)}c.length>0&&(r.show(n),i.innerText=c.length,i.classList.add("jp-carousel-show")),r.hide(l)}},s.onerror=u,s.send()}}function H(e){var t=e.el,r=e.attrs,o=t.querySelector("img");if(!o.hasAttribute("data-loaded")){var a=!!r.previewImage,i=r.thumbSize;!a||i&&t.offsetWidth>i.width?o.src=r.src:o.src=r.previewImage,o.setAttribute("itemprop","image"),o.setAttribute("data-loaded",1)}}function T(t){var r=t.el;e&&e.slides&&(r=e.slides[e.activeIndex]);var o=t.attrs.originalElement;o.complete&&0!==o.naturalHeight?C(t,r,o):o.onload=function(){C(t,r,o)}}function C(e,r,o){var a=t.getBackgroundImage(o);e.backgroundImage=a,r.style.backgroundImage="url("+a+")",r.style.backgroundSize="cover"}function I(){p.commentField&&(p.commentField.value="")}function M(e,o){p.slides=[];var a={width:window.innerWidth,height:window.innerHeight-64};0!==o&&null!==e[o].getAttribute("data-gallery-src")&&((new Image).src=e[o].getAttribute("data-gallery-src"));var i=!!r.closest(e[0],".tiled-gallery.type-rectangular");Array.prototype.forEach.call(e,function(e,o){var n=r.closest(e,"a"),l=e.getAttribute("data-orig-file")||e.getAttribute("src-orig"),s=e.getAttribute("data-attachment-id")||e.getAttribute("data-id")||"0",c=document.querySelector('img[data-attachment-id="'+s+'"] + figcaption');c=c?c.innerHTML:e.getAttribute("data-image-caption");var u={originalElement:e,attachmentId:s,commentsOpened:e.getAttribute("data-comments-opened")||"0",imageMeta:r.getJSONAttribute(e,"data-image-meta")||{},title:e.getAttribute("data-image-title")||"",desc:e.getAttribute("data-image-description")||"",mediumFile:e.getAttribute("data-medium-file")||"",largeFile:e.getAttribute("data-large-file")||"",origFile:l||"",thumbSize:{width:e.naturalWidth,height:e.naturalHeight},caption:c||"",permalink:n&&n.getAttribute("href"),src:l||e.getAttribute("src")||""},d=r.closest(e,".tiled-gallery-item"),m=d&&d.querySelector(".tiled-gallery-caption"),g=m&&m.innerHTML;g&&(u.caption=g);var h=function(e){var t=e.getAttribute("data-orig-size")||"";if(t){var r=t.split(",");return{width:parseInt(r[0],10),height:parseInt(r[1],10)}}return{width:e.getAttribute("data-original-width")||e.getAttribute("width")||void 0,height:e.getAttribute("data-original-height")||e.getAttribute("height")||void 0}}(e);if(u.origWidth=h.width||u.thumbSize.width,u.origHeight=h.height||u.thumbSize.height,"undefined"!=typeof wpcom&&wpcom.carousel&&wpcom.carousel.generateImgSrc?u.src=wpcom.carousel.generateImgSrc(e,a):u.src=x({origFile:u.src,origWidth:u.origWidth,origHeight:u.origHeight,maxWidth:a.width,maxHeight:a.height,mediumFile:u.mediumFile,largeFile:u.largeFile}),e.setAttribute("data-gallery-src",u.src),"0"!==u.attachmentId){u.title=t.texturize(u.title),u.desc=t.texturize(u.desc),u.caption=t.texturize(u.caption);var f=new Image,v=document.createElement("div");v.classList.add("swiper-slide"),v.setAttribute("itemprop","associatedMedia"),v.setAttribute("itemscope",""),v.setAttribute("itemtype","https://schema.org/ImageObject");var y=document.createElement("div");y.classList.add("swiper-zoom-container"),p.gallery.appendChild(v),v.appendChild(y),y.appendChild(f),v.setAttribute("data-attachment-id",u.attachmentId),v.setAttribute("data-permalink",u.permalink),v.setAttribute("data-orig-file",u.origFile),i&&(u.previewImage=u.src);var w={el:v,attrs:u,index:o};p.slides.push(w)}})}function F(e,t){if(!window.JetpackSwiper){var o=document.querySelector("#jp-carousel-loading-overlay");r.show(o);var a=document.createElement("script");return a.id="jetpack-carousel-swiper-js",a.src=window.jetpackSwiperLibraryPath.url,a.async=!0,a.onload=function(){r.hide(o),O(e,t)},a.onerror=function(){r.hide(o)},void document.head.appendChild(a)}O(e,t)}function O(t,o){var l,s={imgSelector:".gallery-item [data-attachment-id], .tiled-gallery-item [data-attachment-id], img[data-attachment-id], img[data-id]",startIndex:0},c=r.getJSONAttribute(t,"data-carousel-extra");if(!c)return;const u=t.querySelectorAll(s.imgSelector);if(u.length&&(w(),!p.isOpen)){for(var d in p.isOpen=!0,a=getComputedStyle(document.body).overflow,document.body.style.overflow="hidden",i=getComputedStyle(document.documentElement).overflow,document.documentElement.style.overflow="hidden",n=window.scrollY||window.pageYOffset||0,p.container.setAttribute("data-carousel-extra",JSON.stringify(c)),m(["open","view_image"]),o||{})s[d]=o[d];-1===s.startIndex&&(s.startIndex=0),r.emitEvent(p.overlay,"jp_carousel.beforeOpen"),p.gallery.innerHTML="",p.overlay.style.opacity=1,p.overlay.style.display="block",M(u,s.startIndex),(e=new window.JetpackSwiper(".jp-carousel-swiper-container",{centeredSlides:!0,zoom:!0,loop:p.slides.length>1,enabled:p.slides.length>1,pagination:{el:".jp-swiper-pagination",clickable:!0},navigation:{nextEl:".jp-swiper-button-next",prevEl:".jp-swiper-button-prev"},initialSlide:s.startIndex,on:{init:function(){L(s.startIndex)}},preventClicks:!1,preventClicksPropagation:!1,preventInteractionOnTransition:!r.isTouch(),threshold:5})).on("slideChange",function(e){L(e.realIndex),p.overlay.classList.remove("jp-carousel-hide-controls")}),e.on("zoomChange",function(e,t){t>1&&p.overlay.classList.add("jp-carousel-hide-controls"),1===t&&p.overlay.classList.remove("jp-carousel-hide-controls")}),e.on("doubleTap",function(e){if(clearTimeout(l),1===e.zoom.scale)var t=setTimeout(function(){p.overlay.classList.remove("jp-carousel-hide-controls"),clearTimeout(t)},150)}),e.on("tap",function(){e.zoom.scale>1&&(l=setTimeout(function(){p.overlay.classList.toggle("jp-carousel-hide-controls")},150))}),r.fadeIn(p.overlay,function(){r.emitEvent(p.overlay,"jp_carousel.afterOpen")})}}function W(e){if("click"!==e.type){if("keydown"===e.type){const t=document.activeElement.parentElement,r=t&&t.classList.contains("tiled-gallery__item");" "!==e.key&&"Enter"!==e.key||!r||R(e)}}else R(e)}function N(e){var t=e.parentElement,o=t.parentElement,a=null;return o&&o.classList.contains("wp-block-image")?a=t.getAttribute("href"):t&&t.classList.contains("wp-block-image")&&t.querySelector(":scope > a")&&(a=t.querySelector(":scope > a").getAttribute("href")),!(a&&a.split("?")[0]!==e.getAttribute("data-orig-file").split("?")[0]&&a!==e.getAttribute("data-permalink")||t.classList.contains("gallery-caption")||r.matches(t,"figcaption"))}function R(e){if(window.CSS&&window.CSS.supports&&window.CSS.supports("display","grid")){var t,o=e.target,a=r.closest(o,c);if(a){if(!(t=a)||!t.getAttribute("data-carousel-extra"))return;if(!N(o))return;document.documentElement.style.height="auto",e.preventDefault(),e.stopPropagation();var i=r.closest(o,d),n=Array.prototype.indexOf.call(a.querySelectorAll(d),i);F(a,{startIndex:n})}}}document.body.addEventListener("click",W),document.body.addEventListener("keydown",W),document.querySelectorAll(u+"img").forEach(function(e){N(e)&&y(e)}),1===Number(jetpackCarouselStrings.single_image_gallery)&&(b(),document.body.addEventListener("is.post-load",function(){b()})),window.addEventListener("hashchange",function(){var e=/jp-carousel-(\d+)/;if(window.location.hash&&e.test(window.location.hash)){if(window.location.hash!==l||!p.isOpen)if(window.location.hash&&p.gallery&&!p.isOpen&&history.back)history.back();else{l=window.location.hash;for(var t=window.location.hash.match(e),r=parseInt(t[1],10),o=document.querySelectorAll(c),a=0;a