'use strict';

if (typeof jQuery === "undefined") {
    throw new Error("Page Editor requires jQuery");
}
$(function () {
    _init();
});
var au;
var uid;
var FeedAccessLevel;
var trebid;
var u;
var b;
var browse;
var propertiesList;
var propertiesListfilter;
var newdevpropertiesList;
var lastf;
var Toronto = "Toronto C01,Toronto C02,Toronto C03,Toronto C04,Toronto C05,Toronto C06,Toronto C07,Toronto C08,Toronto C09,Toronto C10,Toronto C11,Toronto C12,Toronto C13,Toronto c14,Toronto C15,Toronto W01,Toronto W02,Toronto W03,Toronto W04,Toronto W05,Toronto W06,Toronto W07,Toronto W08,Toronto W09,Toronto W10,Toronto E01,Toronto E02,Toronto E03,Toronto E04,Toronto E05,Toronto E06,Toronto E07,Toronto E08,Toronto E09,Toronto E10,Toronto E11";
var NorthYork = "Toronto W05,Toronto C06,Toronto C07,Toronto C14,Toronto C15";
var Etobicoke = "Toronto W06,Toronto W07,Toronto W08,Toronto W09,Toronto W10";
var MidTown = "Toronto C04,Toronto C03,Toronto C02";
var DownTown = "Toronto C01,Toronto C08";
var DonMills = "Toronto C12,Toronto C13,Toronto C10,Toronto C09,Toronto C11";
var Beaches = "Toronto E01,Toronto E02,Toronto E03";
var TorontoWest = "Toronto W01,Toronto W02,Toronto W03,Toronto W04";
var Scarborough = "Toronto E04,Toronto E05,Toronto E11,Toronto E06,Toronto E07, Toronto E09, Toronto E08, Toronto E10";
 var lazyLoadInstance = new LazyLoad({
  threshold: 300,
 });
