var larghezza;
var altezza;
var menu_generated = 0;
var attualmente_real = "";

var righe;
var elementi_per_riga;
var risultati;

var backgroundCalling = -1;
var backgroundCalled = 0;

var home = true;
var cicloBackground = true;
var windowAwake;

///////////////////////
// Listener di avvio //
///////////////////////
$(function() {
	
	$(".javascript").hide();
	
	$(window).bind('resize', function() {
		$('.renderized').fadeOut();
		$("#background").fadeOut();
		clearTimeout(windowAwake);
		windowAwake = setTimeout('init()', 500);
	});
	setInterval('gingin()', 200);
	
	$(window).bind('readyForRender', function() {});
	
	init();
	
});

//////////////////////
// Pulizie generali //
//////////////////////
function prerender() {
	
	if($('.renderized').length > 0)
		$('.renderized').remove();
	
	$(window).trigger('readyForRender');
	
}

//////////////////////
// Avvio del kernel //
//////////////////////
function init() {
	
	larghezza = $(window).width();
	altezza = $(window).height();
	setInterval('pre_background();', 5000);
	pre_background();
	menu();
	
	attualmente = '';
	
	$('<img />')
		.attr('id', 'yoyoLoader')
		.css({
			zIndex: 999,
			position: 'fixed',
			top: altezza/2-20,
			left: larghezza/2-20,
			width: 40,
			height: 40,
			display: 'none'
		})
		.attr('src', '/static/media/loader.gif')
		.appendTo('body');
	
}

////////////////////////////////////////////////
// Funzione che crea il substrato di partenza //
////////////////////////////////////////////////
function pre_background() {
	
	if(cicloBackground == true) {
		
		if($('.cloneBackground').html() != "")
			$('.cloneBackground').remove();
		
		$("#background").clone().addClass('cloneBackground').css({
			zIndex: -999
		}).appendTo('body');
		
		$.post('/home', function(r) {
			
			if(r.length-1 == backgroundCalling)
				backgroundCalling = 0;
			else
				backgroundCalling++;
			
			background();
			
		}, 'json');
		
	}
	
}

////////////////////////////////
// Generazione del background //
////////////////////////////////
function background() {
	
	if(home == true)
		prerender();
	
	$.post('/home', function(r) {
		
		var immagine = r[backgroundCalling].img;
		var titolo = r[backgroundCalling].h1;
		var testo = r[backgroundCalling].p;
		
		$("#menu li a").css('color', r[backgroundCalling].coloreMenu);
		$("#kane-color").css('color', r[backgroundCalling].coloreMenu);
		
		if($("#background").html() == null) {
			
			$('<div />')
				.attr('id', 'background')
				.appendTo('body');
				
		}
	
		$('#background')
			.html('')
			.css({
				position: 'fixed',
				top: 0,
				left: 0,
				overflow: 'hidden',
				width: larghezza,
				height: altezza,
				zIndex: -998
			});
		
		$('<img />')
			.attr('id', 'foto')
			.appendTo('#background');
			
		if(altezza < larghezza)
			$("#foto").css({
				zIndex: -9999,
				width: '100%'
			});
		else
			$("#foto").css({
				zIndex: -9999,
				width: '100%'
			});
			
		$("#foto")
			.hide()
			.bind('load', function() {
				if(home == true) {
					
					$('<h1 />')
						.addClass('renderized')
						.html(titolo.tit)
						.css({
							fontFamily: 'Arial',
							fontWeight: 'normal',
							fontStyle: 'italic',
							position: 'absolute',
							top: altezza/100*titolo.y,
							left: larghezza/100*titolo.x,
							color: titolo.color
						})
						.hide()
						.fadeIn();
					
					$('<p />')
						.addClass('renderized')
						.html(testo.tit)
						.css({
							fontFamily: 'Arial',
							fontWeight: 'normal',
							fontStyle: 'italic',
							position: 'absolute',
							top: altezza/100*testo.y,
							left: larghezza/100*testo.x,
							color: testo.color,
							width: r[backgroundCalling].width + '%'
						})
						.hide()
						.fadeIn();
					
				}
				
				var questaAltezza = $(this).height();
				var questaLarghrzza = $(this).width();
			
				if(questaAltezza > altezza)
					$(this).css('margin-top', -1*((questaAltezza-altezza)/2));
			
				if(questaLarghrzza > larghezza)
					$(this).css('margin-left', -1*((questaLarghrzza-larghezza)/2));
				$(this).fadeIn();
				
			})
			.attr('src', immagine)
		
			$("#background").fadeIn();
		
	}, 'json');
	
	// Calcolo le righe e gli elementi della riga.
	elementi_per_riga = Math.floor((larghezza-110)/270);
	righe = Math.floor((altezza-50)/220)-1;
	risultati = elementi_per_riga * (righe+1);
	
	if(elementi_per_riga > 5)
		elementi_per_riga = 5;
	
}

