	/*
	(C) www.dhtmlgoodies.com, September 2005
	
	You are free to use this script as long as the copyright message is kept intact
	
	
	Alf Magne Kalleland
	
	Skládačka obrázku
	
	*/
		
	var puzzleImages = ['http://www.kaclehy.cz/wp-content/themes/kaclehy/js/images/image1.jpg','http://www.kaclehy.cz/wp-content/themes/kaclehy/js/images/image2.jpg','http://www.kaclehy.cz/wp-content/themes/kaclehy/js/images/image3.jpg','http://www.kaclehy.cz/wp-content/themes/kaclehy/js/images/image4.jpg','http://www.kaclehy.cz/wp-content/themes/kaclehy/js/images/image5.jpg','http://www.kaclehy.cz/wp-content/themes/kaclehy/js/images/image6.jpg'];	// Array of images to choose from
	var rows = 3;
	var cols = 4;
		
	var imageArray = new Array();
	var imageInUse = false;
	var puzzleContainer;
	var activeImageIndicator = false;
	var activeSquare = false; 	// Reference to active puzzle square
	var squareArray = new Array(); // Array with references to all the squares

	
	var emptySquare_x;
	var emptySquare_y;
	
	var colWidth;
	var rowHeight;
	
	var gameInProgress = false;
	
	var revealedImage = false;
	
	for(var no=0;no<puzzleImages.length;no++){
		imageArray[no] = new Image();
		imageArray[no].src = puzzleImages[no];	
	}
	
	function initPuzzle()
	{
		gameInProgress = false;
		var tmpInUse = imageInUse;
		imageInUse = imageArray[Math.floor(Math.random() * puzzleImages.length)];
		if(imageInUse==tmpInUse && puzzleImages.length>1)
			initPuzzle();
		else{
			puzzleContainer = document.getElementById('puzzle_container');
			getImageWidth();
		}
	}
	
	function getImageWidth()
	{
		if(imageInUse.width>0){
			startPuzzle();	
		}else{
			setTimeout('getImageWidth()',100);	
		}
	}
	
	function scramble()
	{
		gameInProgress = true;
		var currentRow = cols-1;
		var currentCol = rows-1;
		
		document.getElementById('revealedImage').style.display='none';
		
		for(var no=0;no<rows;no++){
			for(var no2=0;no2<cols;no2++){
				if(no<rows.length || no2<cols.length){
					var el = document.getElementById('square_' + no2 + '_' + no);
					if(el){
						el.style.left = (no2 * colWidth) + (no2) + 'px';
						el.style.top = (no * rowHeight) + (no) + 'px';	
					}else{
						initPuzzle();
						return;
					}
				}			
			}
		}		
		
		
		var lastPos=false;
		var countMoves = 0;
		while(countMoves<(50*cols*rows)){
			var dir = Math.floor(Math.random()*4);
			var readyToMove = false;
			if(dir==0 && currentRow>0 && lastPos!=1){	// Moving peice down
				currentRow = currentRow-1;	
				readyToMove = true;
			}				
			if(dir==1 && currentRow<(rows-1) && lastPos!=0){	// Moving peice up
				currentRow = currentRow+1;
				readyToMove = true;
			}	
			if(dir==2 && currentCol>0 && lastPos!=3){ 	// Moving peice right
				currentCol = currentCol -1;
				readyToMove = true;
			}	
			if(dir==3 && currentCol<(cols-1) && lastPos!=2){ 	// Moving peice right
				currentCol = currentCol + 1;
				readyToMove = true;
			}
			if(readyToMove){
				activeSquare = document.getElementById('square_' + currentCol + '_' + currentRow);
				moveImage(false,true);	
				lastPos = dir;
				countMoves++;
			}
		}
		
		return;
	}
	
	function gameFinished()
	{
		var string = "";

		var squareWidth = colWidth + 1;
		var squareHeight = rowHeight + 1;		
		var squareCounter = 0;
		var errorsFound = false;
		var correctSquares = 0;
		for(var prop in squareArray){
			var currentCol = squareCounter % cols; 
			var currentRow = Math.floor(squareCounter/cols);
			var correctLeft = currentCol * squareWidth;
			var correctTop = currentRow * squareHeight;
			if(squareArray[prop].style.left.replace('px','') != correctLeft || squareArray[prop].style.top.replace('px','') != correctTop){
				//return;			
			}else{
				correctSquares++;
			}
				
			squareCounter++;	
		}	
		
		if(correctSquares == ((cols * rows) -1)){
			document.getElementById('messageDiv').innerHTML = '<h2>Skvělé, zvládli jste to!</h2>';
			gameInProgress = false;
			revealImage();
			
		}else{
			document.getElementById('messageDiv').innerHTML = 'Momentálně máte ' + correctSquares + ' z ' + ((cols * rows) -1) + ' kousků na správném místě.';
		}
		
	}
	
	var currentOpacity = 0;
	function revealImage()
	{
		if(currentOpacity==100)currentOpacity=0;
		var obj = document.getElementById('revealedImage');
		obj.style.display = 'block';
		currentOpacity = currentOpacity +2;
		if(document.all){
			obj.style.filter = 'alpha(opacity='+currentOpacity+')';
		}else{
			obj.style.opacity = currentOpacity/100;
		}
		
		if(currentOpacity<100)setTimeout('revealImage()',10);
		
	}
	function displayActiveImage()
	{
		if(!gameInProgress)return;
		if(!activeImageIndicator){
			activeImageIndicator = document.createElement('DIV');
			activeImageIndicator.className = 'activeImageIndicator';
			puzzleContainer.appendChild(activeImageIndicator);
			activeImageIndicator.onclick = moveImage;
			
		}
		activeImageIndicator.style.display='block';
		activeImageIndicator.style.left = this.offsetLeft +  'px';
		activeImageIndicator.style.top = this.offsetTop + 'px';
		activeImageIndicator.style.width = this.style.width;
		activeImageIndicator.style.height = this.style.height;
		activeImageIndicator.innerHTML = '<span></span>';
		activeSquare = this;
	}
	
	function moveImage(e,fromShuffleFunction)
	{
		if(!activeSquare)return;
		if(!gameInProgress && !fromShuffleFunction){
			alert('You have to shuffle the cards first');
			return;
		}
		var currentLeft = activeSquare.style.left.replace('px','') /1;
		var currentTop = activeSquare.style.top.replace('px','') /1;
		
		var diffLeft = Math.round((currentLeft - emptySquare_x) / colWidth);
		var diffTop = Math.round((currentTop - emptySquare_y) / rowHeight);	
		
		if(((diffLeft==-1 || diffLeft==1) && diffTop==0) || ((diffTop==-1 || diffTop==1) && diffLeft==0)){	// Moving right
			activeSquare.style.left = emptySquare_x + 'px';
			activeSquare.style.top = emptySquare_y + 'px';
			emptySquare_x = currentLeft;
			emptySquare_y = currentTop;	
			activeSquare = false;	
			if(activeImageIndicator)activeImageIndicator.style.display = 'none';
			if(!fromShuffleFunction)gameFinished();	
		}
	}
	
	function startPuzzle()
	{
		puzzleContainer.innerHTML = '';


		var subDivs = puzzleContainer.getElementsByTagName('DIV');
		for(var no=0;no<subDivs.length;no++){
			subDivs[no].parentNode.removeChild(subDivs[no]);
		}
		activeImageIndicator = false;
		squareArray.length = 0; 

		
		if(document.getElementById('revealedImage')){
			var obj = document.getElementById('revealedImage');
			obj.parentNode.removeChild(obj);
		}
		var revealedImage = document.createElement('DIV');
		revealedImage.style.display='none';
		revealedImage.id='revealedImage';;
		revealedImage.className='revealedImage';;
		var img = document.createElement('IMG');
		img.src = imageInUse.src;
		revealedImage.appendChild(img);
		puzzleContainer.appendChild(revealedImage);
			
		colWidth = Math.round(imageInUse.width / cols)-1;
		rowHeight = Math.round(imageInUse.height / rows)-1;

		puzzleContainer.style.width = colWidth * cols + (cols * 1) + 'px';
		puzzleContainer.style.height = rowHeight * rows + (rows * 1) + 'px';
		
		if(navigator.appVersion.indexOf('5.')>=0 && navigator.userAgent.indexOf('MSIE')>=0){
			puzzleContainer.style.width = colWidth * cols + (cols * 1) + 20 + 'px';
			puzzleContainer.style.height = rowHeight * rows + (rows * 1) + 20 + 'px';			
			
		}
				
		if(!revealedImage){
			revealedImage = document.createElement('DIV');
			revealedImage.style.display='none';	
			revealedImage.innerHTML = '';
			
		}
		for(var no=0;no<rows;no++){
			for(var no2=0;no2<cols;no2++){
				if(no2==cols-1 && no==rows-1){
					emptySquare_x = (no2 * colWidth) + (no2);	
					emptySquare_y = (no * rowHeight) + (no);	
					break;
				}
				var newDiv = document.createElement('DIV');
				newDiv.id = 'square_' + no2 + '_' + no;
				newDiv.onmouseover = displayActiveImage;
				newDiv.onclick = moveImage;
				newDiv.className = 'square';
				newDiv.style.width = colWidth + 'px';
				newDiv.style.height = rowHeight + 'px';	
				newDiv.style.left = (no2 * colWidth) + (no2) + 'px';
				newDiv.style.top = (no * rowHeight) + (no) + 'px';
				newDiv.setAttribute('initPosition',(no2 * colWidth) + (no2) + '_' + (no * rowHeight) + (no));
				var img = new Image();
				img.src = imageInUse.src;
				img.style.position = 'absolute';
				img.style.left = 0 - (no2 * colWidth) + 'px';
				img.style.top = 0 - (no * rowHeight) + 'px';
				newDiv.appendChild(img);				
				puzzleContainer.appendChild(newDiv);
				squareArray.push(newDiv);
			}
		}	
		
		
	}
	window.onload = initPuzzle;
	
	
	
