/*
требование скрипта — подключённый jQuery.
Пример:

		<script src="/js/set-height.js"></script>
<div id="merch"       class="js-eqheight" data-eqh-block="div.tovar" data-eqh-what="div.fotot;div.m4">

Сначала подключается скрипт (можно и в подвале страницы).
Нам нужно отравнять по высоте товары, содержащиеся вот в теге <div id="merch"

потому дописываем к нему:
class="js-eqheight" — это покажет что здесь есть что выравнивать
data-eqh-block="div.tovar" — атрибут определяет какие блоки внутри нужно подравнять. В данном случае это CSS-селектор div'а товара.

Теперь нужно указать засчёт чего этот блок товара должен выравняться. Это div содержащий картинку и текст. Указываются CSS-селекторами, через точку с запятой:
data-eqh-what="div.fotot;div.m4"

в такой комбинации скрипт внутри <div id="merch"       class="js-eqheight"...>
найдёт все блоки data-eqh-block="div.tovar"
и выравняет их засчёт выравнивания содержимого: what="div.fotot;div.m4"
*/




/** Go through `items` and find `block_selector` inside.
 * Measure their contents' height, pick the max one and apply the same height to all of them
 * @param {Array}	items		Array of Nodes to measure
 * @param {String}	selector	jQuery selector that finds the block
 * @return {Number} The measured common height
 */
function equalize_height(items, selector){
	var items_N = items.length;
	var blocks = [];
	// Determine max height
	var max_height = 0;
	for (var i = 0; i<items_N; i++){
		var item = $(items[i]);
		blocks[i] = item.find(selector);
		var height = 0;
		blocks[i].children().each(function(){
			height += $(this).outerHeight();
			});
		if (height>max_height)
			max_height = height;
		}
		// HACK: floats
		if (selector == 'dl.properties')
			max_height = Math.ceil(max_height/1.95);
	// Apply height
	if (height>0)
		for (var i = 0; i<items_N; i++)
			blocks[i].css({
						'height': max_height+'px',
						'min-height': max_height+'px'
						});
	return max_height;
	}

/** Split an array of Nodes into pieces that appears to be in one row (in a line)
 * @param {Array}		all_items	An array of Nodes
 * @param {Function}	callback	function(row) that will handle the detected row
 */
function row_detection(all_items, callback){
	var last_y = 0;
	var row = [];
	for (var i=all_items.length-1; i>=-1; i--){ // Go backwards; otherwise, height-changes will influence 'y'!
		var y = (i==-1)? null : $(all_items[i]).position().top;
		if (y !== last_y){
			callback(row);
			row = [];
			}
		last_y = y;
		if (i != -1)
			row.push(all_items[i]);
		}
	}

// Detect products that are in a line && equalize their heights
//$(window).load(function(){ // We can't use `.ready()` here because the images are not loaded (document.readyState != 'complete')
//	row_detection($('div.tovar'), function(row){
//		equalize_height(row, 'div.fotot');
//		equalize_height(row, 'div.m4');
//		});
//	});

$(window).load(function(){
	$('.js-eqheight').each(function(){
			var $this = $(this);
			var sets = {
					blockSel: $this.attr('data-eqh-block'),
					what: $this.attr('data-eqh-what').split(';')
					};
			row_detection( $this.find(sets.blockSel), function(row){
					for (var i=0; i<sets.what.length; i++)
						equalize_height(row, sets.what[i]);
					});
			});
	});