//////////////////////////
// Generazione del logo //
//////////////////////////
function logo() {
	
	if(!$("#logo").html())
		$("<div />")
			.hide()
			.attr('id', 'logo')
			.html('<span style="color: red">SUGAR</span><span id="kane-color" style="color: white">KANE</span>')
			.appendTo('body');
		
	$("#logo")
		.css({
			fontFamily: 'Impact',
			position: 'absolute',
			top: 20,
			left: (((larghezza/elementi_per_riga)*elementi_per_riga - (200 * elementi_per_riga))/elementi_per_riga)/2,
			fontSize: 65
		}).fadeIn();
	
}

//////////////////////////
// Generazione del menù //
//////////////////////////
function menu() {
	
	if(!$("#menu").html())
		$('<ul />')	
			.css({
				fontFamily: 'Arial',
				fontSize: 12,
				color: 'white'
			})
			.attr('id', 'menu')
			.html('… caricamento')
			.appendTo('body');	
	
	if(menu_generated == 0) {
	
		$.get('menu', function(dt) {
			
			menu_generated = 1;
			
			$("#menu").html('');
			
			$.each(dt, function(e, key) {
			
				$('<li />')
					.html('<a href="#'+key[1]+'">' + key[0] + '</a>')
					.appendTo($("#menu"));
				
				if(e + 1 == dt.length)
					guiMenu();	// Questa funzione viene lanciata dopo che il menù è stato creato, lo chiamiamo perché c'è da stilare il menù e farlo carino
					
			});
		}, 'json');
	
	} else
		guiMenu(); // Lo chiamiamo qui, perché il menù fu già generato...
	
}


///////////////////////////
// Graficazione del menù //
///////////////////////////
function guiMenu() {
	
	logo();
	
	$("#menu li")
		.css({
			float: 'left',
			marginRight: 30,
			marginTop: 8,
			textTransform: 'uppercase'
		});
	
	$("#menu li a")
		.css({
			textDecoration: 'none'
		});
	
	
	var positionOfLogo = $("#logo").position();
	var rleft = positionOfLogo.left + $("logo").width() + (larghezza - 688)/2 + 50;
	
	$("#menu")
		.css({
			listStyle: 'none',
			padding: 0,
			margin: 0,
			fontFamily: 'Arial',
			letterSpacing: 1,
			fontSize: 16,
			position: 'absolute',
			top: 25,
			left: rleft
		}).fadeIn();
	
}

//////////////////////
// Motore delle url //
//////////////////////
function gingin() {
	
	var url = document.location.hash;
	
	if(url != attualmente_real) {
		
		loader('show');
		attualmente_real = url;
		
		$.post('/url', { url : url, limit: 100 }, function(a) {
			
			loader('hide');
			
			if(a == null)
				return false;
			
			if(a.type == 'gallery') {
				
				$("#menu li").css({
					textDecoration: 'none'
				});
				
				$($("#menu li a[href='"+url+"']").parent()).css({
					textDecoration: 'underline'
				});
				
				logo();
				menu();
				$(window).bind('readyForRender', function() {
					
					cicloBackground = true;
					SKgallery(a.content, a);
					$(window).unbind('readyForRender');
					
				});
				
			} else if(a.type == 'opera') {
				
				logo();
				menu();
				
				$(window).bind('readyForRender', function() {
					
					cicloBackground = false;
					SKOpera(a);
					$(window).unbind('readyForRender');
					
				});
				
			} else if(a.type == "pagina") {
				
				$(window).bind('readyForRender', function() {
					
					cicloBackground = false;
					SKPagina(a);
					$(window).unbind('readyForRender');
					
				});
				
			}
			
			prerender();
			
		}, 'json');
		
	}
	
}