/******************** Bludiště **************************/

var canvas, ctx, currentPos, maze, path, time, timer, gameInProgress, startTime;var scale = 25;var offsets ={"left":{x:-1,y:0},"up":{x:0,y:-1},"right":{x:1,y:0},"down":{x:0,y:1}};var levelSize = [21, 17, 13, 10, 8];var completeMessages = ["Complete!", "Done!", "Super!", "Bam!", "Woot!", "Yay!", "Sweet!"];
var rand = new Rand();

function Cell(x, y) {this.visited = false;this.up = true;this.right = true;this.down = true;this.left = true;this.x = x;this.y = y;}function Rand() {this.randomInt = function (x) {return Math.floor(Math.random() * x);
};
this.pickRand = function (al) {
return al[this.randomInt(al.length)];
};
}

function Maze(width, height){this.m = [];this.width = width;this.height = height;
this.start = {x: 0,y: 0};
this.end = {x: this.width - 1,y: this.height - 1};
this.c;
this.nextC;
this.stack = [];
this.initMaze = function () {
for (y = 0; y < height; y++) {
this.m.push(new Array());
for (x = 0; x < width; x++) {
this.m[y].push(new Cell(x, y));
}
}
};
this.getNeighbors = function (x, y) {
var n = [];
var c = this.getCell(x, y);
if (y != 0) {
n.push(this.getCell(x, y - 1));
}
if (y != height - 1) {
n.push(this.getCell(x, y + 1));
}
if (x != 0) {
n.push(this.getCell(x - 1, y));
}
if (x != width - 1) {
n.push(this.getCell(x + 1, y));
}
return n;
};
this.availableNeighbors = function (x, y) {
var list = [];
var neighbors = this.getNeighbors(x, y);
for (i = 0; i < neighbors.length; i++) {
if (!neighbors[i].visited) list.push(neighbors[i]);
}
return list;
};
this.randomNeighbor = function (x, y) {
return rand.pickRand(this.availableNeighbors(x, y));
};
this.breakWall = function (c1, c2) {
if (c1.x == c2.x) {
if (c1.y < c2.y) {
c1.down = false;
c2.up = false;
}
if (c1.y > c2.y) {
c1.up = false;
c2.down = false;
}
} else if (c1.y == c2.y) {
if (c1.x < c2.x) {
c1.right = false;
c2.left = false;
}
if (c1.x > c2.x) {
c1.left = false;
c2.right = false;
}
}
};
this.getCell = function (x, y) {
return this.m[y][x];
};
this.inBounds = function (x, y) {
if (x >= 0 && x < this.width && y >= 0 && y < this.height) {
return true;
}
return false;
};
this.isDeadEnd = function (x, y) {
var neighbors = this.getNeighbors(x, y);
for (i = 0; i < neighbors.length; i++) {
if (!neighbors[i].visited) return false;
}
return true;
};
this.isStart = function (x, y) {
if (this.start.x === x && this.start.y === y) return true;
return false;
};
this.isEnd = function (x, y) {
if (this.end.x === x && this.end.y === y) return true;
return false;
};
this.generateMaze = function () {
this.c = this.getCell(rand.randomInt(this.width), rand.randomInt(this.height));
this.c.visited = true;
this.mazeDo();
while (this.stack.length !== 0) {
if (this.isDeadEnd(this.c.x, this.c.y) || this.isEnd(this.c.x, this.c.y) || this.isStart(this.c.x, this.c.y)) {
this.nextC = this.stack.pop();
this.c = this.nextC;
} else {
this.mazeDo();
}
}
};
this.mazeDo = function () {
this.nextC = this.randomNeighbor(this.c.x, this.c.y);
this.nextC.visited = true;
this.breakWall(this.c, this.nextC);
this.stack.push(this.c);
this.c = this.nextC;
};
this.initMaze();
this.generateMaze();
}

