// PUZZLE
window.addEvent('domready', function() {

	// reserved position

	// box neighbours for every position
	boxNeighbours_p01 = new Array('p02','p05');
	boxNeighbours_p02 = new Array('p01','p03','p06');
	boxNeighbours_p03 = new Array('p02','p04','p07');
	boxNeighbours_p04 = new Array('p03','p08');
	
	boxNeighbours_p05 = new Array('p01','p06','p09');
	boxNeighbours_p06 = new Array('p02','p05','p07','p10');
	boxNeighbours_p07 = new Array('p03','p06','p08','p11');
	boxNeighbours_p08 = new Array('p04','p07','p12');
	
	boxNeighbours_p09 = new Array('p05','p10');
	boxNeighbours_p10 = new Array('p06','p09','p11');
	boxNeighbours_p11 = new Array('p07','p10','p12');
	boxNeighbours_p12 = new Array('p08','p11');

	(function(){ puzzleGo(); }).delay(4000);

})
function puzzleGo(boxLast) {
	// box last is the previous position of the moving box, 
	// so that we don't just swap back to the previous state.
	
	// find the empty box
	var boxEmpty = $$('.box_empty');
	var emptyId = boxEmpty.getProperty('id');
	// find the neighbour options for the empty box
	emptyboxNeighbours = eval('boxNeighbours_' + emptyId)
	// pick an option
	var boxMoverId = boxLast;
	while (boxMoverId==boxLast) {
		var boxMoverKey = Math.floor(Math.random()*emptyboxNeighbours.length);
		boxMoverId = emptyboxNeighbours[boxMoverKey];
	}
	//console.log(boxMoverId + ' : ' + boxLast);
	// position to move from
	var oldLeft = $(boxMoverId).getStyle('left');
	var oldTop = $(boxMoverId).getStyle('top');
	// position to move to
	var newLeft = boxEmpty.getStyle('left');
	var newTop = boxEmpty.getStyle('top');
	// move the emptybox back
	boxEmpty.setStyle('z-index',1);
	var boxFadeOut = new Fx.Morph($(boxMoverId), {duration: 400});
	boxFadeOut.start({
		'opacity': 0.5
	}).chain(function() {
		// move the new box to take the place of the emptybox
		var boxSlide = new Fx.Morph($(boxMoverId), {duration: 1200, transition: Fx.Transitions.Quad.easeOut});
		boxSlide.start({
			'left': newLeft,
			'top': newTop
		}).chain(function() {
			var boxFadeIn = new Fx.Morph($(boxMoverId), {duration: 400});
			boxFadeIn.start({
				'opacity': 1
			}).chain(function() {
				// move white space to new gap
				boxEmpty.setStyles({
					'left': oldLeft,
					'top': oldTop
				});
				// change the id of the moving box
				//$(boxMoverId).set('text',emptyId);
				$(boxMoverId).setProperty('id',emptyId);
				// change the id of the empty box
				//boxEmpty.set('text',boxMoverId);
				boxEmpty.setProperty('id',boxMoverId);
					
			})
		})
	});
	
	(function(){ puzzleGo(emptyId); }).delay(3000);
}

