function random(min,max) {
	var range = max - min;
	var n = Math.floor(Math.random()*range) + min;
	return n;
}

compactGallery = {};
compactGallery.count = 0;

compactGallery.coords_mas = {top:0,left:0};

//создает надписи в нужном месте или перемещает если уже созданы
compactGallery.create_and_move_label = function() {
	$('.compact_gallery').each(function() {
		
		//размеры превьюшек берем из тега обрамляющего галерею, атрибут preview_size='..x..'
		var temp = explode('x', $(this).attr('preview_size'));
		compactGallery.preview_width = temp[0];
		compactGallery.preview_height = temp[1];
		
		$(this).find('img').each(function() {
			//нумеруем тег img или берем его номер если есть
			if(compactGallery.isCreateLabel) {
				var nomer = $(this).attr('nomer');
			}
			else {
				//нумеруем тег, чтобы знать номер его текста и дымки
				$(this).attr('nomer', compactGallery.count);
				var nomer = compactGallery.count;
				compactGallery.count ++;
			}
			
			
			var text = $(this).attr('alt');
			var image_url = $(this).attr('src');
			
			var temp = explode('/', text);
			text_small = temp[0];
			
			image_url = image_url.replace('small', 'big');
			image_url += '?'+random(1000,90000); //чтобы заново загружал а не из кеша брал
			
			var width = compactGallery.preview_width;
			var height = compactGallery.preview_height;
			var left = $(this).offset().left;
			var top = $(this).offset().top;
			
			//в ie почему-то координаты ошибочны на 2 px, исправляем
			if(isMSIE && !isMSIE8) {
				left -=2;
				top -= 2;
			}
			
			//устанавливаем размер картинок в сам тег img
			//$(this).css({width:width+'px', height:height+'px'});
			
			/* ВЕРСИЯ С ПОЛНОЙ ДЫМКОЙ
			$(this).after(
				'<div class="cg_dymka" style="width:'+width+'px; height:'+height+'px; left:'+left+'px; top:'+top+'px; "></div>'+
				'<div class="cg_text" style="width:'+width+'px; height:'+height+'px; left:'+left+'px; top:'+top+'px; ">'+
					'<table cellpadding="0" cellspacing="0" style="width:100%;height:100%">'+
					'<tr valign="bottom"><td>'+text+
					'</table>'+
				'</div>'
				);
			*/
			
			/*width -= 2;
			left += 1;
			top +=1;*/
			
			//ВЕРСИЯ С ДЫМКОЙ ТОЛЬКО ПОД ТЕКСТОМ
			//создаем дымку если не создана
			if(!compactGallery.isCreateLabel) {
				$(this).after(
					'<div class="cg_dymka" id=cg_dymka_'+nomer+' style="width:'+width+'px; height:'+height+'; left:'+left+'px; top:'+top+'px; -moz-opacity:0.8; filter:alpha(opacity=80); opacity:0.8;"></div>'+
					'<div class="cg_text"  id=cg_text_'+nomer+' style="width:'+width+'px; left:'+left+'px; top:'+top+'px; ">'+
						'<table cellpadding="0" cellspacing="0" width="100%" height="100%">'+
						'<tr valign="middle"><td>'+text_small+'<div class="zoom"><u>увеличить</u></div>'+
						'</table>'+
					'</div>'+
					'<a class="cg_link" id=cg_link_'+nomer+' href="'+image_url+'" target="_blank" preview=1 style="width:'+width+'px; height:'+height+'; left:'+left+'px; top:'+top+'px; "><img src="/i/space.gif" class="cj_space" width='+width+' height='+height+'></a>'
					);
				
				//растягиваем дымку чтобы она полностью покрывала пространство под текстом
				/*text_height = $('#cg_text_'+nomer).height();
				$('#cg_dymka_'+nomer).css({height:text_height+'px'});
				*/
				
				//события для появления и пропадания текста
				$('#cg_link_'+nomer).bind('mouseover', {count:nomer}, function(e) {
					$('#cg_dymka_'+e.data.count).fadeIn(150);
					$('#cg_text_'+e.data.count).fadeIn(150);
				});
				$('#cg_link_'+nomer).bind('mouseout', {count:nomer}, function(e) {
					$('#cg_dymka_'+e.data.count).fadeOut(150);
					$('#cg_text_'+e.data.count).fadeOut(150);
				});
			}
			//если дымка существует, просто передвигаем ее и надпись
			else {
				//console.log(nomer);
				
				$('#cg_dymka_'+nomer).css({left:left, top:top});
				$('#cg_text_'+nomer).css({left:left, top:top});
				$('#cg_link_'+nomer).css({left:left, top:top});
			}
		});
	});
	
	compactGallery.isCreateLabel = true;
}


//формируем надписи на картинках
$(document).ready(function() {	compactGallery.coords_mas = $('.compact_gallery').position();	compactGallery.create_and_move_label();
});

/*
//перемещаем надписи если изменился размер экрана
$(window).bind('resize', function() {
	compactGallery.coords_mas = $('.compact_gallery').position();
	compactGallery.create_and_move_label();
});*/

//Отслеживает, не сместились ли фотографии в результате загрузки другого контента и если сместились, перемещает надписи
//Ограничение! Нельзя использовать несколько блоков картинок.
setInterval('compactGallery_check_position()', 1000);
compactGallery_check_position = function() {
	var new_coords = $('.compact_gallery').position();
	if(compactGallery.coords_mas['top'] != new_coords['top'] || 
		compactGallery.coords_mas['left'] != new_coords['left']
	) {
		console.log(new_coords);
		compactGallery.coords_mas = new_coords;
		compactGallery.create_and_move_label();
	}
}