var today = new Date().setHours(0, 0, 0, 0);
function _init() {
    au=$('#propertysearchjs').attr('data-au');
    FeedAccessLevel=$('#propertysearchjs').attr('data-access');
    trebid=$('#propertysearchjs').attr('data-id');
    u = $('#propertysearchjs').attr('data-uname');
    uid = $('#propertysearchjs').attr('data-uid');
    b = $('#propertysearchjs').attr('data-office');

    function filterProperties(data, filters) {
        return data.filter(item => {
            const property = item['_source']; // Access the nested _source object
            let isValid = true; // Assume the item is valid unless a filter fails

            // Check each filter and if it exists, apply it
            if (filters.propertytype && filters.propertytype !== property.PropertyType) isValid = false;
            if (filters.salelease && filters.salelease !== property.SaleLease) isValid = false;
            if (filters.type && filters.type !== property.Type) isValid = false;
            if (filters.city && filters.city !== property.MunicipalityDistrict) isValid = false;
            if (filters.minprice && (parseInt(property.ListPrice) < parseInt(property.minprice))) isValid = false;
            if (filters.maxprice && (parseInt(property.ListPrice) > parseInt(property.maxprice))) isValid = false;

            return isValid; // Return true if all relevant filters pass
        });
    }
    $(".featured-listings").each(function (index) {
        var divid = $(this).attr('id');
        $('#' + divid).find('#filter_featured').append('<div class="bloader"><div class="ball"></div><div class="ball"></div><div class="ball"></div><span>Loading...</span></div>');
        var propertyclass = $(this).attr('data-listing-class');
        var propertytype = $(this).attr('data-listing-type');
        var sold = '';
        var featured = $(this).attr('data-listing-featured');
        var salelease = $(this).attr('data-listing-transaction');
        var type = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var status = $(this).attr('data-listing-status');
        var minprice = $(this).attr('data-listing-minprice');
        var maxprice = $(this).attr('data-listing-maxprice');
        var limit = $(this).attr('data-listing-limit');
        var tag = $(this).attr('data-listing-tag');
        var display = $(this).attr('data-listing-display');
        var filter = $(this).attr('data-listing-filter');

        if (status == 'Sld') { sold = '1'; }
        if (status == 'A') { sold = '0'; }
        if (propertyclass == "Exclusive") { FeedAccessLevel = "REMEX"; }
        var filterQuery = 'uname=' + u + '&active=1&featured=' + featured + '&sold=' + sold + '&salelease=' + salelease + '&proptype=' + propertytype + '&accesslevel=' + FeedAccessLevel + '&tag=' + tag + '&limit=' + limit;
      
        fetch("https://remarketer.azure-api.net/listings/agent_listings?" + filterQuery, {
            method: 'GET',
            headers: {
                "api_key": "d468c0dbe3ae41d69db0c0e3f8ca1477",
                "Accept": "application/json"  // Ensure JSON response
            }
        }).then(response => response.json())
            .then(data => {

                const filters = {
                    propertytype: propertytype,
                    salelease: salelease,
                    type: type,
                    city: city,
                    minprice: minprice,
                    maxprice: maxprice
                };
                if (salelease || type || city || minprice || maxprice) {
                    const filteredData = filterProperties(data, filters);
                    propertiesList = filteredData;
                } else {
                    propertiesList = data;
                }
                if (Array.isArray(propertiesList) && propertiesList.length > 1) {

                    propertiesList.sort((a, b) => {
                        if (b["_source"]["AdditionalItems"]["Priority"] !== a["_source"]["AdditionalItems"]["Priority"]) {
                            return b["_source"]["AdditionalItems"]["Priority"] - a["_source"]["AdditionalItems"]["Priority"];  // Descending by Priority
                        }
                        // Assuming DateAdded or another date field for secondary sort
                        const dateA = new Date(a["_source"] && a["_source"]["ListingEntryDate"] ? parseInt(a["_source"]["ListingEntryDate"].match(/\d+/)[0], 10) : 0);
                        const dateB = new Date(b["_source"] && b["_source"]["ListingEntryDate"] ? parseInt(b["_source"]["ListingEntryDate"].match(/\d+/)[0], 10) : 0);
                        return dateB - dateA;  // Descending by Date
                    });
                }

                
                elasticpropertylargegrid(divid, filter, propertiesList);
            });
    });
      

    
   
     $(".featured-listings-tr").each(function (index) {
        var divid = $(this).attr('id');
         $('#' + divid).find('#filter_featured').append('<div class="bloader"><div class="ball"></div><div class="ball"></div><div class="ball"></div><span>Loading...</span></div>');
      var propertyclass = $(this).attr('data-listing-class');
        var propertytype = $(this).attr('data-listing-type');
        var sold = '';
         var featured = $(this).attr('data-listing-featured');
        var salelease = $(this).attr('data-listing-transaction');
        var type = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var status = $(this).attr('data-listing-status');
        var minprice = $(this).attr('data-listing-minprice');
        var maxprice = $(this).attr('data-listing-maxprice');
         var limit = $(this).attr('data-listing-limit');
         var tag = $(this).attr('data-listing-tag');
         var display = $(this).attr('data-listing-display');
         var filter = $(this).attr('data-listing-filter');

        if (status == 'Sld') { sold = '1'; }
         if (status == 'A') { sold = '0'; }
         if (propertyclass == "Exclusive") { FeedAccessLevel = "REMEX"; }
        
         $.getJSON('https://apostropheapi.azurewebsites.net/api/getlistingmanager?u=' + u + '&featured=' + featured + '&sold=' + sold + '&salelease=' + salelease + '&class=' + propertyclass + '&proptype=' + propertytype + '&accesslevel=' + FeedAccessLevel + '&tag=' + tag + '&limit=' + limit, function (data) {
             const mlsToPriorityMap = new Map(data.map(item => [item.MLS.trim(), item.Priority, item.Source]));

                 const remexData = data.filter(item => item.Source === 'REMEX');
                 const remexMLS = remexData.map(item => item.MLS.trim());
                 const remexMLSString = remexMLS.join(',') || '00000000';

                 // Filtering for other sources
                 const otherData = data.filter(item => item.Source !== 'REMEX');
                 const otherMLS = otherData.map(item => item.MLS.trim());
                const otherMLSString = otherMLS.join(',') || '00000000';

             const urlRemex = `https://apostropheapi.azurewebsites.net/api/ES_REMEX_Query?mls=${remexMLSString}`;
             const urlOther = `https://apostropheapi.azurewebsites.net/api/ES_Query?mls=${otherMLSString}`;
                 
                 // Perform the AJAX requests
                 const requestRemex = $.getJSON(urlRemex);
                 const requestOther = $.getJSON(urlOther);
                 // Wait for both AJAX requests to complete
                 $.when(requestRemex, requestOther).done(function (responseRemex, responseOther) {
                     
                     const combinedData = responseOther[0].concat(responseRemex[0]);
                     const filters = {
                         propertytype: propertytype,
                         salelease: salelease,
                         type: type,
                         city: city,
                         minprice: minprice,
                         maxprice: maxprice
                     };
                     if (salelease || type || city || minprice || maxprice) {
                         const filteredData = filterProperties(combinedData, filters);
                         propertiesList = filteredData;
                     } else {
                         propertiesList = combinedData;
                     }
                     if (Array.isArray(propertiesList) && propertiesList.length > 1) {
                         propertiesList.forEach(item => {
                             const mls = item["_source"] ? item["_source"].MLS : null;
                             item.Priority = mlsToPriorityMap.get(mls) || -Infinity;  // Assign a low priority if not found
                         });
                         propertiesList.sort((a, b) => {
                             if (b.Priority !== a.Priority) {
                                 return b.Priority - a.Priority;  // Descending by Priority
                             }
                             // Assuming DateAdded or another date field for secondary sort
                             const dateA = new Date(a["_source"] && a["_source"].DateAdded ? parseInt(a["_source"].DateAdded.match(/\d+/)[0], 10) : 0);
                             const dateB = new Date(b["_source"] && b["_source"].DateAdded ? parseInt(b["_source"].DateAdded.match(/\d+/)[0], 10) : 0);
                             return dateB - dateA;  // Descending by Date
                         });
                     }

                     // Call the display function with the sorted data
                     elasticpropertylargegrid(divid, filter, propertiesList);
                 });



             });

        /*
         $.getJSON('/api/agentlistingsfilter?u=' + u + '&featured=' + featured + '&sold=' + sold + '&salelease=' + salelease + '&class='+propertyclass+'&proptype=' + propertytype + '&accesslevel=' + FeedAccessLevel + '&muni=' + city + '&minprice=' + minprice + '&maxprice=' + maxprice+ '&tag=' + tag+ '&limit=' + limit, function (data) {
             propertiesList = data;
            featurepropertyhome(divid,data);

         });}*/
         
     });
   
    $(".agent-listings").each(function (index) {
        var divid = $(this).attr('id');
        $('#' + divid).append(' <div class="bloader"><div class="ball"></div><div class="ball"></div><div class="ball"></div><span>Loading...</span></div>');
         var propertyclass = $(this).attr('data-listing-class');
        var propertytype = $(this).attr('data-listing-type');
        var sold = '';
        var active = '1';
        var salelease = $(this).attr('data-listing-transaction');
        var style = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var municipalitycode = $(this).attr('data-listing-municode');
        var communitycode = $(this).attr('data-listing-commcode');
        var status = $(this).attr('data-listing-status');
        var minprice = $(this).attr('data-listing-minprice');
        var maxprice = $(this).attr('data-listing-maxprice');
        var limit = $(this).attr('data-listing-limit');
        var listagentid = $(this).attr('data-listing-listagentid');
        if (status == 'Sld') { sold = '1'; }
        if (status == 'A') { sold = '0'; }
      
        var formdata = 'active=' + active + '&sold=' + sold + '&salelease=' + salelease + '&classsearch=' + propertyclass + '&typesearch=' + propertytype + '&source=' + FeedAccessLevel + '&municipalitydistrict=' + city + '&minprice=' + minprice + '&maxprice=' + maxprice + '&municipalitycode=' + municipalitycode + '&communitycode=' + communitycode + '&listagentid=' + listagentid + '&limit=' + limit;

        fetch("https://remarketer.azure-api.net/PropertySearch/search?" + formdata, {
            method: 'GET',
            headers: {
                "api_key": "d468c0dbe3ae41d69db0c0e3f8ca1477"
            }
        }).then(response => response.json())
            .then(data => {
                propertiesList = data;
                elasticpropertygrid(divid, data);
            });

    });
    $(".newdev-listings-tr").each(function (index) {
        var divid = $(this).attr('id');
        var featured = $(this).attr('data-listing-featured');
        var type = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var salelease = $(this).attr('data-listing-transaction');
        var limit = $(this).attr('data-listing-limit');
        var tag = $(this).attr('data-listing-tag');
        if (!tag) { tag = ''; }
        if (!salelease) { salelease = ''; }

        $.getJSON('https://apostropheapi.azurewebsites.net/api/agentnewdevlistingsfilter?u=' + u + '&featured=' + featured + '&trebid=' + trebid + '&salelease=' + salelease + '&accesslevel=' + FeedAccessLevel + '&type=' + type + '&tag=' + tag + '&limit=' + limit, function (data) {
            // propertiesList = data;
            newdevpropertygrid(divid, data);
        });
    });

    $(".newdev-listings").each(function (index) {
         var divid = $(this).attr('id');
        var featured = $(this).attr('data-listing-featured');
        var type = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var salelease = $(this).attr('data-listing-transaction');
        var limit = $(this).attr('data-listing-limit');
        var tag = $(this).attr('data-listing-tag');
        if (!tag) { tag = ''; }
        if (!salelease) { salelease = ''; }

        var filterQuery = 'uname=' + u + '&active=1&featured=' + featured + '&salelease=' + salelease + '&accesslevel=APOSOL&type=' + type + '&tag=' + tag + '&limit=' + limit;

        fetch("https://remarketer.azure-api.net/listings/agent_listings?" + filterQuery, {
            method: 'GET',
            headers: {
                "api_key": "d468c0dbe3ae41d69db0c0e3f8ca1477",
                "Accept": "application/json"  // Ensure JSON response
            }
        }).then(response => response.json())
            .then(data => {
                const filters = {
                    salelease: salelease,
                    type: type,
                    city: city
                };
                if (salelease || type || city) {
                    const filteredData = filterProperties(data, filters);
                    newdevpropertiesList = filteredData;
                } else { newdevpropertiesList = data; }


                if (Array.isArray(newdevpropertiesList) && newdevpropertiesList.length > 1) {

                    newdevpropertiesList.sort((a, b) => {
                        if (b["_source"]["AdditionalItems"]["Priority"] !== a["_source"]["AdditionalItems"]["Priority"]) {
                            return b["_source"]["AdditionalItems"]["Priority"] - a["_source"]["AdditionalItems"]["Priority"];  // Descending by Priority
                        }

                        const dateA = new Date(a["_source"] && a["_source"]["ListingEntryDate"] ? parseInt(a["_source"]["ListingEntryDate"].match(/\d+/)[0], 10) : 0);
                        const dateB = new Date(b["_source"] && b["_source"]["ListingEntryDate"] ? parseInt(b["_source"]["ListingEntryDate"].match(/\d+/)[0], 10) : 0);
                        return dateB - dateA;  // Descending by Date
                    });
                }

                elasticnewdevpropertygrid(divid, newdevpropertiesList);
            });

       
    });
    $(".buildify-listings").each(function (index) {
        var divid = $(this).attr('id');
        var featured = $(this).attr('data-listing-featured');
        var trending = $(this).attr('data-listing-trending');
        var search = $(this).attr('data-listing-search');
        var province = $(this).attr('data-listing-province');
        var limit = $(this).attr('data-listing-limit');
        var display = $(this).attr('data-listing-display');
        $.getJSON('https://apostropheapi.azurewebsites.net/api//buildify-search?featured=' + featured + '&trending=' + trending + '&search=' + search + '&province=' + province + '&limit=' + limit, function (data) {
           
            if (display == "carousel") { buildifypropertycarousel(divid, data); }
            else {
                buildifypropertygrid(divid, data);
            }
        });

    });
    $(".brokerage-listings").each(function (index) {

         var divid = $(this).attr('id');
        $('#' + divid).append(' <div class="bloader"><div class="ball"></div><div class="ball"></div><div class="ball"></div><span>Loading...</span></div>');
        b = encodeURIComponent(b);
         var propertyclass = $(this).attr('data-listing-class');
        var propertytype = $(this).attr('data-listing-type');
        var sold = '';
        var active = "1";
        var salelease = $(this).attr('data-listing-transaction');
        var type = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var status = $(this).attr('data-listing-status');
        var minprice = $(this).attr('data-listing-minprice');
        var maxprice = $(this).attr('data-listing-maxprice');
        var limit = $(this).attr('data-listing-limit');
        if (status == 'Sld') { sold = '1'; active = '0'; }
        if (status == 'A') { sold = '0'; }
        if (type) { type = type.replace('Condo Apt', 'Apartment Unit').replace('Att/Row/Twnhouse', 'Row/Townhouse'); }
        if (!propertyclass) { propertyclass = propertytype; }

        var formdata = 'listbrokerage='+b+'&active=' + active + '&sold=' + sold + '&salelease=' + salelease + '&classsearch=' + propertyclass + '&typesearch=' + type + '&source=' + FeedAccessLevel + '&municipalitydistrict=' + city + '&minprice=' + minprice + '&maxprice=' + maxprice + '&limit=' + limit;

        
        fetch("https://remarketer.azure-api.net/PropertySearch/search?" + formdata, {
            method: 'GET',
            headers: {
                "api_key": "d468c0dbe3ae41d69db0c0e3f8ca1477"
            }
        }).then(response => response.json())
            .then(data => {
                propertiesList = data;
                elasticpropertygrid(divid, data);
            });


       

       // $.getJSON('/api/availablebrokeragelistings?b=' + b + '&limit=' + limit + '&sold=' + sold + '&salelease=' + salelease + '&class='+propertyclass+'&proptype=' + propertytype + '&accesslevel=' + FeedAccessLevel + '&muni=' + city + '&minprice=' + minprice + '&maxprice=' + maxprice, function (data) {
        //    propertiesList = data;
         //   propertygrid(divid, data);
       // });
    });

    $(".listings").each(function (index) {
       
        var divid = $(this).attr('id');
        $('#' + divid).append('<div class="bloader"><div class="ball"></div><div class="ball"></div><div class="ball"></div><span>Loading...</span></div>');
        var propertyclass = $(this).attr('data-listing-class');
        var propertytype = $(this).attr('data-listing-type');
        var laststatus = '';
        var active = 1;
        var sold = 0;
        var salelease = $(this).attr('data-listing-transaction');
        var type = $(this).attr('data-listing-style');
        var city = $(this).attr('data-listing-city');
        var area = $(this).attr('data-listing-area');
        var community = $(this).attr('data-listing-community');
        var status = $(this).attr('data-listing-status');
        var postalcode = $(this).attr('data-listing-postalcode');
        var minprice = $(this).attr('data-listing-minprice');
        var maxprice = $(this).attr('data-listing-maxprice');
        var limit = $(this).attr('data-listing-limit');
        var subtype = $(this).attr('data-listing-subtype');
        browse = $(this).attr('data-listing-browse');
        if (!propertyclass) { propertyclass = propertytype; }
        if (!subtype) { subtype = ''; }
        if (!browse) { browse = ''; }

        if (status == 'Sld') { sold = 1; active = 0; salelease = 'Sale'; }
        if (type) { type = type.replace('Condo Apt', 'Apartment Unit').replace('Att/Row/Twnhouse', 'Row/Townhouse'); }
        switch (city) {
            case "Toronto":
                city = Toronto;
                break;
            case "City Of Toronto":
                city = Toronto;
                break;
            case "North York":
                city = NorthYork;
                break;
            case "North-York":
                city = "NorthYork";
                break;
            case "Etobicoke":
                city = Etobicoke;
                break;
            case "Toronto Midtown":
                city = MidTown;
                break;
            case "Don-Mills":
                city = DonMills;
                break;
            case "Toronto Don-Mills":
                city = DonMills;
                break;
            case "Toronto Beaches":
                city = Beaches;
                break;
            case "Toronto West":
                city = TorontoWest;
                break;
            case "Scarborough":
                city = Scarborough;
        }

        var formdata = 'active=' + active + '&sold=' + sold + '&salelease=' + salelease + '&propertytypesearch=' + propertyclass + '&typesearch=' + type + '&source=' + FeedAccessLevel + '&municipalitydistrict=' + city + '&minprice=' + minprice + '&maxprice=' + maxprice + '&limit=' + limit + '&postalcode=' + postalcode + '&community=' + community + '&propertysubtypesearch=' + subtype;
        if (area && area != 'undefined') { formdata = formdata + '&area=' + area; }
        fetch("https://remarketer.azure-api.net/PropertySearch/search?" + formdata, {
            method: 'GET',
            headers: {
                "api_key": "d468c0dbe3ae41d69db0c0e3f8ca1477"
            }
        }).then(response => response.json())
            .then(data => {
                propertiesList = mergeObjects(data);
                elasticpropertygrid(divid, data);
            });
     
       
    });

}
function mergeObjects(arr) {
    var mergedObj = [];
    if (arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            var property = arr[i]['_source'];
            mergedObj.push(property);
        }

    }
    return mergedObj
}

