// JavaScript Document

/*
 * Original Author: Mamaevsky Vasily
 */
 
function Abracadabra(min_item_w, left_part_width, s_teaser) {
	var stretch = 1.02;

	var s_teasers 			= $('.related_goods .teaser').css('width', stretch * 100 + '%');
	var s_teasers_holder 	= $('.related_goods .catalog.level2');
	var _window 			= $('#left_part');
	
	var window_w = _window.width();
	
	var window_w_tmp = 0;
	var items = 0;
	var items_tmp = 0;
	
	var wrap_tag = [];
	
	function _init() {
		$(window).resize(function(){
			window_w = _window.width();
			items_tmp = Math.floor( ( window_w -left_part_width ) / min_item_w);
			
			if (items_tmp != items) {				
				if (items_tmp > 0) items = items_tmp;
				new_w = 100 / items / stretch; 
				new_w = new_w.toFixed(3);
			
				s_teaser.css('width', new_w + '%');				
				
				s_teasers_holder.each( function(i) { 
					id = $(this).attr('id');
					var items_num = $(".teaser", this).length;
					$("."+id+"_wrapped").unwrap();
					$("#"+id+" .teaser").removeClass(id+"_wrapped");
					if( new_w < 20 ) { // 5 in row 
						$("#"+id+" .teaser").each( function(index) { 
							if( index > 4 )	{
								$(this).addClass( id+"_wrapped" );
							}
						} );
					} else {
						$("#"+id+" .teaser").each( function(index) { 
							if( index > 3 )	{ // 4 in row
								$(this).addClass( id+"_wrapped" );
							}
						} );
					}

					if( $("#sb"+(i+1)).hasClass("pact") ) { 
						wrap_tag[i] = '<div class="slide_block show" id="_sb'+(i+1)+'"></div>';
					} else {
						wrap_tag[i] = '<div class="slide_block" id="_sb'+(i+1)+'"></div>';
					}
					$("."+id+"_wrapped").wrapAll(wrap_tag[i]);
				} );
			}
		});
		$(window).resize();
	}

	return {
		init: _init
	}
}

jQuery(function(){
	var ruberTeasers = new Abracadabra(154, 0, $('.related_goods .teaser'));
	ruberTeasers.init();
});


