(function($){
	
	function getTgbData(count, callback){
		$.getJSON("/ad/tgb-set/", {num: count}, callback);
	}

	$(function(){
		var tgdNavBlocks = $('#left_menu .tgd-block'),
			count = tgdNavBlocks.size(),
			template = '<a target="_blank" href="{#url#}"><img width="60" height="60" alt="" src="{#image#}"><span>{#text#}</span></a>';
		
		if(count > 0)
			getTgbData(count, 
				function(response) {
					
					if(!response.tgbs.length) return;
				
					tgdNavBlocks.each(function(index){
						
						if(index < response.tgbs.length)
							$(this).html(template
											.replace('{#url#}', response.tgbs[index].link)
											.replace('{#image#}', response.tgbs[index].image)
											.replace('{#text#}', response.tgbs[index].text));
					});
				
			});
		
			var tgbBaseBlocks = $('.central_part .tgd-block_row'),
				count = tgbBaseBlocks.size(),
				templateBase = '<span class="tgd-block"><a target="_blank" href="{#url#}"><img width="60" height="60" alt="" src="{#image#}"><span>{#text#}</span></a></span>';
			
			var blockNum = 0,
				isStubAppended = false;
			
			if(count > 0)
				getTgbData(6,
					function(response) {
						
						var tgbCount = response.tgbs.length;
						
						tgbBaseBlocks.each(function(){
							
							for(var i = 0; i<3; i++){
							
								if(blockNum < tgbCount){
									
									$(this).append($(templateBase
														.replace('{#url#}', response.tgbs[blockNum].link)
														.replace('{#image#}', response.tgbs[blockNum].image)
														.replace('{#text#}', response.tgbs[blockNum].text)));
								}else if(response.stubs.length && tgbCount < 2 && !isStubAppended){
									
									isStubAppended = true;
									
									$(this).append($(templateBase
														.replace('{#url#}', response.stubs[blockNum - tgbCount].link)
														.replace('{#image#}', response.stubs[blockNum - tgbCount].image)
														.replace('{#text#}', response.stubs[blockNum - tgbCount].text)));
								}
								
								blockNum++;
							}
							
							
						});
					
						var isShifted = false;
						
						function tgbBlockShift(){
							if(tgbBaseBlocks.size() < 4) return;
							
							var windowWidth = $(window).width();
							
							if(windowWidth >= 1280 && !isShifted){
								$('.tgd-block_row_top').append($('.tgd-block_row_bottom .tgd-block:last-child')).addClass('tgd-block_row_shrink');
								isShifted = true;
							}
							else if(windowWidth < 1280 && isShifted){
								$('.tgd-block_row_bottom').append($('.tgd-block_row_top .tgd-block:last-child'));
								$('.tgd-block_row_top').removeClass('tgd-block_row_shrink');
								isShifted = false;
							}
								
						}
						
						tgbBlockShift();
						
						$(window).bind('resize', tgbBlockShift)
					});
		
	});

})(jQuery);
