jQuery(document).ready(function($){
	
	var preloadedItems = null;
	var preloadedEnd = true;
	
	// manage scroll event
	$(window).scroll(function(){
		if(pixelFromBottom() === 0 && globalOtherPostsToLoad === 1){
			//$("#content").animate({height: "+=200px"}, 500, 'linear', function() {
				
				var scrollbottom = $(document).height() - $(window).height() + 10;
				$('html, body').animate( {scrollTop : scrollbottom }, 1000);
			
				var actualWidth = (!$.browser.opera) ? getDocumentWidth() : getWindowWidth();
				var loadedPosts = getLoadedPosts();
				var postsPerRow = getPostsPerRow(actualWidth, globalPostWidth, 149);
				if (loadedPosts > 0 && actualWidth === globalWidth) {
					if (preloadedItems == null) { 
						appendPosts(loadedPosts, postsPerRow, 0); 
					}
					else {
						$("#loader").css("visibility","visible");
						if (preloadedEnd) {
							appendData(preloadedItems);
							preloadedItems = null;
						}
						$("#loader").css("visibility","hidden");
					}
				}
				//return false;
			//});
		}
	});
					
	// manage resize event
	$(window).resize(function() {
	
		preloadedItems = null;
	
		var actualWidth = (!$.browser.opera) ? getDocumentWidth() : getWindowWidth();
		if (actualWidth !== globalWidth && globalOtherPostsToLoad === 1) {
			globalWidth = actualWidth;
			var loadedPosts = getLoadedPosts();
			var postsPerRow = getPostsPerRow(actualWidth, globalPostWidth, 149);
			if ((loadedPosts % postsPerRow) !== 0) { 
				appendPosts(loadedPosts, postsPerRow, 1); 
			}
		}
		var actualWindowHeight = getWindowHeight();
		if (actualWindowHeight !== globalWindowHeight) {
			var loadedPosts2 = getLoadedPosts();
			var postsPerRow2 = getPostsPerRow(globalWidth, globalPostWidth, 149);
			if (actualWindowHeight > (Math.ceil(loadedPosts2 / postsPerRow2) * 272)) {
				appendPosts(postsPerRow2 * Math.ceil(loadedPosts2 / postsPerRow2), postsPerRow2, 0);
				globalWidth = (!$.browser.opera) ? getDocumentWidth() : getWindowWidth();
			}
			globalWindowHeight = actualWindowHeight;
			if (fixed && actualWindowHeight < domHeader.height() + domSidebar.height()) {
				domLogo.css("position","absolute");
				domSidebar.css("position","absolute");
				if ($("#control").length) {
					var oldControl = $("#control");
					var newControl = oldControl.clone();
					oldControl.remove();
					domSidebar.before(newControl);
					$("#control").css("position","absolute");
				}
				fixed = false;
			}
			if (!fixed && actualWindowHeight >= domHeader.height() + domSidebar.height()) {
				domLogo.css("position","fixed");
				domSidebar.css("position","fixed");
				if ($("#control").length) {
					var oldControl = $("#control");
					var newControl = oldControl.clone();
					oldControl.remove();
					domSidebar.prepend(newControl);
					$("#control").css("position","fixed");
				}
				fixed = true;
			}
		}
	});
		
	/* START Functions definitions */
	function getDocumentWidth() { return $(document).width(); }
	function getDocumentHeight() { return $(document).height(); }
	function getWindowWidth() { return $(window).width(); }
	function getWindowHeight() { return $(window).height(); }
	function getPostBoxWidth() { return 268; }
	function getLoadedPosts() { return $("div.post", "#content").length; }
	function getPostsPerRow(browserWidth, postWidth, offset) { return Math.floor((browserWidth - offset) / postWidth); }
	function pixelFromBottom() { return (0 + getDocumentHeight() - (document.documentElement.scrollTop || document.documentElement.ownerDocument.body.scrollTop) - $(window).height()); }

	// se type 0 carica una riga di articoli, altrimenti riempe la riga corrente
	function appendPosts(loadedPosts,postsPerRow,type) {
		if ($.browser.msie) {
			if (globalFixDoubleAppend === true) {
				globalFixDoubleAppend = false;
				$("#loader").css("visibility","visible");
				$.post(globalLoadingURL, {
					from: loadedPosts,
					n: postsPerRow,
					t: type
				//}, function(data) { appendData(data); });
				}, function(data) { 
					appendData(data); 
					preloadedEnd = false;
					$.post(globalLoadingURL, {
						from: parseInt(parseInt(loadedPosts)+parseInt(postsPerRow)) ,
						n: postsPerRow,
						t: type
					}, function (data) { preloadedItems = data; preloadedEnd = true; });
				});
			}
		}
		else {
			$.ajax({
				url: globalLoadingURL,
				data: {
					from: loadedPosts,
					n: postsPerRow,
					t: type
				},
				type: "POST",
				async: false,
				cache: false,
				beforeSend: function() { $("#loader").css("visibility","visible"); },
				success: function(data) {
					if (!$.browser.opera) { appendData(data); }
					else {
						$("#loader").css("visibility","hidden");
						var dataToAppend = data;
						if (parseInt(data) == 0 || (jQuery.trim(data)).length == 0) {
							globalOtherPostsToLoad = 0;
							$(window).unbind('scroll');
							if (parseInt(data) == 0) {
								dataToAppend = jQuery("<div>No more posts to load</div>").attr("id","loading-end");
							}
						}
						domContent.append(dataToAppend); 
						globalFixDoubleAppend = true;
					}
					preloadedEnd = false;
					$.ajax({
						url: globalLoadingURL,
						data: {
							from: parseInt(parseInt(loadedPosts)+parseInt(postsPerRow)),
							n: postsPerRow,
							t: type
						},
						type: "POST",
						async: false,
						cache: false,
						success: function(data) { preloadedItems = data; preloadedEnd = true;}
					});	
				}
			});
		}
	}
		
	function appendData(data) {
		$("#loader").css("visibility","hidden");
		var dataToAppend = data;
		if (parseInt(data) == 0 || (jQuery.trim(data)).length == 0) {
			globalOtherPostsToLoad = 0;
			$(window).unbind('scroll');
			if (parseInt(data) == 0) {
				dataToAppend = jQuery("<div>No more posts to load</div>").attr("id","loading-end");
			}
		}
		domContent.append(dataToAppend); 
		globalFixDoubleAppend = true;
	}
	/* END functions definition */
	
	/* START "main" */
	$.preloadCssImages();
	
	domSidebar = $("#sidebar");
	domHeader = $("#header");
	domLogo = $("#header>h1");
	domContent = $("#content");
	globalWindowHeight = getWindowHeight();
	globalDocumentHeight = getDocumentHeight();
	globalWidth = (!$.browser.opera) ? getDocumentWidth() : getWindowWidth();
	globalPostWidth = getPostBoxWidth();
	globalOtherPostsToLoad = 1;
	globalFixDoubleAppend = true;
	
	$(document).scrollTop(0);
	//if($.browser.msie && $.browser.version == "6.0") {
	if($.browser.msie && window.XMLHttpRequest == undefined && ActiveXObject != undefined) {
		domSidebar.css("visibility","visible");
	}
	else {
		$("div.search-box",domSidebar).css("marginTop","4em");
		domSidebar.animate({marginLeft:"-140"},1).addClass("hide");
		fixed = false;
		if (globalWindowHeight >= domHeader.height() + domSidebar.height()) {
			domLogo.css("position","fixed");
			domSidebar.css("position","fixed");
			fixed = true;
		}

		var controlLink = jQuery('<a></a>').attr("href","#").attr('id', 'control');
		controlLink.css("visibility","visible");
		if (fixed) {
			controlLink.css("position","fixed");
			domSidebar.prepend(controlLink);
		}
		else { domSidebar.before(controlLink);
		}
	}
		
	domContent.empty().css("visibility","visible");
	var loadedPosts = getLoadedPosts();
	var postsPerRow = getPostsPerRow(globalWidth, globalPostWidth, 149);
	var loaderIcon = jQuery('<div></div>').attr('id', 'loader');
	domContent.after(loaderIcon).load(globalLoadingURL, {from: loadedPosts, n: postsPerRow, type: 0});
	$("#loader").css("visibility","hidden");
	/* END "main" */
	
	// click event management
	$("#control").live("click",function(e){
		e.preventDefault();
		var slidepx = domSidebar.width();
		if (!domSidebar.hasClass('hide')) {
			if (!$.browser.msie) { $(this).fadeOut("slow", function() { $(this).removeClass('close');});}
			else { $(this).hide("fast", function() { $(this).removeClass('close');}); }
			margin = "-=" + slidepx;
			domSidebar.addClass('hide');
		}
		else {
			domSidebar.css("visibility","visible");
			if (!$.browser.msie) { $(this).fadeOut("slow", function() { $(this).addClass('close');}); }
			else { $(this).hide("fast", function() { $(this).addClass('close');}); }
			margin = "+=" + slidepx;
			domSidebar.removeClass('hide');
		}
		domSidebar.animate({ left: margin }, "slow");
		if ($.browser.msie) {
			domSidebar.css('zIndex',90);
			$("#control").css('zIndex',100);
		}
		if (!$.browser.msie) { $("#control").fadeIn("fast"); }
		else { $("#control").show("fast"); }
	});	
});
