var home = true;
var working = false;
var first = true;

function show_url_from_hash(hash)
{
	if(working && !first) return false;
	id = hash.replace("#", "");
	if(!id) return;
	closeHome(true);
	openSlide(id);
}

$(window).resize(function() {
	$("DIV#menu").css("position", "static");
	var position = $("DIV#menu").offset();
	$("DIV#menu").css("position", "fixed").css("margin", "0 auto").css("bottom", (50)+"px").css("left", position.left+"px");
});

$(document).ready(	
function()
{
	$(document).ajaxStart( function(){ working = true; } );
	$(document).ajaxStop( function(){ working = false; } );
	loadTwitter();
	 
	/* Menu */
	$('#navigator li').hover(  
		function () { $('ul', this).slideDown(100);  if ($('ul', this).length>0) $(this).addClass("open") },   
		function () { $('ul', this).slideUp(100);	 $(this).removeClass("open") });
	
	/* PopUp */
	$('#popup-mask').click(function () { closePopUp(); });
	$('#popup #chiudi').click(function () { closePopUp(); });

	$('INPUT.label').focus( function() { $("LABEL", $(this).parent()).fadeOut("fast"); });
	$('INPUT.label').blur( function() { if($(this).val()=="") { $("LABEL", $(this).parent()).fadeIn("fast");} });
	$('INPUT.label').each( function() { if($(this).val()!="") { $("LABEL", $(this).parent()).fadeOut("fast");} });
	
	$("#button-social").click( function() { if($("#social .content").width()==0) $("#social .content").animate({width: '357px'}); else $("#social .content").animate({width: '0px'}); });
	
	$("#slide A.close").hide().click( function() { closeSlide(); if($("#projects").hasClass("letters")) { getProjects("all"); } } );
	$("H1 A#logo").click( function() { closeSlide(); closeHome(false); if($("#projects").hasClass("letters")) { getProjects("all"); } } );
	
	loadProjects();
	
	$("#cerca-form").submit( function() {
		$.post(baseurl+"progetti/cerca", $(this).serialize(), function(data) { getFilter(); $("#projects").remove(); $("#projects-gallery").html(data); loadProjects(); });
		$(".label", $(this)).val("").blur();
	});
	
	var position = $("DIV#menu").offset();
	$("DIV#menu").css("position", "fixed").css("margin", "0 auto").css("bottom", (50)+"px").css("left", position.left+"px");
	
	show_url_from_hash(location.hash)
	first = false;

	$("A.slide").live("click", function() {
		closeHome(true);
		id = $(this).attr("href").replace("#", "");
		openSlide(id);
	});
});

function loadTwitter()
{
	if ($("#twitter-text").length == 0)
	{
		$.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=roomor&count=1&callback=?", function(data) {

			var tweets = $.map(data.results || data, function(item)
			{
				var retweet = (typeof(item.retweeted_status) != 'undefined');
	            var retweeted_screen_name = retweet ? item.retweeted_status.user.screen_name : null;
	            var tweet_raw_text = retweet ? ('RT @'+retweeted_screen_name+' '+item.retweeted_status.text) : item.text; // avoid '...' in long retweets
	            
	    	    var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;
	    	    tweet_raw_text = tweet_raw_text.replace(regexp,
	    	                                      function(match) {
	    	                                        var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
	    	                                        return "<a href=\""+url+"\" target=\"_blank\">"+match+"</a>";
	    	                                      });
	
		        var regexp = /[\@]+(\w+)/gi;
		        tweet_raw_text = tweet_raw_text.replace(regexp,"@<a href=\"http://www.twitter.com/$1\" target=\"_blank\">$1</a>");
		        
		    	$("#social").append("<div id='twitter-text' style='display:none;'><p>"+tweet_raw_text+"</p></div>");
		    	$("#twitter-text").fadeIn("fast");
			});
		});
	}
	else
	{
		if ($("#twitter-text").is(":hidden")) 
			$("#twitter-text").fadeIn("fast");
		else
			$("#twitter-text").fadeOut("fast");
	}
	
}

function closeHome(close)
{
	if (home && close)
	{
		$("H2").fadeOut("slow");
		$("H3").fadeOut("slow");
		$("DIV#container").removeClass("home")
		home = false;
	}
	else if(!close)
	{
		$("H2").fadeIn("slow");
		$("H3").fadeIn("slow");
		$("DIV#container").addClass("home");
		home = true;
	}
}