function setup(height, width) {
height = Math.floor(height);
width = Math.floor(width);
maze = new Maze(height, width);
currentPos = {x: 0,y: 0};
path = [];
path.push(currentPos);
canvas.width = maze.width * scale + 3;
canvas.height = maze.height * scale + 3;
jQuery("#a").width(maze.width * scale + 3);
draw();
}

function start() {
startTime = new Date();
timer = setInterval(timeTick, 100);
showTime();
showSteps();
gameInProgress = true;
jQuery('#game-info').show();
}

function unlockGame() {
jQuery("#f").show();
jQuery("#next").remove();
center(jQuery("#win"));
localStorage.setItem("unlocked", true);
}

function draw() {
drawPath();
drawMaze();
}

function move(direction) {
var newPos = {x: currentPos.x + offsets[direction].x,y: currentPos.y + offsets[direction].y};
if (gameInProgress && maze.inBounds(newPos.x, newPos.y)) {
if (maze.getCell(currentPos.x, currentPos.y)[direction] === false) {
path.push(newPos);
currentPos = newPos;
draw();
showSteps()
if (maze.isEnd(newPos.x, newPos.y)) {
levelWon();
}}}}

function levelWon() {
clearInterval(timer);
gameInProgress = false;
jQuery("#win h2").html(rand.pickRand(completeMessages));
center(jQuery("#win").show());
}

