/* Author: 

*/
var arrayPosX = [];
var arrayPosY = [];
var nbCols;
var nbRows;
var singleWidth;
var singleHeight;
var selected;
var minSize = 130;
var statusActions = null;

function getColsAndRows() {
	var w = $('body').width();
	var h = $('body').height();
	var i = 0;
	while(!nbCols && i < minSize) {
		if(w%(minSize + i) < minSize && h%(minSize + i) < minSize) {
			nbCols = (w - w%(minSize + i)) / (minSize + i);
			nbRows = (h - h%(minSize + i)) / (minSize + i);
			singleWidth = Math.floor(w / nbCols);
			singleHeight = Math.floor(h / nbRows);
		}
		i++;
	}
}
	
function cutMeInPieces(element,image) {
	if(image) {
		var img = new Image();
		img.onload = function() {
			$(element).cutinpieces({rows: nbRows, cols: nbCols, center: true, imageHeight: img.height, imageWidth: img.width, color: '#111'});
		}
		img.src = image;
	}
	else {
		$(element).cutinpieces({rows: nbRows, cols: nbCols, content: true});
	}
}

function showMyPieces(element, pieces) {
	disableActions(element);
	$(element).parent().show();
	$(element).parent().css('height','100%');
	$(element).parent().css('visibility','hidden');
	$(pieces).each(function() {
		var r = Math.random();
		var angle = Math.ceil(r*90);
		var el = $(this);
		var leftPos = el.css('left');
		var topPos = el.css('top');
		
		el.scale('y', r).scale('x', r);
		el.rotate(angle);

		el.css('left', el.position().left + r * singleWidth);
		el.css('top', - singleHeight - r * 500);
		
		el.setTransition({
		  property: 'transform',
		  'timing-function': 'ease-in',
		  duration: '.3s'
		}).rotate(0).scale('y', 1).scale('x', 1).animate({left: leftPos, top: topPos}, r * 400 + 500);
	});
	$(element).parent().css('visibility','visible');
	setTimeout("enableActions()", 1500);
}

function slideWorkspace(element) {
	var workspace = $('#workspace');
	var el = $(element);
	$('#container').html($(el).html());
	$('#container').css('background','#000');
	workspace.css('height', '0%');
	workspace.css('opacity', '0.8');
	workspace.show();
	$('#closeWorkspace').show();
	$('#closeWorkspace').css('opacity', '0');
	workspace.animate({duration: 3, height: '100%'});
}

function throwMyPieces(element, pieces, kill) {
	disableActions(element);
	$(pieces).each(function() {
		var r = Math.random();
		var w = $('body').width();
		var h = $('body').height();
		var angle = Math.ceil(r*360);
		var el = $(this);
		var leftPos = $(this).position().left + r * 500;
		var topPos = $(document).height() + 200 + r * 500;
		//el.boxshadow({hOffset : 3, vOffset : 3, shadowblur : 3, color : '#333333'});
		el.clearTransform();
		
		el.setTransition({
		  property: 'transform',
		  'timing-function': 'ease-in',
		  duration: '1.5s'
		}).rotate(angle).scale('y', r).scale('x', r).animate({left: leftPos, top: topPos}, r * 500 + 1500);
		if(!kill) {
			var id = $(this).attr('id') ? "#" + $(this).attr('id') : $(this).attr('href');
			arrayPosX[id] = null;
			arrayPosY[id] = null;
		}
	});
	if(kill)
		setTimeout("killPieces('" + element + "','" + pieces + "')", 1500);
	else
		setTimeout("enableActions()", 1500);
}

function killPieces(element,pieces) {
	$(pieces).remove();
	$(element).parent().hide();
	enableActions();
}