function loadProjects()
{
	$("#projects DIV").css("opacity", "0.4").each( function() {
		$(this).css("width", $(this).width()).css("height", $(this).height())
		$img = $(this).find("IMG").clone();
		$img.attr("src", $img.attr("src").replace("bnthumb", "thumb")).addClass("saturated");
		$(this).prepend($img);
	});
	$("#projects P").each( function() { $(this).attr("prewidth", $(this).width()).css("width", "0px").hide();});
	
	$("#projects").masonry( { columnWidth: 10 });
	
	home = true;
	$("#projects DIV").mouseenter( function() {
		$div = $(this);
		closeHome(true);

		$("#projects .open").removeClass("open");
		$div.addClass("open");
		$("#projects P:visible").stop().animate({ width: '0px' }, 200);
		$("#projects .solid").fadeTo("fast", 0.6).removeClass("solid");
		
		$p = $("P", $div);
		if ($p.length>0)
		{
			$p.css("z-index", "9999").show().stop().animate({width: $p.attr("prewidth")+'px'}, $p.attr("prewidth"));
		}
		$div.fadeTo(50, 1).addClass("solid");
	}).mouseleave( function() {
		$("#projects .open").removeClass("open");
		$("#projects P:visible").stop().animate({ width: '0px' }, 200);
		$("#projects .solid").fadeTo("fast", 0.6).removeClass("solid");
	}).click( function() {
		a = $("A", $(this));
		document.location=a.attr('href');
		show_url_from_hash(a.attr('href'));
	});
	
	$.fn.showdelay = (function() {
		var delay = 0;
		$(this).hide();
		return this.each(function() {
			$(this).delay(delay).fadeIn(200);
	      				delay += 80;
	    			});
				});
	
	$('#projects DIV').showdelay();
	
}

function openSlide(id)
{
	if ($("#slide #"+id).length == 0)
	{
		$("#slide A.close").hide();
		$("#projects-gallery").animate({ marginTop: 0}, 800, "easeInOutCirc");
		$("#slide").animate({ top: 0-$("#slide").height()+"px"}, 800, "easeInOutCirc", function() {
			$("#slide .inside").html("");
			$("#slide").css("top","-9999999px");
			$("#slide .inside").load(baseurl+id, function() {
				$("#slide .inside").waitForImages(function() {
					$("#slide").animate({ top: 0-$("#slide").height()+"px"}, 0);
					$("#slide").css({ top:(1-$(this).height())+"px" });
					$("#slide").animate({ top: 0 }, 800, "easeInOutCirc");
					$("#projects-gallery").animate({ marginTop: $("#slide").height() }, 800, "easeInOutCirc");
					$("#slide A.close").show();
					$("html").scrollTop();
				});

			});
			
			//if ((id == "chi-siamo" || id == "contatti") && !$("#projects").hasClass("letters"))
				//getProjects("letters");
			//else if (id != "chi-siamo" && id != "contatti" && $("#projects").hasClass("letters"))
			//	getProjects("all");
		});
	}
}

function closeSlide()
{
	$("#slide").animate({ top: 0-$("#slide").height()+"px"}, 800, "easeInOutCirc", function() {
		$("#slide .inside").html("");
	});
	$("#projects-gallery").animate({ marginTop: 0}, 800, "easeInOutCirc");
}

/* PopUp */
function loadPopUp(title, url, data, big)
{
	$("#popup").removeClass("big");
	if (big==1) $("#popup").addClass("big");
	
	//Get the screen height and width  
	var maskHeight = $(document).height();  
	var maskWidth = $(window).width();  

	//Set height and width to mask to fill up the whole screen  
	$('#popup-mask').css({'width':maskWidth,'height':maskHeight});  
	  
	//transition effect   
	$('#popup-mask').fadeTo("fast",0.8);    

	//Get the window height and width  
	var winH = $(window).height();  
	var winW = $(window).width();  
	        
	//Set the popup window to center  
	if (big==1) $('#popup').css('top', 50);
	else		  $('#popup').css('top',  winH/2-100);
	$('#popup').css('left', winW/2-$('#popup').width()/2);
	
	$('#popup #contentAjax').html("<div style='text-align:center'><img src='{/literal}{$smarty.const.BASEURL}{literal}lib/img/site/loader.gif' style='margin:40px 0;'><"+"/div>");
	$("#popup").show();
	$('#popup H3').html(title);
	if (url == '')	$('#popup #contentAjax').html(data);
	else			$('#popup #contentAjax').load(url+"/?a", function() {  });
}
function loadingPopUp()
{
	$('#popup #contentAjax').html("<div style='text-align:center'><img src='{/literal}{$smarty.const.BASEURL}{literal}lib/img/site/loader.gif' style='margin:40px 0;'><"+"/div>");
}
function closePopUp()
{
	$('#popup #contentAjax').html("");
	$('#popup-mask').fadeOut("fast");
	$('#popup').hide();  
}

function getProjects(what, params)
{
	closeHome(true);
	if (params == undefined) params = new Array();
	$.post(baseurl+"progetti/"+what, params, function(data) { if (what=="tag" || what=="deltag" || what == "delcerca") getFilter(); $("#projects").remove(); $("#projects-gallery").html(data); loadProjects(); });
}

function getFilter()
{
	$('#filter').load(baseurl+"filter");
}
function showConfirmMsg()
{
	$('#ok_msg').show();
	$('#intro_msg').hide();
	$('form').hide();
}