function center(e) {
e.css('top', jQuery("#maze").offset().top + jQuery("#maze").height() / 2 - e.outerHeight() / 2).css('left', jQuery("body").width() / 2 - e.outerWidth() / 2)
}

function drawPath() {
ctx.fillStyle = "#d7edff";
for (i = 0; i < path.length - 1; i++) {
ctx.fillRect(path[i].x * scale + 2, path[i].y * scale + 2, scale, scale);
}
ctx.fillStyle = "#67b9e8";
ctx.fillRect(currentPos.x * scale + 2, currentPos.y * scale + 2, scale - 2, scale - 2);
}
function drawMaze() {
ctx.fillStyle = "#65c644";
ctx.fillRect(maze.end.x * scale, maze.end.y * scale, scale, scale);
for (y = 0; y < maze.height; y++) {
for (x = 0; x < maze.width; x++) {
drawCell(x, y);
}}}
function drawCell(x, y) {
var curCell = maze.getCell(x, y);
var originx = x * scale;
var originy = y * scale;
if (curCell.up && !maze.isStart(curCell.x, curCell.y)) line(originx, originy, originx + scale, originy);
if (curCell.down && !maze.isEnd(curCell.x, curCell.y)) line(originx, originy + scale, originx + scale, originy + scale);
if (curCell.right) line(originx + scale, originy, originx + scale, originy + scale);
if (curCell.left) line(originx, originy, originx, originy + scale);
}

function line(x1, y1, x2, y2) {
ctx.beginPath();
ctx.strokeStyle = "#ee4646";
ctx.lineCap = 'round';
ctx.lineWidth = 2;
ctx.moveTo(x1 + 1, y1 + 1);
ctx.lineTo(x2 + 1, y2 + 1);
ctx.stroke();
}

function showTime() {deltaTime = Math.floor(((new Date).getTime() - startTime.getTime()) / 1000);jQuery("#timer, .timer").html(deltaTime + " second" + (deltaTime !== 1 ? "s" : ""));}

function showSteps() {jQuery("#steps, .steps").html(path.length - 1 + " step" + (path.length !== 2 ? "s" : ""));}

function timeTick() {showTime();}
jQuery().ready(function () {
canvas = document.getElementById('maze');
if (canvas.getContext) {
ctx = canvas.getContext("2d");
var newLevelSize = levelSize.pop();
setup(newLevelSize * 1.33, newLevelSize);
if (localStorage.getItem("unlocked") !== null) {
unlockGame();
jQuery("#win").show();
} else {
start();
}
} else {
return;
}
jQuery("#f").submit(function () {
jQuery('#win, #end-game').hide();
setup(jQuery('#w').val(), jQuery('#h').val());
start();
return false;
});
jQuery("#next").click(function () {
var newLevelSize = levelSize.pop();
if (newLevelSize != null) {
setup(newLevelSize * 1.33, newLevelSize);
start();
jQuery("#win").hide();
} else {
unlockGame();
}
return false;
});
jQuery('#h, #win').bind('keypress', function (e) {
return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
});jQuery(window).resize(function(){center(jQuery("#win"));});});
jQuery(window).keydown(function(e){var keyCode = e.keyCode || e.which,keyCodes = {37:"left",38:"up",39:"right",40:"down",65:"left",87:"up",68:"right",83:"down"};if (keyCodes[keyCode] !== null && keyCodes[keyCode] !== undefined) {move(keyCodes[keyCode]);return false;} else if (keyCode === 13 || keyCode === 32) {jQuery('#win button:visible:last').trigger('click');return false;}});


