var Ali = {
	currentPage: "",
	showcasePostsManager: null,
	showcaseElementsManager: null,
	showcaseMode: "",
	page: 0,
	lastPage: -1,
	screenWidth: 0,
	screenHeight: 0,
	currentLayoutWidth: 0,
	currentLayoutHeight: 0,
	resizeTimeoutIdentifier: null,
	layoutReady: false
};
Ali.showcasePostClickHandler = function(box)
{
	Ali.layoutReady = false;
	Ali.pushState(box.id);
	Ali.showShowcaseElements(box.id);
};
Ali.showcasePostHoverInHandler  = function(box)
{
	if(box.isTextBox)
		return;
	box.titleElement.css("opacity", 0);
	box.element.append(box.titleElement);
	box.titleElement.animate({ opacity: Ali.settings.titleOpacity}, Ali.settings.titleFadeInDuration, Ali.settings.titleFadeInEasing);
};
Ali.showcasePostHoverOutHandler = function(box)
{
	if(box.isTextBox)
		return;
	box.titleElement.stop().animate({ opacity: 0}, Ali.settings.titleFadeOutDuration, Ali.settings.titleFadeOutEasing, function()
	{
		box.element.empty();	
	});
};
Ali.init = function(page)
{
	$(document).scrollTop(0);
	Ali.updateViewportDimensions();
	Ali.showPage(page, true);
	$(window).resize(Ali._onResize);
	//$("#backgroundWrapper").css({width: Ali.screenWidth + "px", height: Ali.screenHeight + "px"});
	$(document).scroll(Ali._onScroll);
	Ali.refreshLoadingAnimationPosition();
	Ali.wrapper = $("#" + Ali.settings.wrapperId);
	Ali.wrapper.css("position", "relative");
	$(window).bind('popstate', function(event)
	{
		Ali.onPopState();
		event.preventDefault();
		return false;
	});
};
Ali._onResize = function()
{	
	Ali.refreshLoadingAnimationPosition();
	
	if(Ali.resizeTimeoutIdentifier != null)
		window.clearTimeout(Ali.resizeTimeoutIdentifier);

	Ali.resizeTimeoutIdentifier = window.setTimeout(function()
	{
		Ali.updateViewportDimensions();
		if(Ali.showcasePostsManager != null)
			Ali.showcasePostsManager.onResize();
		
		if(Ali.showcaseElementsManager != null)
			Ali.showcaseElementsManager.onResize();
			
		if(Ali.showcaseMode != "elements")
			Ali.centerLayout();
		var bw = $("#backgroundWrapper");
		bw.css({width: Ali.screenWidth + "px", height: Ali.screenHeight + "px"});
	}, Ali.settings.resizeReactivity);
};
Ali._onScroll = function()
{
	if(Ali.layoutReady)
	{
		Ali.performSmoothLoad();
		if(Ali.showcasePostsManager != null)
			Ali.showcasePostsManager.onScroll();
		if(Ali.showcaseElementsManager != null)
			Ali.showcaseElementsManager.onScroll();
	}
};
Ali.performSmoothLoad = function()
{
	//alert("X");
	if(Ali.isInPosts())
	{
		var st = Math.max($("body").scrollTop(), $("html").scrollTop());
		var h = $(window).height();
		var th = Ali.showcasePostsManager.totalHeight;// + Ali.settings.postsLayoutSettings.marginTop;
		var visibleBottom = st + h + Ali.settings.loadNextPageStickyZoneSize;
		//alert(visibleBottom + " > " + th + " || " + h + " > " + th);
		if(visibleBottom > th || h > th)
		{
			Ali.requestNextPage();
		}
	}
};
Ali.requestNextPage = function()
{
	if(Ali.requestActive || Ali.page == Ali.lastPage)
		return;
	Ali.requestActive = true;
	ServerProxy.requestPosts(Ali.page + 1, function(posts)
	{
		if(posts.length > 0)
		{
			Ali.page ++;
			Ali.showcasePostsManager.addBoxes(posts, function()
			{
				Ali.requestActive = false;
				Ali.performSmoothLoad();
			});
		}
		else
		{
			Ali.requestActive = false;
			Ali.lastPage = Ali.page;
		}
		
	});
};
Ali.isInElements = function()
{
	return Ali.currentPage == "showcase" && Ali.showcaseMode == "elements";
};
Ali.isInPosts = function()
{
	return Ali.currentPage == "showcase" && Ali.showcaseMode == "posts";
};
Ali.onNavUp = function(disablePushState)
{
	if(Ali.isInElements())
		Ali.hideShowcaseElements(function()
		{
			if(disablePushState == undefined || !disablePushState)
				Ali.showShowcasePosts(function(){ Ali.pushState(""); });
			else
				Ali.showShowcasePosts();
		});
};
/*
Ali.onNavRight = function()
{
	if(Ali.currentPage == "showcase" && Ali.showcaseMode == "elements")
		Ali.showShowcaseElements(Ali.currentPost.nextId);
};
Ali.onNavLeft = function()
{
	if(Ali.currentPage == "showcase" && Ali.showcaseMode == "elements")
		Ali.showShowcaseElements(Ali.currentPost.previousId);
};
*/
Ali.refreshLoadingAnimationPosition  = function()
{
	var la = $("#" + Ali.settings.loadingAnimationId);
	la.css({
		left: (.5 * ($(window).width() - la.width())) + "px",
		top: (.5 * ($(window).height() - la.height())) + "px"
	});
};
Ali.showPage = function(page, disablePushState)
{
	if(page == "")
		page = "showcase";
	
	if(page == Ali.currentPage)
	{
		if(page == "showcase" && Ali.showcaseMode == "elements")
			Ali.onNavUp();
		return;
	}
	
	Ali.log("Showing page " + page);
	Ali.hideCurrentPage(function()
	{
		Ali.currentPage = page;
		var pushedPage = "";
		if(page == "showcase")
		{
			if(Ali.postId == undefined)
			{
				Ali.showShowcasePosts();
				pushedPage = "";
			}
			else
			{
				Ali.showShowcaseElements(Ali.postId);
				pushedPage = Ali.postId;
				Ali.postId = undefined;
			}
		}
		else if (page == "about")
		{
			Ali.showAjaxPage(page);
			pushedPage = page;
		}
		if(disablePushState == undefined || !disablePushState)
			Ali.pushState(pushedPage);
	});
};
Ali.showAjaxPage = function(page)
{
	Ali.showLoadingAnimation();
	ServerProxy.requestPage(Ali.settings.pageIds[page], function(data)
	{
		Ali.fadeToOverviewColors();
		Ali.wrapper.html();
		Ali.wrapper.css("opacity", 0);
		Ali.wrapper.addClass("contentPage");
		Ali.wrapper.html(data.content);
		Ali.currentPage = page;
		Ali.setTitle(data.title);
		Ali.hideLoadingAnimation();
		Ali.wrapper.animate({ opacity: 1 }, Ali.settings.ajaxPageFadeInDuration);
		Ali.centerLayout();
	});
};
Ali.setTitle  = function(title)
{
	//TODO set title to data.title
};
Ali.hideCurrentPage  = function(successiveFunction)
{
	
	if(Ali.currentPage === "showcase" && Ali.showcaseMode === "elements")
		Ali.hideShowcaseElements(successiveFunction);
		
	else if(Ali.currentPage === "showcase" && Ali.showcaseMode === "posts")
		Ali.hideShowcasePosts(successiveFunction);
		
	else if(Ali.currentPage === "about")
		Ali.hideAjaxPage(successiveFunction);
		
	else if(Ali.currentPage === "" && successiveFunction != undefined)
		successiveFunction();
	else
		Ali.log("Error - no page hidden and successiveFunction not executed");
	
};
Ali.hideAjaxPage  = function(successiveFunction)
{
	Ali.wrapper.animate(
	{
		opacity:0
	}, Ali.settings.ajaxPageFadeOutDuration, function()
	{
		Ali.wrapper.html("");
		Ali.wrapper.removeClass("contentPage");
		Ali.wrapper.css("opacity", "1");
		if(successiveFunction !== undefined)
			successiveFunction();
	});
};
Ali.hideShowcasePosts  = function(queuedFunction)
{
	Ali.showcasePostsManager.fadeOut(function()
	{
		Ali.showcaseMode = "";
		if(queuedFunction !== undefined)
			queuedFunction();
	});
};
Ali.hideShowcaseElements = function(queuedFunction)
{
	if(Ali.showcaseElementsManager !== null)
	{
		$("#descriptionWrapper").empty();
		Ali.showcaseElementsManager.fadeOut(function()
		{
			Ali.showcaseMode == "";
			if(queuedFunction !== undefined)
				queuedFunction();
		});
	}
	else
		Ali.log("Elements not hidden - elementsManager is null");
};
Ali.fadeToOverviewColors = function(d)
{
	$("body").animate({
		color: Ali.settings.overviewTextColor
	}, d);
	var bw = $("#backgroundWrapper");
	bw.css("opacity", 1);
	bw.animate({
		opacity: 0,
		backgroundColor: Ali.settings.overviewBackgroundColor
	}, d, function()
	{
		$("nav").css("backgroundColor", "#fff");
	});
	$("nav").css("background", "none");
};
Ali.showShowcasePosts  = function(queuedFunction)
{
	Ali.showcaseElementsManager = null;
	var backgroundEffect = function()
	{
		var d = Ali.settings.elementsLayoutSettings.fadeOut.backgroundDuration;
		
		Ali.fadeToOverviewColors(d);
		$("window,body,html").scrollTop(0);
		$("#subTitle").html("art-direction&amp;design");
		
		$("#backgroundWrapper").css("opacity", 1);
		
		//$("nav").animate({ backgroundColor: "#fff" }, d);
		
	};
	
	if(Ali.showcasePostsManager == null)
	{
		var s = this.settings;
		Ali.showLoadingAnimation();
		Ali.layoutReady = false;
		ServerProxy.requestPosts(Ali.page, function(posts)
		{
			Ali.showcasePostsManager = new LayoutManager(Ali.wrapper, s.postsLayoutSettings);
			Ali.hideLoadingAnimation();
			Ali.currentPage = "showcase";
			Ali.showcaseMode = "posts";
			//Ali.showcasePostsManager.fadeIn(
			Ali.showcasePostsManager.addBoxes(posts, function()
			{
				Ali.layoutReady = true;
				//Ali.centerLayout();
				Ali.performSmoothLoad();
			});
			Ali.centerLayout();
			backgroundEffect();
			if(queuedFunction != undefined)
				queuedFunction();	
		});
	}
	else
	{
		backgroundEffect();
		Ali.showcaseMode = "posts";
		Ali.showcasePostsManager.fadeIn(queuedFunction);
	}
};
Ali.showShowcaseElements = function(postId)
{
	var s = this.settings;
	var queuedFunction = function()
	{
		Ali.showLoadingAnimation();
		ServerProxy.requestPost(postId, function(post)
		{
			Ali.showcaseElementsManager = new LayoutManager(Ali.wrapper, s.elementsLayoutSettings);
			Ali.hideLoadingAnimation();
			Ali.currentPage = "showcase";
			Ali.currentPost = post;
			Ali.showcaseMode = "elements";
			// ); Ali.showcaseElementsManager.fadeIn(
			var boxes = [];
			//if(post.description != null)
			//	boxes.push(AutoLayout.Box.createTextBox(post.description, post.backgroundImage, post.backgroundColor));

			$("#descriptionWrapper").html(post.description);
			
			for(var i = 0; i < post.elements.length; i++)
				boxes.push(post.elements[i]);
			
			//alert("X");
			$("#subTitle").html("&larr; back");
			Ali.showcaseElementsManager.addBoxes(boxes, function()
			{
				//Ali.showNavigator();
				Ali.layoutReady = true;
				//Ali.centerLayout();
			});
			var d = Ali.settings.elementsLayoutSettings.fadeIn.backgroundDuration;
			$("body").animate({color: post.textColor }, d);
			$("window,body,html").scrollTop(0);
			$("#backgroundWrapper").css({
				backgroundImage: post.backgroundImage,
				backgroundColor: post.backgroundColor,
				opacity: 0
			});
			$("nav").animate({ backgroundColor : post.backgroundColor }, d);
			$("#backgroundWrapper").animate({ opacity:1 }, d);
			
		});
	};
	
	if(Ali.showcasePostsManager !== null)
		Ali.showcasePostsManager.fadeOut(queuedFunction, true);
	else
		queuedFunction();
};
/*
Ali.showNavigator  = function()
{
	//var navElements = $("#navigatorLeft, #navigatorUp, #navigatorRight");
	var navElements = $("#navigatorUp");
	navElements.css({
		opacity:0,
		display:"inline-block"
	});
	navElements.animate(
	{
		opacity: 1
	}, "linear", Ali.settings.navigatorFadeInDuration);	
};

Ali.hideNavigator  = function()
{
	//var navElements = $("#navigatorLeft, #navigatorUp, #navigatorRight");
	var navElements = $("#navigatorUp");
	navElements.animate(
	{
		opacity: 0
	}, "linear", Ali.settings.navigatorFadeInDuration, function()
	{
		navElements.css({
			opacity:0,
			display:"inline-block"
		});
	});	
};
*/
Ali.showLoadingAnimation  = function()
{
	if(!this.settings.loadingAnimationEnabled)
		return;
	var e = $("#" + Ali.settings.loadingAnimationId);
	var la = $("#" + Ali.settings.loadingAnimationId);
	
	//left: (.5 * ($(window).width() - la.width())) + "px",
	//top: (.5 * ($(window).height() - la.height())) + "px"
	var w = la.width();
	var h = la.height();
	e.css({
		left: .5 * Ali.screenWidth,
		top: .5 * Ali.screenHeight,
		width: "1px",
		height: "1px",
		opacity: 0,
		display: "block"
	});
	e.animate({
		width: w + "px",
		height: h + "px",
		left: .5 * (Ali.screenWidth - w) + "px",
		top: .5 * (Ali.screenHeight - h) + "px",
		opacity: 1
	}, Ali.settings.loadingAnimationFadeInDuration,
	"linear");
};
Ali.hideLoadingAnimation  = function()
{
	if(!this.settings.loadingAnimationEnabled)
		return;
	var e = $("#" + Ali.settings.loadingAnimationId);
	e.animate({
		opacity: 0
	}, Ali.settings.loadingAnimationFadeOutDuration,
	"linear",
	function()
	{
		e.css({
			display:"none",
			opacity:1
		});
	});

};
Ali.isElementInViewport  = function (el)
{	var o = el.offset();
	var w = el.width();
	var h = el.height();
	var sL = $(document).scrollLeft();
	var sT = $(document).scrollTop();
	
	//var a = o.left + "x" + o.top + " - " + (o.left+w) + "x" + (o.top+h);
	//var b = sL + "x" + sT + " - " + (sL+Ali.screenWidth) + "x" + (sT+Ali.screenHeight);
	//Ali.log(a + " in " + b);
	
	return o.left + w > sL &&
		   o.left < sL + Ali.screenWidth &&
		   o.top + h > sT &&
		   o.top < sT + Ali.screenHeight;
};
Ali.updateViewportDimensions = function()
{
	Ali.screenWidth = $(window).width();
	Ali.screenHeight = $(window).height();
	if(Ali.isTouch())
	{
		Ali.screenWidth = Math.max(Ali.screenWidth, 1280);
		Ali.screenHeight = $(window).height();
	}
};
Ali.isTouch = function()
{
	return $.browser.safari && navigator.userAgent.indexOf("Mobile") != -1;
};
Ali.centerLayout = function()
{
	//if(!Ali.layoutReady)
	//	return;
	Ali.log("centering layout");
	Ali.updateViewportDimensions();
	var m, w;
	if(Ali.currentLayoutWidth > 0)
	{
		m = (.5 * (Ali.screenWidth - Ali.currentLayoutWidth));
		w = Ali.currentLayoutWidth + "px";
	}
	else
	{
		m = 10;
		w = "auto";
	}
	var tm = Math.min(Math.max(50, m) - 25, 100);
	//var ntm = tm - 30;
	Ali.wrapper.css({
		left: m + "px",
		top: tm + "px",
		minHeight: Ali.screenHeight
	});

	if(Ali.showcaseMode !== "elements")
	{
		$("#showcaseLink").css({
			marginLeft: m + Ali.settings.postsLayoutSettings.borderWidth + "px",
		//top: ntm + "px",
			opacity: 1
		});
		$("nav ul").css({
			marginRight: m + Ali.settings.postsLayoutSettings.borderWidth + "px", //(m + Ali.currentLayoutWidth - 210) + "px",
			//top: ntm + "px",
			opacity: 1
		});
		
		$("#descriptionWrapper").css({
			left: m + Ali.settings.postsLayoutSettings.borderWidth + "px",
			width: Ali.currentLayoutWidth - 20 + "px"
		});
		
	}
	Ali.wrapper.css({
		width: w,
		height: Ali.currentLayoutHeight + 100 + "px",
		overflow:"hidden"
	});
};
Ali.onPopState = function()
{
	var l = Ali.normalizeLink(location.href);
	Ali.log("popstate: " + l);
	if(l == "" && ( Ali.currentPage !== "showcase" || Ali.showcaseMode === "elements"))
	{
		if(Ali.currentPage != "showcase")
			Ali.showPage(l, true);
		
		else if(Ali.showcaseMode === "elements")
			Ali.onNavUp(true);
	}else if(l > 0)
	{
		Ali.showShowcaseElements(l);
	}
};
Ali.normalizeLink = function(link)
{
	link = link.replace(Ali.getBaseUrl(), "");
	if(link.substr(0, 1) === "/")
		link = link.substr(1);
	
	if(link.substr(0, 1) === "#")
		link = link.substr(1);
	
	return link;
};
Ali.pushState = function(link)
{
	if(Ali.normalizeLink(location.href) === link)
		return;
	
	//alert(location.href + " push " + link);
	
	if(Ali.isHistoryHijackingSupported())
		history.pushState({ path: undefined}, "", Ali.getBaseUrl() + "/" + link); 
	else
		location.href = "#" + link;
};
Ali.isHistoryHijackingSupported = function()
{
	return history.pushState != undefined;
};
Ali.getBaseUrl = function()
{
	return location.protocol + "//" + location.host;
};
Ali.log = function(what)
{
	if(console !== undefined && Ali.settings.logEnabled)
		console.log(what);
};
Ali.settings = 
{
	logEnabled: true,
	pageIds:
	{
		about:2
	},
	wrapperId: "aliWrapper",
	baseUrl: "http://www.pputzar.com/",
	ajaxPageFadeInDuration: 1000,
	ajaxPageFadeOutDuration: 1000,
	loadingAnimationId: "aliLoadingAnimation",
	loadingAnimationFadeInDuration: 200,
	loadingAnimationFadeOutDuration: 200,
	resizeReactivity: $.browser.mozilla ? 300 : 600,
	loadingAnimationEnabled: false,
	loadNextPageStickyZoneSize: 500,
	titleOpacity: 1,
	titleFadeInDuration: 200,
	titleFadeInEasing: "linear",
	titleFadeOutDuration: 200,
	titleFadeOutEasing: "linear",
	overviewTextColor: "#000000",
	overviewBackgroundColor: "#ffffff",
	defaultTextColor: "#ffffff",
	defaultBackgroundColor: "#000000",
	defaultBackgroundImage: "none",
	postsLayoutSettings: 
	{
		offsetTop:0,
		borderWidth: 10,
		resizeDuration: 1000,
		resizeEasing: "easeHorstElastic",
		fadeIn:
		{
			duration: 100, //was 500
			easing: "linear",
			stepping: 100
		},
		fadeInFast:
		{
			duration: 100, //was 500
			easing: "linear",
			stepping: 50
		},
		fadeOut:
		{
			duration: 500,
			easing: "linear",
			stepping: 50
		},
		boxClass:"postBox",
		clickable:true,
		gridTileSize:200,
		clickHandler: null
	},
	elementsLayoutSettings: 
	{
		offsetTop:50,
		resizeDuration: 1000,
		resizeEasing: "easeHorstElastic",
		fadeIn:
		{
			duration: 100, //was 500
			easing: "linear",
			stepping: 100,
			backgroundDuration: 2000
		},
		fadeOut:
		{
			duration: 1000,
			easing: "linear",
			stepping: 100,
			backgroundDuration: 2000
		},
		boxClass:"elementBox",
		gridTileSize:200,
		borderWidth:0,
		clickable:false
	}

};
Ali.settings.postsLayoutSettings.clickHandler =  Ali.showcasePostClickHandler;
Ali.settings.postsLayoutSettings.hoverHandler =
{
	inHandler: Ali.showcasePostHoverInHandler,
	outHandler: Ali.showcasePostHoverOutHandler
};

$.extend($.easing,
{
	easeHorstElastic: function (x, t, b, c, d)
	{
		var s = 1.70158;
		var p = 0;
		var a = c;
		if (t == 0)
			return b; 
		if ( (t /= d) == 1)
			return b + c; 
		
		if (!p)
			p = d * .7;//Originally was .3
		if (a < Math.abs(c))
		{
			a = c;
			s = p/4;
		}
		else
			s = p / (2 * Math.PI) * Math.asin ( c / a );
		
		return a * Math.pow(2, -10 * t) * Math.sin( ( t * d - s ) * ( 2 * Math.PI) / p ) + c + b;
	}
});

