$(function(){

	_typeface_js.renderDocument();
	
	wrapperBoxesWith = 960;
	
	if($(window).width() >= 1320)
	{
		wrapperBoxesWith = 1320;
		$("div#wrapper_boxes").css("width", "1280px");
	}
	
	var $items = $("#wrapper_boxes");
	$items.masonry({
			itemSelector: ".box"
		,	columnWidth: 320
	});
	
	$(window).resize(function() {
		if($(window).width() >= 1320 && wrapperBoxesWith == 960)
		{
			$("div#wrapper_boxes").css("width", "1320px");
			wrapperBoxesWith = 1320;
			$items.masonry({
					itemSelector: ".box"
				,	columnWidth: 320
			});
		}
		else if($(window).width() <= 1320 && wrapperBoxesWith == 1320)
		{
			$("div#wrapper_boxes").css("width", "960px");
			wrapperBoxesWith = 960;
			$items.masonry({
					itemSelector: ".box"
				,	columnWidth: 320
			});
		}
	});
	
	function getMoreData(iDataCounter)
	{
		
		var iAmountLoops = 5;
		var iStartValue = (iDataCounter*5);
		
		$.ajax({
				url: remoteurl+"?itemstart="+iStartValue
			,	async: false
			,	cache: false
			,	success: function(data) {
				
					aSplittedElements = data.split("!!---------------------!!");
					
					var newEls = [];
					$.each(aSplittedElements, function(key, value)
					{
						$box = $(value);
						newEls.push($box[0]);
					});
					
					$boxes = $(newEls);
					$items.append($boxes);
					_typeface_js.renderDocument();
					$items.masonry({appendedContent: $boxes})
					
					$("div#loading-box").animate({opacity: .8},800).fadeOut('normal');
				}
		});
		
	}
	
	var iDataCounter = 0;
	$(window).scroll(function(){
		
		function pausecomp(millis)
		 {
		  var date = new Date();
		  var curDate = null;
		  do { curDate = new Date(); }
		  while(curDate-date < millis);
		}

		
		if("none" != $("div#loading-box").css("display"))
		{
			sHeight = $(window).height()+$(window).scrollTop();
			sWidth = $(window).width();
			$("div#loading-box").css("top", sHeight-120);
		}
		
		if  ($(window).scrollTop() == $(document).height() - $(window).height())
		{
			if(iDataCounter < iAmountPages)
			{
				$("div#loading-box").animate({opacity: .8},100).fadeIn("normal");
				sHeight = $(window).height()+$(window).scrollTop();
				sWidth = $(window).width();
				$("div#loading-box").css("top", sHeight-120).css("left", (sWidth/2)-100);
				
				var func = function afterPauze()
				{
					iDataCounter = iDataCounter+1;
					getMoreData(iDataCounter);
				}
				setTimeout(func, 1000);
				
			}
		}
	});
	
});