///////////
// Opere //
///////////
function SKPagina(pagina) {
	
	var giro = 0;
	
	$(document).keyup(function(e) { 
		if (e.which == 27) { location.hash = '/' }
	});
	
	$('<div />')
		.addClass('renderized')
		.css({
			backgroundColor: 'black',
			position: 'fixed',
			top: 0,
			left: 0,
			width: larghezza,
			height: altezza,
			opacity: 0,
			cursor: 'pointer',
			overflow: 'hidden'
		})
		.bind('click', function() {
			location.hash = '/';
		})
		.fadeTo(200, 0.8)
		.appendTo('body');
	
	if(altezza > 800)
		var altezza_player = 690;
	else
		var altezza_player = altezza - 200;
	
	
	var larghezza_player = altezza_player * 1.78;
	
	$('<div />')
		.html('<h1 style="font-family: \'Arial\'; font-size: 12px; margin: 0px; padding: 10px; line-height: 16px; padding-left: 0px">'+pagina.titolo+'</h1><p style="font-family: \'Arial\'; font-size: 12px; margin: 0px; padding: 0px 0px 0px 0px">'+base64_decode(pagina.contenuto)+'</p>')
		.css({
			overflow: 'auto',
			color: 'white',
			zIndex: 999,
			position: 'fixed',
			top: (altezza-altezza_player)/2,
			left: (larghezza - larghezza_player)/2,
			width: larghezza_player,
			height: altezza_player
		})
		.addClass('renderized')
		.appendTo('body');
	

	
}