function checkRecentSoldDate(soldDate) {
    if (!soldDate) return false; // If no sold date provided, return false

    const soldDateObj = new Date(soldDate);
    const threeMonthsAgo = new Date();
    threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);

    return soldDateObj > threeMonthsAgo;
}
 function featurepropertygrid(divid,data) {
            var sec =  $('#'+divid).find('.row');
             $(sec).empty();
            $('#' + divid).find('.bloader').css('display','none');
            if (data.length > 0) {
                $('#resultcount').html(data.length);
                 for (var i = 0; i < data.length; i++) {
                    var property = data[i];
                    var trebmask = '';
                    var unitnumber = '';
                     var AskingPrice=property.listPrice;
        var pricesec='$';
                if(AskingPrice !=null){
                 pricesec='$'+ parseFloat(AskingPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                var bplus = '';
                     var blur, ohtag = '';
        var exclusivetag='';
                if(property.BedroomsPlus !='' && property.BedroomsPlus != null){bplus = '+'+property.BedroomsPlus; }
                if(property.UnitNumber !='' && property.UnitNumber != null){unitnumber = property.UnitNumber+', '; }
                var statustagclass= 'property-status';
                var statustag = 'For '+property.SaleLease;
                var typeown1out = property.Typeown1out;
              var community = "";
                if(property.Community != null && property.Community !='' && property.Community!='---'){community = "in "+property.Community;}
          var address = '';
                     var imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,c-force';
                if(property.DisplayAddressOnInternet !="N"){address = '<p>'+unitnumber+''+property.address+', '+property.Municipality+'</p>';}

                if (typeown1out == "Semi-Detached"){typeown1out ='Semi Detached';}else if (typeown1out == "Att/Row/Twnhouse"){typeown1out='Townhouse';}else if (typeown1out == "Condo Apt"){typeown1out='Condo';}
                     var parking = String(property.GarageSpaces);
            if(parking !=null && parking !='' && parking != undefined){parking = parking.replace('.00','').replace('.0',''); }
              if(property.Source=="APOSOL"){imgbg = '/GetPropertyImage/' + property.MLS + '/1/'+property.Source;}
           if((property.LastStatus == 'Sld' || property.LastStatus == 'Lsd')){
               statustagclass= 'property-sold-status';
               if(property.SaleLease == "Sale"){statustag = 'SOLD';}else{statustag = 'LEASED';}
               pricesec=statustag;
               }
                     if (au == '0' && property.Source != 'APOSOL' && property.Source != 'REMEX') {
                         if (property.Status != "A" || (property.Status == "A" && property.IDX != 'Y')) {
                             blur = 'blur-on';
                             imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,bl-4,c-force';
                 if (property.Status == "A" && property.IDX != 'Y') {
                     trebmask = '<div class="treb-mask"><span>Login Required</span></div>';
                 }
                
                             address = '<p style="position: relative"><span class="blur-element">' + unitnumber + '' + property.address + ', ' + property.Municipality + '</span><a class="login-mask-tiny-left" href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '">Sign up or Log in to view</a></p>';
                pricesec= statustag;
             }
             }
                     if (property.OpenHouseDate1) {
                         if (new Date(property.OpenHouseDate1).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.OpenHouseDate2) {
                         if (new Date(property.OpenHouseDate2).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.OpenHouseDate3) {
                         if (new Date(property.OpenHouseDate3).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.oh1Start) {
                       
                         if (new Date(property.oh1Start).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.oh2Start) {
                         if (new Date(property.oh2Start).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
        if(property.Class=="Exclusive" && property.Status == "A"){exclusivetag='<div class="openhouse-tag"><span>'+property.Use+'</span></div>';}
            
      
                                  
                var propMetas='';
                 
                    if(property.PropertyType !="Commercial"){ propMetas='<div class="property-meta entry-meta clearfix clearfix '+blur+'"><div class="meta-wrapper"> <span class="meta-value">' + property.Bedrooms + '' + bplus + '</span> <span class="meta-label">Beds</span> </div><div class="meta-wrapper"> <span class="meta-value">' + property.Washrooms + '</span> <span class="meta-label">Baths</span> </div><div class="meta-wrapper"> <span class="meta-value">' + parking + '</span> <span class="meta-label">Garage</span> </div></div>';}
                    else{propMetas='<div class="property-meta entry-meta clearfix"> <div class="meta-wrapper"> <span class="meta-value">Property Type</span> <sub class="meta-unit">'+typeown1out+'</sub> </div></div>';}
                    
                     var content = '<div class="col-xs-6 custom-col-xs-12 col-sm-6 col-md-4 ' + property.PropertyType + ' ' + property.SaleLease + ' item"><article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><img class="img-responsive lazy" src="' + imgbg + '" data-src="' + imgbg + '" alt="' + property.address + '">' + trebmask + ' ' + exclusivetag + ' ' + ohtag+'</a> <a href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><span class="' + statustagclass + '">' + statustag + '</span></a> </div><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"> '+typeown1out+' '+community+'</a></h4> <div class="price-and-status"><span class="price">' + pricesec+'</span></div></header>'+address+''+ propMetas +'</div></article></div>';

                    $(sec).append(content);
       
                }
                lazyLoadInstance.update();
                loadmore(divid);
            } else {$(sec).append('<h4>No Listing Found.</h4>');}
        };

function elasticpropertylargegrid(divid, filter, data) {
    $('#' + divid).css('display', 'block');
    var sec = $('#' + divid).find('.listings_wrapper');
    $(sec).empty();
    $('#' + divid).find('.bloader').css('display', 'none');
        if (data.length > 0) {
            $('#resultcount').html(data.length);
            for (var i = 0; i < data.length; i++) {
                var property = data[i]['_source'];
            var trebmask = '';
            var unitnumber = '';
                var AskingPrice = property.ListPrice;
                var pricesec = '$';
                if (AskingPrice != null) {
                    pricesec = '$' + parseFloat(AskingPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
            var bplus = '';
                var blur = ""; var ohtag = '';
            var exclusivetag = '';
                if (property.BedroomsPlus != '' && property.BedroomsPlus != null && property.BedroomsPlus != "0") { bplus = '+' + property.BedroomsPlus; }
            if (property.UnitNumber != '' && property.UnitNumber != null) { unitnumber = property.UnitNumber + ', '; }
            var statustagclass = 'property-status';
            var statustag = 'For ' + property.SaleLease;
            var typeown1out = property.Type;
            var community = "";
            if (property.Community != null && property.Community != '' && property.Community != '---') { community = "in " + property.Community; }
            var address = '';
            var imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,c-force';
            if (property.DisplayAddressOnInternet != "N") { address = '<p>' + unitnumber + '' + property.Address + ', ' + property.Municipality + '</p>'; }

            if (typeown1out == "Semi-Detached") { typeown1out = 'Semi Detached'; } else if (typeown1out == "Att/Row/Twnhouse") { typeown1out = 'Townhouse'; } else if (typeown1out == "Condo Apt") { typeown1out = 'Condo'; }
                var parking = String(property.GarageSpaces);
               
            if (parking != null && parking != '' && parking != undefined) { parking = parking.replace('.00', '').replace('.0', ''); }
            if (property.Source == "APOSOL") { imgbg = '/GetPropertyImage/' + property.MLS + '/1/' + property.Source; }
            if ((property.LastStatus == 'Sld' || property.LastStatus == 'Lsd')) {
                statustagclass = 'property-sold-status';
                if (property.SaleLease == "Sale") { statustag = 'SOLD'; } else { statustag = 'LEASED'; }
                pricesec = statustag;
            }
            if (au == '0' && property.Source != 'APOSOL' && property.Source != 'REMEX') {
                if (property.Status != "A" || (property.Status == "A" && property.IDX != 'Y')) {
                    blur = 'blur-on';
                    imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,bl-4,c-force';
                    if (property.Status == "A" && property.IDX != 'Y') {
                        trebmask = '<div class="treb-mask"><span>Login Required</span></div>';
                    }

                    address = '<p style="position: relative"><span class="blur-element">' + unitnumber + '' + property.Address + ', ' + property.Municipality + '</span><a class="login-mask-tiny-left" href="/Details/' + property.MLS + '/' + property.Address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '">Sign up or Log in to view</a></p>';
                    pricesec = statustag;
                }
            }
            if (property.OpenHouseDate1) {
                if (new Date(property.OpenHouseDate1).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
            }
            if (property.OpenHouseDate2) {
                if (new Date(property.OpenHouseDate2).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
            }
            if (property.OpenHouseDate3) {
                if (new Date(property.OpenHouseDate3).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
            }
            if (property.oh1Start) {

                if (new Date(property.oh1Start).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
            }
            if (property.oh2Start) {
                if (new Date(property.oh2Start).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
            }
            if (property.Source == "REMEX" && property.Status == "A") { exclusivetag = '<div class="openhouse-tag"><span>' + property.Category + '</span></div>'; }



            var propMetas = '';

            if (property.PropertyType != "Commercial") { propMetas = '<div class="property-meta entry-meta clearfix clearfix ' + blur + '"><div class="meta-wrapper"> <span class="meta-value">' + property.Bedrooms + '' + bplus + '</span> <span class="meta-label">Beds</span> </div><div class="meta-wrapper"> <span class="meta-value">' + property.Washrooms + '</span> <span class="meta-label">Baths</span> </div><div class="meta-wrapper"> <span class="meta-value">' + parking + '</span> <span class="meta-label">Garage</span> </div></div>'; }
            else { propMetas = '<div class="property-meta entry-meta clearfix"> <div class="meta-wrapper"> <span class="meta-value">Property Type</span> <sub class="meta-unit">' + typeown1out + '</sub> </div></div>'; }

                var content = '<div class="col-xs-6 custom-col-xs-12 col-sm-6 col-md-4 ' + property.ClassSearch + ' ' + property.SaleLease + ' item"><article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="/Details/' + property.MLS + '/' + property.Address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><img class="img-responsive lazy" src="' + imgbg + '" data-src="' + imgbg + '" alt="' + property.Address + '">' + trebmask + ' ' + exclusivetag + ' ' + ohtag + '</a> <a href="/Details/' + property.MLS + '/' + property.Address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><span class="' + statustagclass + '">' + statustag + '</span></a> </div><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="/Details/' + property.MLS + '/' + property.Address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"> ' + typeown1out + ' ' + community + '</a></h4> <div class="price-and-status"><span class="price">' + pricesec + '</span></div></header>' + address + '' + propMetas + '</div></article></div>';

                if (filter == "old-sold") {

                    if (property.Active == 1 || (property.Sold == 1 && checkRecentSoldDate(property.SoldDate))) { $(sec).append(content); }

                } else { $(sec).append(content); }

        }
        lazyLoadInstance.update();
           // loadmore(divid);
           filterlisting();
        } else { $('#' + divid).css('display', 'none'); }
};
function elasticpropertygrid(divid, data) {
    
    var sec = $('#' + divid).find('.row');
    $(sec).empty();
    $('#' + divid).find('.bloader').css('display', 'none');
    if (data.length > 0) {
        $('#resultcount').html(data.length);
        for (var i = 0; i < data.length; i++) {
            var property = data[i]['_source'];
            var trebmask = '';
            var unitnumber = '';
            var propertylink = "/Details/" + property.MLS + "/" + property.Address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-");
            if (browse == "r") { propertylink = "#submitsec"; }
            var AskingPrice = property.ListPrice;
            var pricesec = '$';
            if (AskingPrice != null) {
                pricesec = '$' + parseFloat(AskingPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
            }
            var bplus = '';
            var blur = '';
            var exclusivetag = '';
            if (property.BedroomsPlus != '' && property.BedroomsPlus != null && property.BedroomsPlus != '0') { bplus = '+' + property.BedroomsPlus; }
            if (property.UnitNumber != '' && property.UnitNumber != null) { unitnumber = property.UnitNumber + ', '; }
            var statustagclass = 'property-status';
            var statustag = 'For ' + property.SaleLease;
            var typeown1out = property.Type;
            var community = "";
            if (property.Community != null && property.Community != '' && property.Community != '---') { community = "in " + property.Community; }
            var address = '';
            var imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,c-force';
            if (property.DisplayAddressOnInternet != "N") { address = unitnumber + '' + property.Address + ', ' + property.Municipality; }

            if (typeown1out == "Semi-Detached") { typeown1out = 'Semi Detached'; } else if (typeown1out == "Att/Row/Twnhouse") { typeown1out = 'Townhouse'; } else if (typeown1out == "Condo Apt") { typeown1out = 'Condo'; }
            var parking = String(property.GarageSpaces);
            if (parking != null && parking != '' && parking != undefined) { parking = parking.replace('.00', '').replace('.0', ''); }
            if (property.Source == "APOSOL") { imgbg = '/GetPropertyImage/' + property.MLS + '/1/' + property.Source; }
            if ((property.Sold == 1)) {
                statustagclass = 'property-sold-status';
                if (property.SaleLease == "Sale") { statustag = 'SOLD'; } else { statustag = 'LEASED'; }
                pricesec = statustag;
            }
            if (au == '0' && property.Source != 'APOSOL' && property.Source != 'REMEX') {
                if (property.Status != "A" || (property.Status == "A" && property.IDX != 'Y')) {
                    blur = 'blur-on';
                    imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,bl-4,c-force';
                    
                    trebmask = '<a href="#" data-toggle="modal" data-target="#logInModal"><div class="login-mask">Login Required</div></a>';
                   
                   
                   // address = '<p style="position: relative"><span class="blur-element">' + unitnumber + '' + property.Address + ', ' + property.Municipality + '</span><a class="login-mask-tiny-left" href="'+ propertylink+'">Sign up or Log in to view</a></p>';
                    pricesec = statustag;
                }
            }

            if (property.Class == "Exclusive" && property.Status == "A") { exclusivetag = '<div class="openhouse-tag"><span>' + property.Use + '</span></div>'; }

            var propMetas = '';

            if (property.ClassSearch != "Commercial") { propMetas = '<div class="property-meta entry-meta clearfix ' + blur + '"><div class="meta-wrapper"> <span class="meta-value">' + property.Bedrooms + '' + bplus + '</span> <span class="meta-label">Beds</span> </div><div class="meta-wrapper"> <span class="meta-value">' + property.Washrooms + '</span> <span class="meta-label">Baths</span> </div><div class="meta-wrapper"> <span class="meta-value">' + parking + '</span> <span class="meta-label">Garage</span> </div></div>'; }
            else { propMetas = '<div class="property-meta entry-meta clearfix ' + blur + '"> <div class="meta-wrapper"> <span class="meta-value">Property Type</span> <sub class="meta-unit">' + typeown1out + '</sub> </div></div>'; }

            var content = '<div class="col-xs-6 custom-col-xs-6 item"><article class="hentry featured-property-post clearfix animated fade-in-left"><div class="property-thumbnail"><a href="' + propertylink + '"><img class="img-responsive lazy" src="' + imgbg + '" data-src="' + imgbg + '" alt="' + property.Address + '"></a><a href="' + propertylink + '"><span class="' + statustagclass + '">' + statustag + '</span></a></div><div class="property-description "><header class="entry-header ' + blur + '"><h4 class="entry-title"><a href="' + propertylink + '" rel="bookmark">' + address + '</a></h4><div class="price-and-status"><span class="price">' + pricesec + '</span></div></header>' + propMetas + '' + trebmask +'</div></article></div>';
            $(sec).append(content);

        }
        lazyLoadInstance.update();
        loadmore(divid);
    } else { $(sec).append('<h4 class="text-center">No Listing Found.</h4>'); }
};

function propertygrid(divid,data){
     
     var sec =  $('#'+divid).find('.row');
      $(sec).empty();
    $('#' + divid).find('.bloader').css('display','none');
            if (data.length > 0) {
    $('#resultcount').html(data.length);
            for (var i = 0; i < data.length; i++) {
                var property = data[i];
                var bplus = '';
                var address = '';
                var unitnumber='';
                var imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,c-force';
                   if(property.Source=="APOSOL"){imgbg = '/GetPropertyImage/' + property.MLS + '/1/'+property.Source;}
                if (property.BedroomsPlus != '' && property.BedroomsPlus != null) { bplus = '+' + property.BedroomsPlus; }
                if(property.UnitNumber !='' && property.UnitNumber != null){unitnumber = property.UnitNumber+', '; }
                if(property.DisplayAddressOnInternet !="N"){address = unitnumber+''+property.address;}
                var content = '<div class="col-xs-6 custom-col-xs-6 item"><article class="hentry featured-property-post clearfix animated fade-in-left"><div class="property-thumbnail"><a href="/Details/' + property.MLS + '/' + address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><img class="img-responsive lazy" src="' + imgbg + '" data-src="' + imgbg + '" alt="' + property.address + '"></a><a href="/Details/' + property.MLS + '/' + address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><span class="property-status">For ' + property.SaleLease + '</span></a></div><div class="property-description"><header class="entry-header"><h4 class="entry-title"><a href="/Details/' + property.MLS + '/' + address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '" rel="bookmark">' + address + ', ' + property.Municipality + '</a></h4><div class="price-and-status"><span class="price"><sup class="price-curr">$</sup>' + property.listPriceDecimal.toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,") + '</span></div></header><div class="property-meta entry-meta clearfix"> <div class="meta-wrapper"><span class="meta-value">' + property.Bedrooms + '' + bplus + '</span><span class="meta-label"> Beds</span></div><div class="meta-wrapper"><span class="meta-value">' + property.Washrooms + '</span><span class="meta-label"> Baths</span></div><div class="meta-wrapper"><span class="meta-value">' + property.ParkingSpaces + '</span><span class="meta-label"> Parking</span></div></div></div></article></div>';


                $(sec).append(content);

            }
              lazyLoadInstance.update();
            loadmore(divid);
        } else {
             $(sec).append('<h4>No Listing Found.</h4>');

        }
}

function featurepropertyhome(divid,data) {
            var sec = '#filtercontainer';
    $('#' + divid).find('.bloader').css('display','none');
            if (data.length > 0) {
               
                 for (var i = 0; i < data.length; i++) {
                    var property = data[i];
                    var trebmask = '';
                     var unitnumber = '';
                     var blur = '';
                     var AskingPrice=property.listPrice;
        var pricesec='$';
                if(AskingPrice !=null){
                 pricesec='$'+ parseFloat(AskingPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                var bplus = '';
                var ohtag='';
                var exclusivetag='';
                if(property.BedroomsPlus !='' && property.BedroomsPlus != null){bplus = '+'+property.BedroomsPlus; }
                if(property.UnitNumber !='' && property.UnitNumber != null){unitnumber = property.UnitNumber+', '; }
                var statustagclass= 'property-status';
                var statustag = 'For '+property.SaleLease;
                var typeown1out = property.Typeown1out;
                var community = "";
                if(property.Community != null && property.Community !='' && property.Community!='---'){community = "in "+property.Community;}
                var address = '';
                     var imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,c-force';
                
                if(property.DisplayAddressOnInternet !="N"){address = "<p>"+unitnumber+""+property.address+", "+property.Municipality+"</p>";}
 if (typeown1out == "Semi-Detached"){typeown1out ='Semi Detached';}else if (typeown1out == "Att/Row/Twnhouse"){typeown1out='Townhouse';}else if (typeown1out == "Condo Apt"){typeown1out='Condo';}
                     var parking = String(property.GarageSpaces);
            if(parking !=null && parking !='' && parking != undefined){parking = parking.replace('.00','').replace('.0',''); }
                     if (property.OpenHouseDate1) {
                         if (new Date(property.OpenHouseDate1).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.OpenHouseDate2) {
                         if (new Date(property.OpenHouseDate2).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.OpenHouseDate3) {
                         if (new Date(property.OpenHouseDate3).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.oh1Start) {
                         ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'
                         if (new Date(property.oh1Start).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
                     if (property.oh2Start) {
                         if (new Date(property.oh2Start).setHours(0, 0, 0, 0) >= today) { ohtag = '<div class="openhouse-tag"><span>OPEN HOUSE</span ></div>'; }
                     }
        if((property.LastStatus == 'Sld' || property.LastStatus == 'Lsd')){
               statustagclass= 'property-sold-status';
               if(property.SaleLease == "Sale"){statustag = 'SOLD';}else{statustag = 'LEASED';}
               pricesec= statustag;
               }
                     if (au == '0' && property.Source != 'APOSOL' && property.Source != 'REMEX') {
                        
                         if (property.Status != "A" || (property.Status == "A" && property.IDX != 'Y')) {
                             blur = 'blur-on';
                             imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,bl-4,c-force';
                             if (property.Status == "A" && property.IDX != 'Y') {
                                 trebmask = '<div class="treb-mask"><span>Login Required</span></div>';
                             }
                           
                             address = '<p style="position: relative"><span class="blur-element">' + unitnumber + '' + property.address + ', ' + property.Municipality + '</span><a class="login-mask-tiny-left" href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '">Sign up or Log in to view</a></p>';
               
                                    }
                        }
                     if (property.Source == "APOSOL") { imgbg = '/GetPropertyImage/' + property.MLS + '/1/' + property.Source; }
                    
      if(property.Class=="Exclusive" && property.Status == "A"){exclusivetag='<div class="openhouse-tag"><span>'+property.Use+'</span></div>';}
         
                                  
                var propMetas='';
                 
                    if(property.PropertyType !="Commercial"){ propMetas='<div class="property-meta entry-meta clearfix '+blur+'"><div class="meta-wrapper"> <span class="meta-value">' + property.Bedrooms + '' + bplus + '</span> <span class="meta-label">Beds</span> </div><div class="meta-wrapper"> <span class="meta-value">' + property.Washrooms + '</span> <span class="meta-label">Baths</span> </div><div class="meta-wrapper"> <span class="meta-value">' + parking + '</span> <span class="meta-label">Garage</span> </div></div>';}
                    else { propMetas = '<div class="property-meta entry-meta clearfix ' + blur +'"> <div class="meta-wrapper"> <span class="meta-value">Property Type</span> <sub class="meta-unit">'+typeown1out+'</sub> </div></div>';}
                    
                     var content = '<div class="col-xs-6 custom-col-xs-12 col-sm-6 col-md-4 ' + property.Class + ' ' + property.SaleLease + ' item"><article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"><img class="img-responsive lazy" src="' + imgbg + '" data-src="' + imgbg + '" alt="' + property.address + '">' + trebmask + ' ' + exclusivetag + ' ' + ohtag+'</a> <a href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-") + '"><span class="' + statustagclass + '">' + statustag + '</span></a> </div><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="/Details/' + property.MLS + '/' + property.address.replace(" ", "-").replace(".", "-").replace("#", "-").replace("&", "-") + '"> '+typeown1out+' '+community+'</a></h4> <div class="price-and-status"><span class="price">' + pricesec+'</span></div></header>'+address+''+ propMetas +'</div></article></div>';

                    $(sec).append(content);
                   
                }
                  lazyLoadInstance.update();
               // loadmore(divid);
             filterlisting();
            } else {$('#'+divid).css('display','none');}
        };

function newdevpropertygrid(divid,data){
  
     var sec =  $('#'+divid).find('.row');
      $(sec).empty();
    $('#' + divid).find('.bloader').css('display', 'none');
   
     if (data.length > 0) {
         $('#resultcount').html(data.length);
                for (var i = 0; i < data.length; i++) {
                    var property = data[i];

                    var content = '<div class="col-xs-6 custom-col-xs-12 col-sm-6 col-md-4 item"> <article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="/Details/' + property.MLS + '/' + property.Style.replace(" ", "-").replace(".", "-") + '"><img class="img-responsive lazy" src="/GetPropertyImage/' + property.MLS + '/1/' + property.Source + '" data-src="/GetPropertyImage/' + property.MLS + '/1/' + property.Source + '" alt="' + property.address + '"></a> <a href="/Details/' + property.MLS + '/' + property.Style.replace(" ", "-").replace(".", "-") + '"><span class="property-status">' + property.SaleLease + '</span></a> </div><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="/Details/' + property.MLS + '/' + property.Style.replace(" ", "-").replace(".", "-").replace("&", "-") + '">'+property.Style+'</a></h4> <div class="price-and-status"><span class="price">By '+property.listbrokerage+'</span> </div></header> <p>'+property.address+', '+property.Municipality+'</p></div></article> </div>';
                    $(sec).append(content);
       
                }
        loadmore(divid);
            } else {
                $('#'+divid).css('display','none');
            }
    
}
function elasticnewdevpropertygrid(divid, data) {
    
    var sec = $('#' + divid).find('.listings_wrapper');
        $(sec).empty();
        $('#' + divid).find('.bloader').css('display', 'none');
        if (data.length > 0) {
            $('#resultcount').html(data.length);
            for (var i = 0; i < data.length; i++) {
                var property = data[i]['_source'];
                var imgbg = 'https://gallery.remarketer.ca/' + property.Source + '/' + property.MLS + '-1.jpg?tr=di-propertynoimage_pj5ksb5iM.jpg,w-360,h-270,c-force';
                var content = '<div class="col-xs-6 custom-col-xs-12 col-sm-6 col-md-4 item"> <article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="/Details/' + property.MLS + '/' + property.Style.replace(" ", "-").replace(".", "-") + '"><img class="img-responsive lazy" src="' + imgbg + '" data-src="' + imgbg + '" alt="' + property.Address + '"></a> <a href="/Details/' + property.MLS + '/' + property.Style.replace(" ", "-").replace(".", "-") + '"><span class="property-status">' + property.SaleLease + '</span></a> </div><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="/Details/' + property.MLS + '/' + property.Style.replace(" ", "-").replace(".", "-").replace("&", "-") + '">' + property.Style + '</a></h4> <div class="price-and-status"><span class="price">By ' + property.ListBrokerage + '</span> </div></header> <p>' + property.Address + ', ' + property.Municipality + '</p></div></article> </div>';
                $(sec).append(content);

            }
            loadmore(divid);
        } else {
            $('#' + divid).css('display', 'none');
        }

    }

function buildifypropertygrid(divid, data) {
   
    var sec = $('#' + divid).find('.listings_wrapper');
    $(sec).empty();
    $('#' + divid).find('.bloader').css('display', 'none');
    if (data.length > 0) {
        $('#resultcount').html(data.length);
        for (var i = 0; i < data.length; i++) {
            var property = data[i];

            var minPrice;
            var maxPrice;
            var pricesec = "Contact for Pricing";
            if (property.startPrice && property.endPrice) {
                if (property.startPrice != null) {
                    minPrice = '$' + parseFloat(property.startPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                if (property.endPrice != null) {
                    maxPrice = '$' + parseFloat(property.endPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                pricesec = minPrice + "-" + maxPrice;
            }
            var state = property.state;
            var province = "on";
            if (state === "British Columbia") {
                province = "bc";
            } else if (state === "Quebec") {
                province = "qc";
            } else if (state === "Alberta") {
                province = "ab";
            } else if (state === "Manitoba") {
                province = "mb";
            } else if (state === "Saskatchewan") {
                province = "sk";
            } else if (state === "Nova Scotia") {
                province = "ns";
            } else if (state === "New Brunswick") {
                province = "nb";
            } else if (state === "Newfoundland and Labrador") {
                province = "nl";
            } else if (state === "Prince Edward Island") {
                province = "pe";
            } else if (state === "Northwest Territories") {
                province = "nt";
            } else if (state === "Yukon") {
                province = "yt";
            } else if (state === "Nunavut") {
                province = "nu";
            }
            var sanitizedPropertyName = property.name.replace(/[^a-zA-Z0-9\s]/g, "-");
            var propertylink = '/precon/' + property.listingId + '/' + province + '/' + sanitizedPropertyName;
            var imgbg = property.coverPhoto.url;
            var fullAddress = property.streetNumber + " " + property.streetName + " " + property.cityOrDistrict + " " + property.state;
           

            var propMetas = '<div class="property-meta entry-meta clearfix"><div class="meta-wrapper"> <span class="meta-value">' + property.minBeds + '-' + property.maxBeds + '</span> <span class="meta-label">Beds</span> </div><div class="meta-wrapper"> <span class="meta-value">' + property.minSize + '-' + property.maxSize + ' SqFt </span><span class="meta-label">Size Range</span> </div></div></div>';
        
            var content = '<div class="col-xs-6 custom-col-xs-12 col-sm-6 col-md-4 item"><article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="' + propertylink + '"><div style="background: url(' + imgbg + ') no-repeat center center; background-size: cover; width: 100%; height: 410px; position:relative;"><div class="openhouse-tag"><span>' + property.sellingStatus + '</span></div> <span class="property-status">' + property.constructionStatus + '</span></div> </div></a><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="' + propertylink + '"> ' + property.name + '</a></h4> <div class="price-and-status"><span class="price">' + pricesec + '</span></div></header>' + fullAddress + '' + propMetas + '</div></article></div>';
            $(sec).append(content);

        }
        loadmore(divid);
    } else {
        $('#' + divid).css('display', 'none');
    }

}

function buildifypropertycarousel(divid, data) {

    var sec = $('#' + divid).find('.listings_wrapper');
    $(sec).empty();
    $('#' + divid).find('.bloader').css('display', 'none');
    if (data.length > 0) {
        $('#resultcount').html(data.length);
        for (var i = 0; i < data.length; i++) {
            var property = data[i];

            var minPrice;
            var maxPrice;
            var pricesec = "Contact for Pricing";
            if (property.startPrice && property.endPrice) {
                if (property.startPrice != null) {
                    minPrice = '$' + parseFloat(property.startPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                if (property.endPrice != null) {
                    maxPrice = '$' + parseFloat(property.endPrice).toFixed().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                pricesec = minPrice + "-" + maxPrice;
            }


           
            var state = property.state;
            var province = "on";
            if (state === "British Columbia") {
                province = "bc";
            } else if (state === "Quebec") {
                province = "qc";
            } else if (state === "Alberta") {
                province = "ab";
            } else if (state === "Manitoba") {
                province = "mb";
            } else if (state === "Saskatchewan") {
                province = "sk";
            } else if (state === "Nova Scotia") {
                province = "ns";
            } else if (state === "New Brunswick") {
                province = "nb";
            } else if (state === "Newfoundland and Labrador") {
                province = "nl";
            } else if (state === "Prince Edward Island") {
                province = "pe";
            } else if (state === "Northwest Territories") {
                province = "nt";
            } else if (state === "Yukon") {
                province = "yt";
            } else if (state === "Nunavut") {
                province = "nu";
            }
            var sanitizedPropertyName = property.name.replace(/[^a-zA-Z0-9\s]/g, "-");
            var propertylink = '/precon/' + property.listingId + '/' + province + '/' + sanitizedPropertyName;
            var imgbg = property.coverPhoto.url;
            var fullAddress = property.streetNumber + " " + property.streetName + " " + property.cityOrDistrict + " " + property.state;


            var propMetas = '<div class="property-meta entry-meta clearfix"><div class="meta-wrapper"> <span class="meta-value">' + property.minBeds + '-' + property.maxBeds + '</span> <span class="meta-label">Beds</span> </div><div class="meta-wrapper"> <span class="meta-value">' + property.minSize + '-' + property.maxSize + ' SqFt </span><span class="meta-label">Size Range</span> </div></div></div>';

            var content = '<div class="item"><article class="hentry property-listing-three-post image-transition"> <div class="property-thumbnail"> <a href="' + propertylink + '"><div style="background: url(' + imgbg + ') no-repeat center center; background-size: cover; width: 100%; height: 410px; position:relative;"><div class="openhouse-tag"><span>' + property.sellingStatus + '</span></div> <span class="property-status">' + property.constructionStatus + '</span></div> </div></a><div class="property-description"> <header class="entry-header"> <h4 class="entry-title"><a href="' + propertylink + '"> ' + property.name + '</a></h4> <div class="price-and-status"><span class="price">' + pricesec + '</span></div></header>' + fullAddress + '' + propMetas + '</div></article></div>';
            $(sec).append(content);

        }
        initcarousel(divid);
    } else {
        $('#' + divid).css('display', 'none');
    }

}
$('#sort-properties,#salelease-properties').on('change', function () {
    filter();
});

function getPropertyData(item) {
    return item._source || item; // If _source exists, use it, otherwise use the item itself
}


function filter() {
    var sl = $('#salelease-properties').val();
    var s = $('#sort-properties').val();
    var prop = 'ListPrice'; // The property to sort by, adjust as needed
    //var propertiesListfilter;

    if (sl === 'default' || sl === '') {
       
        propertiesListfilter = propertiesList.slice(); // Create a shallow copy to avoid modifying the original array
    } else {
        propertiesListfilter = propertiesList.filter(function (item) {
            var data = getPropertyData(item);
            return sl === '' || data.SaleLease === sl;
        });
    }

    if (s !== '') {
        propertiesListfilter.sort(function (a, b) {
            var dataA = getPropertyData(a);
            var dataB = getPropertyData(b);
            var valueA = Number(dataA[prop] || 0); 
            var valueB = Number(dataB[prop] || 0);

            if (s === 'Lo-Hi') {
                return valueA - valueB;
            } else {
                return valueB - valueA;
            }
        });
    }
    sortlistings(); 
}


function sortlistings(){
    var whichdiv = $('.allitems').parent().parent().attr('id');
    if ($('#' + whichdiv).hasClass('agent-listings')) { featurepropertygrid(whichdiv, propertiesListfilter); }
    else if ($('#' + whichdiv).hasClass('featured-listings')) { elasticpropertylargegrid(whichdiv,'', propertiesListfilter); }
    else if ($('#' + whichdiv).hasClass('brokerage-listings')) { elasticpropertygrid(whichdiv, propertiesListfilter); }
    else if ($('#' + whichdiv).hasClass('newdev-listings')) { newdevpropertygrid(whichdiv, propertiesListfilter); }
    else {  propertygrid(whichdiv, propertiesListfilter);}
    
}
 function loadmore(divid){
 var lm = $('#' + divid).find('.allitems');
 $('#' + divid).find('.loadmore').remove();
 $(lm).simpleLoadMore({
		item: '.item',
		count:12,
		btnHTML: '<a href="#" class="btn-default btn-prime btn-full loadmore" lang="en">Load More <i class="fa fa-angle-down"></i></a>'
	});

};
function filterlisting() {
    var $container = $('#filtercontainer');
    if ($container.length === 0) {
        console.log('#filtercontainer does not exist.');
        return; // Exit the function if the element does not exist
    }

    $container.imagesLoaded(function () {
        $container.isotope({
            filter: '*',
            animationOptions: {
                duration: 750,
                easing: 'linear',
                queue: false
            }
        });
    });
    $('#filters a').click(function () {
        $('#filters .current').removeClass('current');
        $(this).addClass('current');

        var selector = $(this).attr('data-filter');
        $container.isotope({
            filter: selector,
            animationOptions: {
                duration: 750,
                easing: 'linear',
                queue: false
            }
        });
        return false;
    });
}

function initcarousel(d) {
    var sec = $('#' + d).find('.listings_wrapper');
    var carouselNext = $('#' + d).find(".carousel-next-item"),
        carouselPrev = $('#' + d).find(".carousel-prev-item");
    sec.owlCarousel({
        'dots': false,
        'margin': 30,
        'responsive': {
            0: {
                'items': 1
            },
            600: {
                'items': 1,
                'stagePadding': 30
            },
            900: {
                'items': 2,
                'stagePadding': 30
            },
            1200: {
                'items': 3,
                'stagePadding': 0
            },
            1600: {
                'items': 3,
                'stagePadding': 0
            }
        },
       
        'checkVisible': false,
        'smartSpeed': 600
        
    });

    carouselNext.on('click', function (event) {
        sec.trigger('next.owl.carousel');
        event.preventDefault();
    });

    carouselPrev.on('click', function (event) {
        sec.trigger('prev.owl.carousel');
        event.preventDefault();
    });

}
    