	/*-**************
	Няколко управляващи променливи.
	**************-*/
	var number_of_boxes_in_a_row = 9;
	var number_of_boxes_in_a_column = 11;
	var different_boxes = 7;
	var pixels = 44;
	var direction = '';
	var prevent_event_error = 0;
	var score_index = 0;
	var total = 0;
	var score = new Array(0, 1, 2);
	prog = 0;
	for (i=3; i<1000; i++){
		prog += i;
		score[i] = prog;
	}

	/*-**************
	Създава първоначалните елементи и ги позиционира спрямо уникалното id.
	**************-*/
	function createBox(){
		for (i=1; i<=(number_of_boxes_in_a_row*number_of_boxes_in_a_column); i++){
			var div = document.createElement('div');
			div.id = "box"+i;
			div.className = "box";
			div.setAttribute("type_of_box", Math.floor(Math.random()*different_boxes)+1);
			box_background(div);
			div.style.top = (pixels*(parseInt((i-1) / number_of_boxes_in_a_row)))+'px';
			div.style.left = (pixels*((i-1) % number_of_boxes_in_a_row))+'px';
			document.getElementById('whole').appendChild(div);
		}
	}

	/*-**************
	Създава нов елемент над основната матрица, когато елементи от нея изчезнат.
	**************-*/
	function createSingleBox(){
		var div = document.createElement('div');
		current_id = 1000 - j*number_of_boxes_in_a_row + i; //1000 - empty_boxes*numb + column
		div.id = "box"+current_id;
		div.className = "box";
		div.setAttribute("type_of_box", Math.floor(Math.random()*different_boxes)+1);
		box_background(div);
		div.style.top = (-j*pixels)+'px'; //поставя елемента над основната матрица с empty_boxes*pixels пиксела
		div.style.left = (pixels*((i-1) % number_of_boxes_in_a_row))+'px';
		document.getElementById('whole').appendChild(div);
	}

	/*-**************
	Прикачва background към подадения като аргумент елемент.
	**************-*/
	function box_background(div){
		var prefix = '../images/jsrunner/';
		if (div.getAttribute('type_of_box') == 1){
			div.style.backgroundImage = "url(" + prefix + "1.jpg)";
		}
		if (div.getAttribute('type_of_box') == 2){
			div.style.backgroundImage = "url(" + prefix + "2.jpg)";
		}
		if (div.getAttribute('type_of_box') == 3){
			div.style.backgroundImage = "url(" + prefix + "3.jpg)";
		}
		if (div.getAttribute('type_of_box') == 4){
			div.style.backgroundImage = "url(" + prefix + "4.jpg)";
		}
		if (div.getAttribute('type_of_box') == 5){
			div.style.backgroundImage = "url(" + prefix + "5.jpg)";
		}
		if (div.getAttribute('type_of_box') == 6){
			div.style.backgroundImage = "url(" + prefix + "6.jpg)";
		}
		if (div.getAttribute('type_of_box') == 7){
			div.style.backgroundImage = "url(" + prefix + "7.jpg)";
		}
	}

	/*-**************
	Начална функция, която прикача onclick събитие на всеки елемент и при нужда извиква други функции.
	**************-*/
	function attach_event_to_elements(not_the_first_time){
		if (not_the_first_time!=1){ //функцията се вика за първи път
			document.getElementById('load').style.display = 'none';
			document.getElementById('whole').style.display = 'block';
			createBox(); //създават се началните елементи
			if (different_boxes == 7)
				timer();
			else{ //funny mode, не се разрешава submit-ване на резултата
				body = document.getElementsByTagName('body');
				body[0].removeChild(document.getElementById('submit'));
			}
		}
		boxes = document.getElementById('whole').getElementsByTagName('div');
		for (i=0; i<boxes.length; i++){
			boxes[i].onclick = function(){
				if (prevent_event_error){ //други елементи вече са в движение, предотвратяваме бъгове
					return false;
				}
				numb = eval(this.id.substr(3));
				if (neighbour(numb)){
					replace(numb);
				}
				else{
					for (j=0; j<boxes.length; j++){
						boxes[j].className = "box";
						boxes[j].removeAttribute('active'); //Премахваме атрибута 'active' от всички елементи
					}
					this.className = "box active";
					this.setAttribute('active', 'active'); //Прикачаме атрибут 'active' към активния в момента елемент
				}
			}
		}
		if (not_the_first_time!=1)
			remove_boxes("redefine");
		else
			remove_boxes();
	}

	/*-**************
	Определяме дали най-скоро селектираният елемент е в съседство с активния
	**************-*/
	function neighbour(selected_box){
		if (document.getElementById('box'+(selected_box + number_of_boxes_in_a_row)) &&
		document.getElementById('box'+(selected_box + number_of_boxes_in_a_row)).getAttribute('active') == 'active'){
			direction = "down";
			return true;
		}
		if (document.getElementById('box'+(selected_box - number_of_boxes_in_a_row)) &&
		document.getElementById('box'+(selected_box - number_of_boxes_in_a_row)).getAttribute('active') == 'active'){
			direction = "up"
			return true;
		}
		if (document.getElementById('box'+(selected_box+1)) &&
		selected_box % number_of_boxes_in_a_row != 0 &&
		document.getElementById('box'+(selected_box+1)).getAttribute('active') == 'active'){
			direction = "right";
			return true;
		}
		if (document.getElementById('box'+(selected_box-1)) &&
		selected_box % number_of_boxes_in_a_row != 1 &&
		document.getElementById('box'+(selected_box-1)).getAttribute('active') == 'active'){
			direction = "left";
			return true;
		}
		return false;
	}

	/*-**************
	Определя кои елементи ще се разменят.
	**************-*/
	function replace(selected_box){
		prevent_event_error = 2;
		sb = selected_box;
		if (direction == "down")
			active_box = selected_box + number_of_boxes_in_a_row;
		if (direction == "up")
			active_box = selected_box - number_of_boxes_in_a_row;
		if (direction == "right")
			active_box = selected_box + 1;
		if (direction == "left")
			active_box = selected_box - 1;
		move(sb, active_box, "forward");
	}

	/*-**************
	Разменя елементите.
	**************-*/
	var increment = 0;
	function move(selected_box, active_box, replace_back){
		increment+=2;
		sb = selected_box;
		ab = active_box;
		rb = replace_back;
		if (direction == "down"){
			document.getElementById('box'+selected_box).style.top = (parseInt(document.getElementById('box'+selected_box).style.top)+2)+'px';
			document.getElementById('box'+active_box).style.top = (parseInt(document.getElementById('box'+active_box).style.top)-2)+'px';
		}
		if (direction == "up"){
			document.getElementById('box'+selected_box).style.top = (parseInt(document.getElementById('box'+selected_box).style.top)-2)+'px';
			document.getElementById('box'+active_box).style.top = (parseInt(document.getElementById('box'+active_box).style.top)+2)+'px';
		}
		if (direction == "right"){
			document.getElementById('box'+selected_box).style.left = (parseInt(document.getElementById('box'+selected_box).style.left)+2)+'px';
			document.getElementById('box'+active_box).style.left = (parseInt(document.getElementById('box'+active_box).style.left)-2)+'px';
		}
		if (direction == "left"){
			document.getElementById('box'+selected_box).style.left = (parseInt(document.getElementById('box'+selected_box).style.left)-2)+'px';
			document.getElementById('box'+active_box).style.left = (parseInt(document.getElementById('box'+active_box).style.left)+2)+'px';
		}
		if (increment < pixels) //двата елемента все още не са достигнали крайната си точка, за това move() се извиква наново
			setTimeout("move(sb, ab, rb)", 4);
		else{ //двата елемента вече са разменени - техните id-та се разменят и ако е нужно се извиква функция за премахване на някои елементи
			document.getElementById('box'+active_box).id = 'temp';
			document.getElementById('box'+selected_box).id = 'box'+active_box;
			document.getElementById('temp').id = 'box'+selected_box;
			increment = 0;
			if (rb == "forward")
				remove_boxes('none', sb, ab);
			if (rb == "back"){ //връщаме елементите обратно
				prevent_event_error--; //2-1-1=0; докато тази променлива е различна от 0 друг елемент няма да стане активен
			}
		}
	}

	/*-**************
	Премахваме излишните (при съвпадение) елементи.
	**************-*/
	var have_some_boxes_been_removed;
	var columnArray = new Array();
	for (ii=0; ii<=number_of_boxes_in_a_row; ii++)
		columnArray[ii] = 0;
	function remove_boxes(control, selected_box, active_box){
	have_some_boxes_been_removed = 0;
	sb = selected_box;
	ab = active_box;
		for (i=1; i<=number_of_boxes_in_a_row*number_of_boxes_in_a_column; i++){ //i представлява настоящият елемент - неговите съседи трябва да бъдат проверени
			row = parseInt((i-1)/number_of_boxes_in_a_row) + 1; //редица на настоящия елемент
			column = (i-1)%number_of_boxes_in_a_row + 1; //колона на настоящия елемент
			if (column>2){ //ако настоящият елемент не е в първата или втората колона се проверяват съседните на него елементи от ляво
				if (document.getElementById('box'+(i-1)).getAttribute('type_of_box')
				&& document.getElementById('box'+(i-1)).getAttribute('type_of_box') == document.getElementById('box'+i).getAttribute('type_of_box')
				&& document.getElementById('box'+(i-2)).getAttribute('type_of_box') == document.getElementById('box'+i).getAttribute('type_of_box')){
					document.getElementById('box'+i).setAttribute('remove', 'remove');
					document.getElementById('box'+(i-1)).setAttribute('remove', 'remove');
					document.getElementById('box'+(i-2)).setAttribute('remove', 'remove');
				}
			}
			if (row>2){ //по аналогия
				if (document.getElementById('box'+(i-number_of_boxes_in_a_row)).getAttribute('type_of_box')
				&& document.getElementById('box'+(i-number_of_boxes_in_a_row)).getAttribute('type_of_box') == document.getElementById('box'+i).getAttribute('type_of_box')
				&& document.getElementById('box'+(i-2*number_of_boxes_in_a_row)).getAttribute('type_of_box') == document.getElementById('box'+i).getAttribute('type_of_box')){
					document.getElementById('box'+i).setAttribute('remove', 'remove');
					document.getElementById('box'+(i-number_of_boxes_in_a_row)).setAttribute('remove', 'remove');
					document.getElementById('box'+(i-2*number_of_boxes_in_a_row)).setAttribute('remove', 'remove');
				}
			}
		}
		if (control == "redefine"){ //случва се само първият път, за да се избегне огромно количество премахване на елементи още в началото на играта
			for (j=1; j<=boxes.length; j++){
				if (document.getElementById('box'+j).getAttribute('remove') == 'remove'){
					document.getElementById('box'+j).removeAttribute('remove');
					document.getElementById('box'+j).setAttribute("type_of_box", Math.floor(Math.random()*different_boxes)+1);
					div = document.getElementById('box'+j);
					box_background(div);
				}
			}
			remove_boxes('none', sb, ab);
			return false;
		}
		else{
			for (j=1; j<=number_of_boxes_in_a_row*number_of_boxes_in_a_column; j++){
				if (document.getElementById('box'+j).getAttribute('remove')){
					score_index++;
					document.getElementById('whole').removeChild(document.getElementById('box'+j));
					column_to_fall = j%(number_of_boxes_in_a_row);
					if (column_to_fall == 0)
						column_to_fall = 9;
					columnArray[column_to_fall]++;
					have_some_boxes_been_removed = 1;
					prevent_event_error = 0;
				}
			}
			fall_down(columnArray);
			for (ii=0; ii<=number_of_boxes_in_a_row; ii++)
				columnArray[ii] = 0;
		}
		if (selected_box && document.getElementById('box'+selected_box)){
			document.getElementById('box'+selected_box).removeAttribute('active');
			document.getElementById('box'+selected_box).className = "box";
		}
		if (have_some_boxes_been_removed == 0 && sb && ab){
			move(sb, ab, 'back'); //връща елементите на старите им места
		}
		if (have_some_boxes_been_removed == 0){ //точкуване
			total += score[score_index];
			count -= score[score_index];
			formatted_total = total;
			document.getElementById('score').innerHTML = '';
			vertical(formatted_total);
			score_index = 0;
		}
	}

	/*-**************
	Някои изчислителни процедури - определя се кои точно елементи трябва да паднат след взимането на други.
	**************-*/
	var boxes_to_fall = new Array();
	var position_of_empty_boxes = new Array();
	function fall_down(column_Array){
		index = 0;
		i=1;
		while(i<=number_of_boxes_in_a_row){ //Обхождане на всички колони подред.
			for (j=column_Array[i]; j>0; j--){
				createSingleBox(); //Създаване на необходимия брой кутии
				for (x=1; x<=column_Array[i]; x++){
					index++;
					boxes_to_fall[index] = current_id; //добавя най-скоро създадения елемент в масива boxes_to_fall
				}
			}
			if (column_Array[i]){
				x=0;
				for (j=0; j<number_of_boxes_in_a_column; j++){
					if (!(document.getElementById("box"+(j*number_of_boxes_in_a_row+i)))){ //Ако се установи 'дупка' в колоната
						position_of_empty_boxes[x] = j+1; //позицията й се отбелязва в масива position_of_empty_boxes
						x++;
					}
				}
				for (x=position_of_empty_boxes.length-1; x>=0; x--){ //За всяка 'дупка' от колоната
					for (j=position_of_empty_boxes[x]; j>0; j--){ //и за всяка кутия над нея
						if (document.getElementById("box"+((j-1)*number_of_boxes_in_a_row+i))){ //ако тя съществува
							index++;
							boxes_to_fall[index] = (j-1)*number_of_boxes_in_a_row+i; //се добавя към масива boxes_to_fall.
						}
					}
				}
				position_of_empty_boxes.splice(0, position_of_empty_boxes.length+1); //изтрива масива
			}
		i++;
		}
		if (boxes_to_fall.length){
			do_fall_down();
		}
	}

	/*-**************
	Осъществява падането.
	**************-*/
	var top = 0;
	function do_fall_down(){
		prevent_event_error = 1;
		top+=4;
		for (i=1; i<boxes_to_fall.length; i++){
			document.getElementById("box"+boxes_to_fall[i]).style.top = (parseInt(document.getElementById("box"+boxes_to_fall[i]).style.top) + 4) + "px";
		}
		if (top < pixels){
			setTimeout('do_fall_down();', 4);
			return false;
		}
		else{
			top = 0;
			for (i=boxes_to_fall.length-1; i>0; i--){
				if (document.getElementById("box"+boxes_to_fall[i]).getAttribute('new_id')){
					new_id = (parseInt(document.getElementById("box"+boxes_to_fall[i]).getAttribute('new_id').substr(3)) + number_of_boxes_in_a_row)%1000;
				}
				else{
					new_id = (parseInt(document.getElementById("box"+boxes_to_fall[i]).id.substr(3)) + number_of_boxes_in_a_row)%1000;
				}
				document.getElementById('box'+boxes_to_fall[i]).setAttribute('new_id', "box"+new_id);
			}
		}
		boxes_to_fall.splice(0, boxes_to_fall.length+2); //изтрива масива
		boxes = document.getElementById('whole').getElementsByTagName('div');
		for (i=0; i<boxes.length; i++){
			if (boxes[i].getAttribute('new_id')){
				boxes[i].id = boxes[i].getAttribute('new_id');
			}
			boxes[i].removeAttribute('new_id');
		}
		prevent_event_error = 0;
		attach_event_to_elements(1);
	}

	function vertical(ft){
		if (parseInt(ft/10) != 0)
			vertical(parseInt(ft/10));
		document.getElementById('score').innerHTML += ft%10 + " ";
	}

	/*-**************
	Определя времето за игра
	**************-*/
	var count = 0;
	function timer(){
		count++;
		timer_top = 0 + count;
		timer_height = 481 - count;
		document.getElementById('timer').style.top = timer_top + "px";
		document.getElementById('timer').style.height = timer_height + "px";
		if (timer_height){
			setTimeout("timer()", 210);
		}
		else{
			document.getElementById('whole').style.display = 'none';
			document.getElementById('submit').style.display = 'block';
			document.getElementById('info').innerHTML += total;
		}
	}

	/*-**************
	Normal или Funny mode.
	**************-*/
	function mode(x){
		if (x){
			if (different_boxes == 7){
				different_boxes = 3;
				document.getElementById('mode').innerHTML = 'Funny';
			}
			else{
				different_boxes = 7;
				document.getElementById('mode').innerHTML = 'Normal';
			}
		}
		else{
			if (different_boxes == 7)
				document.getElementById('mode').innerHTML = 'Normal';
			else
				document.getElementById('mode').innerHTML = 'Funny';
		}
	}


	/*-**************
	AJAX
	**************-*/
	var xmlhttp;
	function loadHTTP(){
		url = "http://radoslavpopov.com/js/ajax.php";
		nick = '';
		if (!(document.getElementById('name').value) || document.getElementById('name').value.length > 24 || document.getElementById('name').value.match('[\$\#\%\&\*\?\+/]')){
			alert('Please enter your name; 1-24 symbols; letters, numbers, _ and ^ only.');
		}
		else{
			nick = document.getElementById('name').value;
			document.getElementById('submit').innerHTML = "please wait...";

			xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
			
			xmlhttp.onreadystatechange = state_change;
			if (nick.length>0)
				post_vars = "nick=" + encodeURIComponent(nick) + "&score=" + encodeURIComponent(total);
			xmlhttp.open('post', url+'?'+post_vars, true);
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlhttp.send(post_vars);
		}
	}
	function state_change(){
		if (xmlhttp.readyState == 4){
			if (xmlhttp.status == 200){
				document.getElementById('submit').innerHTML = xmlhttp.responseText;
			}
			else{
				alert("Problem retrieving data:" + xmlhttp.statusText);
			}
		}
	}

	/*-**************
	При onload събитие всички изображения, нужни за игра, са заредени - предоставя линк Start на потребителя.
	**************-*/
	window.onload = function(){
		document.getElementById('start').style.visibility = "visible";
	}