function generatePortfolioLink() {
	var linkPortfolio = $('#portfolio ul li a');
	
	linkPortfolio.each(function(i) {
		
		var id = $(this).parent().attr('id');
		var el = $(this);
		var rT = Math.random();
		var rL = Math.random();
		var top = Math.floor(rT * (nbRows - 1)) + 1;
		var left = Math.floor(rL * nbCols);

		var out = false;
		var i = 0;
		while(!out && i < 1000) {
			out = true;
			
			for(var j in arrayPosX) {
				if(arrayPosX[j] == left && arrayPosY[j] == top) {
					//alert(i + " " + j + " - " + arrayPosX[j] + " " + left + " / " + arrayPosY[j] + " " + top);
					out = false;
					break;
				}
			}

			
			if(!out) {
				rT = Math.random();
				rL = Math.random();
				top = Math.floor(rT * (nbRows - 1)) + 1;
				left = Math.floor(rL * (nbCols - 2)) + 1;
			}
			i++;
		}
		
		arrayPosX['#' + id] = left;
		arrayPosY['#' + id] = top;
		
		el.css('width', singleWidth - 20);
		el.css('height', singleHeight - 20);
		el.css('padding', 10);
		el.css('top', top * singleHeight);
		el.css('left', left * singleWidth);
		el.css('background-image',"url('img/works/" + id + ".jpg')");
		el.css('background-position',"center");
		el.unbind('click');
		el.bind('click', function() {
			if(statusActions != "#" + id) {
				selected = "pieces";
				$('#container').css('background-image',"url('img/works/" + id + ".jpg')");
				cutMeInPieces('#container', "img/works/" + id + ".jpg");
				
				$('#workspace #closeWorkspace').show();
				$('#workspace #closeWorkspace').css('opacity', 0);
				$('#description').hide();
								
				setTimeout("showMyPieces('#container','#container .piece')", 100);
			}
			return false;
		});
		el.bind('mouseover', function() {
			if(statusActions != '#portfolio') {
				var descr;
				descr = "<article>";
				descr += "<header>";
				descr += "<h1>" + $(this).html() + "</h1>";
				descr += "</header>";
				if($(this).attr('title'))
					descr += "<p>" + $(this).attr('title') + "</p>";
				descr += "</article>";
				$('#description').html(descr);
				bubbleInfos('#description',this);
			}
		});
		el.bind('mouseout', function() {
			$('#description').css('display', 'none');
		});
	});
}

function generateCvLink() {
	var linkCv = $('#cv > dl > dt > a');
	
	linkCv.each(function(i) {
		var id = $(this).attr('href');
		var dd = $(this).parent().next('dd');
		var el = $(this);
		var rT = Math.random();
		var rL = Math.random();
		var top = Math.floor(rT * (nbRows - 1)) + 1;
		var left = Math.floor(rL * nbCols);

		var out = false;

		var i = 0;
		while(!out && i < 1000) {
			out = true;
			for(var j in arrayPosX) {
				//if(i > 40)
					//alert(j + " " + arrayPosY[j] + " " + top);
				if(arrayPosX[j] == left && arrayPosY[j] == top) {
					out = false;
					break;
				}
			}
			if(!out) {
				rT = Math.random();
				rL = Math.random();
				top = Math.floor(rT * (nbRows - 1)) + 1;
				left = Math.floor(rL * nbCols);
			}
			i++;
		}
		
		arrayPosX[id] = left;
		arrayPosY[id] = top;
		
		el.css('width', singleWidth - 20);
		el.css('height', singleHeight - 20);
		el.css('padding', 10);
		el.css('top', top * singleHeight);
		el.css('left', left * singleWidth);
		el.unbind('click');
		if(el.attr('href').substr(0,1) != '#') {
			el.bind('mouseover', function() {
				if(statusActions != '#cv') {
					bubbleInfos(dd,this);
				}
			});
			el.bind('mouseout', function() {
				$(dd).css('display', 'none');
			});
		}
		else {
			el.bind('click', function() {
				selected = "content";
				slideWorkspace($(this).attr('href'));
			});
		}
	});
}

function generateMainLink() {
	var linkMenu = $('nav ul li a');
	linkMenu.each(function(i) {
		var el = $(this);
		/*
		var id = $(this).parent().attr('class');
		var rT = Math.random();
		var rL = Math.random();
		var top;
		var left;
		if(i == 0) {
			top = 0;
			left = 0;
		}
		else if(i == 1) {
			top = 0;
			left = 1;
		}
		else {
			top = 1;
			left = 0;
		}

		arrayPosX['#' + id] = left;
		arrayPosY['#' + id] = top;
		
		el.css('width', singleWidth - 20);
		el.css('height', singleHeight - 20);
		el.css('padding', 10);
		el.css('top', top * singleHeight);
		el.css('left', left * singleWidth);
		*/
		el.bind('click', function() {
			showSection($(this).attr('href'), this);
		});
	});
}

