/********************************/
/*           PUZZLE             */
/*  Wykonanie: Tomasz Nabrzeski */
/*  Data:   Czerwiec 2007       */
/********************************/


var zindex = 2;
var wsk;

var Puzzle = new Class({
	initialize: function(){
		wsk = this;
	},
	setPicture: function(gfx){
		this.picture = gfx;
	},
	setWidth: function(width){
		this.width = width;
	},
	setHeight: function(height){
		this.height = height;
	},
	setPrecision: function(epsilon){
		this.epsilon = (epsilon ? epsilon : 15);
	},
	puzzleSize: function(size){
		this.size = size;
		this.partx = Math.ceil(this.width/this.size);
		this.party = Math.ceil(this.height/this.size);
	},
	play: function(){
		this.parts = this.partx * this.party;

		if ($('puzzle')) {
			$('puzzle').empty();
			$('puzzle').setStyles({
				'width': this.partx*this.size+'px',
				'height': this.party*this.size+'px'
			});
		} else {
			new Element('div', {
			'id':'puzzle',
			'styles':
			{'width': this.partx*this.size+'px',
			'height': this.party*this.size+'px',
			'border': '1px solid #999999',
			'padding': '0',
			'position': 'relative',
			'margin': 'auto'
			}}).injectInside(document.body);
		}

		for(var i=0;i<this.partx;i++) {
			for(var j=0;j<this.party;j++) {
				new Element('div', {
				'id':'part'+i+j,
				'styles': {
				'width': this.size+'px',
				'height': this.size+'px',
				'border': '1px solid #666666',
				'margin': '0',
				'position': 'absolute',
				'z-index': '2',
				'cursor': 'pointer',
				'left': ((this.width-this.size)*Math.random()).toInt()+'px',
				'top': ((this.height-this.size)*Math.random()).toInt()+'px',
				'background': 'white url('+ this.picture +') no-repeat '+ i*(-this.size) +'px '+ j*(-this.size) +'px'
				}}).injectInside($('puzzle')).makeDraggable({
					onStart: function() {
						zindex++;
						this.setStyle('z-index', zindex);
					}.bind($('part'+i+j)),
					onComplete: function() {
						var current = this.getStyle('backgroundPosition').trim().split(' ');
						var distancex = Math.abs(this.getLeft().toInt() - $('puzzle').getLeft().toInt() - Math.abs(current[0].toInt()));
						var distancey = Math.abs(this.getTop().toInt() - $('puzzle').getTop().toInt() - Math.abs(current[1].toInt()));
						if(Math.sqrt(distancex*distancex + distancey*distancey) < wsk.epsilon) {
							this.removeEvents();
							this.effects({
								duration: 200,
								onComplete: function(el) { el.setStyle('z-index', 1);el.setStyle('border', '0') }
							}).start({
							'left':[this.getLeft().toInt() - $('puzzle').getLeft().toInt(), Math.abs(current[0].toInt())],
							'top':[this.getTop().toInt() - $('puzzle').getTop().toInt(), Math.abs(current[1].toInt())]
							});

							wsk.parts--;
							if(wsk.parts==0) {
								alert('Gratulacje');
							}
						}
					}.bind($('part'+i+j))
				});
			}
		}
	}
});

