$(document).ready(function () {
    let card = $('.product-card');
    let currentRowCount = 3;
    
    if (window.innerWidth < 992) {
        currentRowCount = 2;
    }
    
    function cardsContent(itemsInRow) {
        revealAll(card, ['.product-card__price__old-price',
                                    '.product-card__price-sqm',
                                    '.product-card__price-value']);
        
        let rows = Math.ceil(card.length / itemsInRow);
        
        for ( let i = 0 ; i < rows ; i++ ) {
            let currentRow = card.slice(i * itemsInRow, i * itemsInRow + itemsInRow);
            
            hideEmptiness(currentRow, '.product-card__price__old-price');
            hideEmptiness(currentRow, '.product-card__price-sqm');
            hideEmptiness(currentRow, '.product-card__price-value');
            
            fixHeaders(currentRow, '.product-card__title-v2');
        }
    }
    
    function hideEmptiness(query, className) {
        let currentQuery = query.find(className);
        let rowContent = currentQuery.text();
        if (rowContent.length === query.length) {
            currentQuery.hide();
        }
    }
    
    function revealAll(query, classNames) {
        for ( let i = 0 ; i < classNames.length ; i++) {
            query.find(classNames[i]).show();
        }
    }
    
    function fixHeaders(query, className) {
        let currentQuery = query.find(className);
        currentQuery.parent().removeClass('product-card__header-r1 product-card__header-r2 product-card__header-r3');
        let rowHeight = [];
        for (let i = 0 ; i < currentQuery.length; i++ ) {
            rowHeight[i] = currentQuery.eq(i).height() / parseInt(currentQuery.eq(i).css('line-height'));
        }
        let rows = Math.max.apply(null, rowHeight);
        currentQuery.parent().addClass('product-card__header-r' + Math.round(rows));
    }
    
    cardsContent(currentRowCount);
    
    $(window).on('resize', _.debounce(function () {
        //  "render" again if our screen resolution changed
        if (window.innerWidth < 992) {
            currentRowCount = 2;
        } else {
            currentRowCount = 3;
        }
        cardsContent(currentRowCount);
    }, 200));
});