function showSection(element,menuItem) {
	if(statusActions != element) {
		$(menuItem).addClass('selected');
		if(element == "#portfolio") {
			$(menuItem).unbind('click');
			$(menuItem).bind('click',function() {
			if(statusActions != element) {
				killSection(element, menuItem);
			}
			});
			killSection('#cv', "nav#column li.cv a");
			$(element).show();
			generatePortfolioLink();
			showMyPieces(element, element + " ul li a");
			$('#description').hide();
		}
		if(element == "#me") {
			//bubbleInfos(element,menuItem);
			/*
			$('#workspace').css('background-image',0);
			cutMeInPieces(element);
			$('#workspace #closeWork').show();
			$('#workspace #closeWork').css('opacity', 0);
							
			setTimeout("showMyPieces('#workspace','#workspace .piece')", 1000);
			*/
			selected = "content";
			slideWorkspace(element);			
		}
		if(element == "#cv") {
			$(menuItem).unbind('click');
			$(menuItem).bind('click',function() {
			if(statusActions != element) {
				killSection(element, menuItem);
			}
			});
			killSection('#portfolio', "nav#column li.portfolio a");
			$(element).show();
			generateCvLink();
			showMyPieces(element, element + " dl dt a");
			$('#me > dd').hide();
		}
	}
}

function killSection(element, menuItem) {
	$(menuItem).removeClass('selected');
	$(menuItem).unbind('click');
	$(menuItem).bind('click',function() {
		showSection(element, menuItem);
		return false;
	});
	if(element == "#portfolio") {
		throwMyPieces(element, element + " ul li a");
		$('#description').fadeOut();
	}
	if(element == "#me") {
		throwMyPieces('#workspace', '#workspace .piece');
	}
	if(element == "#cv") {
		throwMyPieces(element, element + " dl dt a");
	}
}

function bubbleInfos(element,menuItem) {
	var posLeft = $(menuItem).position().left;
	var posRight = posLeft + $(menuItem).width() + 20;
	var posTop = $(menuItem).position().top;
	var posBottom = posTop + $(menuItem).height() + 20;
	var w = $('body').width();
	var h = $('body').height();
	var el = $(element);
	el.css('width', w / 3);
	el.show();
	
	if(w - posRight < (20 + el.width()) && posLeft < (20 + el.width())) {
		//Pas de place
		el.css('left', posRight - (20 + el.width()) / 2);
	}
	else if(w - posRight < posLeft) {
		//On affiche à gauche
		el.css('left', posRight - (20 + el.width()));
	}
	else {
		//On affiche à droite
		el.css('left', posLeft);
	}
	
	if(h - posBottom < (20 + el.height()) && posTop < (20 + el.height())) {
		el.css('top', posBottom);
	}
	else if(h - posBottom < posTop) {
		el.css('top', posTop - (20 + el.height()));
	}
	else {
		el.css('top', posBottom);
	}
}

function createWorkspace() {
	var workspace = jQuery("<div />");
	workspace.attr('id','workspace');
	workspace.append('<div id="container"></div>')
	var closeBtn = jQuery("<div />");
	closeBtn.attr('id','closeWorkspace');
	closeBtn.css('opacity', 0);
	closeBtn.append('Fermer');
	$(workspace).append(closeBtn);
		
	closeBtn.bind('mouseover',function() {
		closeBtn.css('opacity', 0.6);
		return false;
	});
	closeBtn.bind('mouseout',function() {
		closeBtn.css('opacity', 0);
		return false;
	});
	
	closeBtn.bind('click', function() {
		if(selected == 'pieces') {
			throwMyPieces('#container', '#container .piece', true);
		}
		else {
			$('#workspace').animate({duration: 3, height: '0%'});
		}
		closeBtn.fadeOut('slow');
		$('nav ul li.me a').removeClass('selected');
		return false;
	});
	
	$('body').append(workspace);
}

function createBubble() {
	$('#portfolio').append($('<div />').attr('id','description'));
}

function enableActions() {
	statusActions = null;
}

function disableActions(element) {
	statusActions = element;
}

function includeVideo() {
	var video = '<div id="backgroundVideo"><video autoplay="autoplay" loop="1"><source src="media/light.mp4" type="video/mp4" /><source src="media/light.ogv" type="video/ogg" /></video></div>';
	$('body').append(video);
    $("#backgroundVideo video").bind('ended', function(){ 
		this.play();
    }); 
}

$(document).ready(function() {
	init();
});


function init() {
	createWorkspace();
	createBubble();
	getColsAndRows();
	
	//cutMeInPieces('#workspace');
	
	generateMainLink();
	includeVideo();
}