///////////
// Opere //
///////////
function SKOpera(opera) {
	
	var giro = 0;
	
	$(document).keyup(function(e) { 
		if (e.which == 27) { location.hash = opera.eventuallyback; }
	});
	
	$('<div />')
		.addClass('renderized')
		.css({
			backgroundColor: 'black',
			position: 'fixed',
			top: 0,
			left: 0,
			width: larghezza,
			height: altezza,
			opacity: 0,
			cursor: 'pointer',
			overflow: 'hidden'
		})
		.bind('click', function() {
			location.hash = opera.eventuallyback;
		})
		.fadeTo(200, 0.8)
		.appendTo('body');
	
	$('<div />')
		.addClass('renderized')
		.attr('id', 'list-of-opere')
		.css({
			position: 'relative',
			top: 0,
			left: 0
		})
		.appendTo('body');
		
	var thumb_create = 0;
	
	if(opera.opere.length > 1) {
		
		var	left = 0;
			thumb_create = 1;
		var thumb_height_here = Math.ceil(altezza/opera.opere.length);
		var thumb_start_here = 0;
		
		if(thumb_height_here > 80)
			thumb_height_here = 80
			
		var shiftLeft = 2 * (Math.floor(thumb_height_here)) * 1.66666667;
		
		$("img.thumbsss").live('click', function() {
			var giro = $(this).attr("p");
			
			var a = $($("#list-of-opere div").get(giro)).position();
			var p = $($("#list-of-opere div").get(giro)).height();
			
			$("#list-of-opere").animate({
				top: (altezza-p)/2 + a.top * -1
			});
		});
		
	} else {
		
		var thumb_height_here = 3;
		var thumb_start_here = 0;
		var shiftLeft = 2 * (Math.floor(100)) * 1.66666667;
		
	}
	
	if(altezza > 800)
		var altezza_player = 690;
	else
		var altezza_player = altezza - 200;
	
	
	var larghezza_player = altezza_player * 1.78;
	
	if(larghezza-(altezza_player*1.78) < shiftLeft) {
		
		shiftLeft = shiftLeft/2;
		var colonne = 1;
		
	} else
		var colonne = 2;
	
	$('<div />')
		.html('<h1 style="font-family: \'Arial\'; font-size: 12px; margin: 0px; padding: 10px; padding-left: 0px">'+opera.title+'</h1><p style="font-family: \'Arial\'; font-size: 12px; margin: 0px; padding: 0px 0px 0px 0px">'+opera.desc+'</p>')
		.css({
			color: 'white',
			zIndex: 999,
			position: 'fixed',
			top: (altezza-altezza_player)/2 + altezza_player,
			left: (larghezza - larghezza_player)/2,
			width: larghezza_player
		})
		.attr('id', 'desc')
		.addClass('renderized')
		.appendTo('body');
	
	$('<div />')
		.addClass('renderized')
		.html('<p style="font-family: Arial; font-size: 12px">Share <a href="http://twitter.com/home?status='+opera.title+' '+opera.url+'" target="_blank"><img border="0" src="/static/media/twitter.png" /></a> <a target="_blank" href="http://www.facebook.com/sharer.php?u='+opera.url+'&t='+opera.title+'"><img border="0" src="/static/media/facebook.png" /></a> <a href="http://www.tumblr.com/share?v=3&amp;u='+opera.url+'&amp;t='+opera.title+'" target="_blank"><img border="0" src="/static/media/tumblr.png" /></a> <a href="http://www.myspace.com/Modules/PostTo/Pages/?u='+opera.url+'" target="_blank"><img border="0" src="/static/media/myspace.png" /></a>')
		.css({
			color: 'white',
			zIndex: 999,
			position: 'fixed',
			top: (altezza-altezza_player)/2 - 50,
			left: (larghezza - larghezza_player)/2 + larghezza_player - 130,
			width: shiftLeft - 15
		})
		.appendTo('body');
		
	
	var reala = -1;
	$(opera.opere).each(function(a, e) {
		
		// Thumb?
		if(thumb_create == 1) {
			
			if(colonne == 2) {
				
				if(left == 0) {
					
					left = 1;
					reala++;
					
				} else
					left = 0;
				
			} else {
				
				left = 0;
				reala++;
				
			}
			
			if(e.type == 'vimeo')
				var thumb = '/tim.php?w='+((Math.floor(thumb_height_here) - 5) * 1.66666667)+'&h='+(Math.floor(thumb_height_here) - 5)+'&src='+e.thumb;
			else
				var thumb = '/tim.php?w='+((Math.floor(thumb_height_here) - 5) * 1.66666667)+'&h='+(Math.floor(thumb_height_here) - 5)+'&src='+e.valueGrezza;
			
			$('<div />')
				.addClass('renderized')
				.css({
					position: 'absolute',
					height: Math.floor(thumb_height_here) - 8,
					width: (Math.floor(thumb_height_here) - 8) * 1.66666667,
					top: ((altezza-altezza_player)/2) + Math.floor(thumb_height_here) * reala,
					left: larghezza - ((Math.floor(thumb_height_here) - 5) * 1.66666667) - 4 - ((Math.floor(thumb_height_here) - 8) * 1.66666667 * left) - 10*left - 5
				})
				.html('<img style="cursor:pointer; padding: 1px" class="thumbsss" p="'+a+'" src="'+thumb+'" width="'+((Math.floor(thumb_height_here) - 5) * 1.66666667)+'" height="'+(Math.floor(thumb_height_here) - 5)+'" />')
				.appendTo('body');
			
		}
		
		if(e.type == 'vimeo') {
			
			$('<div />')
				.html('<iframe src="http://player.vimeo.com/video/'+e.value+'?title=0&amp;byline=0&amp;portrait=0&amp;color=ffffff&amp;autoplay=1" width="'+larghezza_player+'" height="'+altezza_player+'" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>')
				.css({
					position: 'absolute',
					top: altezza*a + (altezza - altezza_player)/2,
					left: (larghezza - larghezza_player)/2
				})
				.appendTo('#list-of-opere');
			
		} else {
			
			$('<div />')
				.html('<img src="'+e.value+'"/>')
				.css({
					display: 'none',
					position: 'absolute'
				})
				.appendTo('#list-of-opere')
				.find('img').bind('load', function(e) {
					
					var gh = 'img[src='+e.currentTarget.src+']';
					var questa_altezza = $(gh).parent().height();
					var ratio = questa_altezza/questa_larghezza;
					
					$(gh).css({
						height: altezza_player
					});
					
					var questa_larghezza = $(gh).parent().width();
					
					$(gh).parent().css({
						top: altezza*a + (altezza - altezza_player)/2,
						left: (larghezza - questa_larghezza)/2
					}).fadeIn();
					
				});
				
		}
		
	});
	
}

///////////////
// Categorie //
///////////////
function SKgallery(contentuto, origine) {
	
	home = false;
	var render = true;
	var top = 0;
	var start_righe = righe;
	var start_elementi = elementi_per_riga;
	risultati++;
	var index = -1;
	
	// Render \\
	
	var marginLeft = ((larghezza/elementi_per_riga)*elementi_per_riga - (200 * elementi_per_riga))/elementi_per_riga;
	
	$("<div />")
		.attr('id', 'listaContenuti')
		.addClass('renderized')
		.appendTo('body');
		
	if ( $.browser.msie ) {
		$("#listaContenuti").css({
			position: 'relative',
			top: '120px'
		});
	} else {
		$("#listaContenuti").css({
			width: larghezza,
			height: altezza-120,
			position: 'relative',
			top: 120,
			overflowY: 'auto'
		});
	}
	
	$.each(contentuto, function(e,a) {
		
		index++;
		
		if(start_elementi == 0) {
			
			top++;
			start_elementi = elementi_per_riga;
			index = 0;
			if(top <= righe)
				render = 1;
			else
				render = 1;
			
		}
		
		start_elementi--;
		
		if(render == 1) {
			
			$('<div />')
				.addClass('renderized')
				.addClass('opera')
				.attr("t", 250*top)
				.css({
					position: 'absolute',
					top: (top*250),
					left: (marginLeft/2) + ((larghezza/elementi_per_riga)*index)
				})
				.html('<img src="/tim.php?src=' + a.thumb + '&w=200&h=150" width="200" height="150" />')
				.hide().fadeIn()
				.click(function() {
					openOpera(a.id); // This is a big big big fake! :D
				})
				.mouseover(function() {
					
					$(".descrizione-opera").remove();
					
					var posizione = $(this).offset();
					this_w = $(this).width();
					this_h = $(this).height();
					
					$('<div />')
						.addClass('renderized')
						.css({
							position: 'absolute',
							top: $(this).attr('t') + 'px',
							left: posizione.left,
							opacity: 0.6,
							width: this_w-8,
							height: this_h-8,
							backgroundColor: 'black',
							padding: 4,
							fontFamily: 'Arial',
							fontSize: 12,
							color: 'white',
							cursor: 'pointer'
						})
						.click(function() {
							location.hash = 'opera/' + a.id + "-" + a.cat;
						})
						.addClass('descrizione-opera')
						.html(a.title)
						.appendTo('#listaContenuti');
						//.appendTo('body');
				})
				.appendTo('#listaContenuti');
				//.appendTo('body');
				
		}
		
	});
	$('<div />')
		.css({
			position: 'absolute',
			height: 0,
			top: (250*(top+1)) - 40,
			visibility: 'hidden'
		})
		.html("e")
		.appendTo('#listaContenuti');
	
}

//////////////////////////////
// Loader, girella che gira //
//////////////////////////////
function loader(evar) {
	
	if(evar == 'show') {
		
		$(".renderized").fadeOut();
		$("#yoyoLoader").show();
		$("#menu li").css({
			textDecoration: 'none'
		});
		
	}
	else
		$("#yoyoLoader").hide();
}


function builtDatabase() {}

///////////////
// PHP -> JS //
///////////////
function base64_decode (dt) {
	
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
		ac = 0,
		dec = "",
		tmp_arr = [];
	
	if (!dt) {
		return data;
	}
	
	dt += '';
	
	do { // unpack four hexets into three octets using index points in b64
		h1 = b64.indexOf(dt.charAt(i++));
		h2 = b64.indexOf(dt.charAt(i++));
		h3 = b64.indexOf(dt.charAt(i++));
		h4 = b64.indexOf(dt.charAt(i++));
		
		bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
		
		o1 = bits >> 16 & 0xff;
		o2 = bits >> 8 & 0xff;
		o3 = bits & 0xff;
		
		if (h3 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1);
		} else if (h4 == 64) {
			tmp_arr[ac++] = String.fromCharCode(o1, o2);
		} else {
			tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
		}
	} while (i < dt.length);
	
	dec = tmp_arr.join('');
	dec = this.utf8_decode(dec);
	
	return dec;
	
}

function utf8_decode (str_data) {
	
	var tmp_arr = [],
		i = 0,
		ac = 0,
		c1 = 0,
		c2 = 0,
		c3 = 0;
	
	str_data += '';
	
	while (i < str_data.length) {
		c1 = str_data.charCodeAt(i);
		if (c1 < 128) {
			tmp_arr[ac++] = String.fromCharCode(c1);
			i++;
		} else if (c1 > 191 && c1 < 224) {
			c2 = str_data.charCodeAt(i + 1);
			tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
			i += 2;
		} else {
			c2 = str_data.charCodeAt(i + 1);
			c3 = str_data.charCodeAt(i + 2);
			tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	
    return tmp_arr.join('');

}
