/*
Falling Letters, ©Copyright 2006-2008 - bezumie.com. All Rights Reserved
Буквопад, ©Copyright 2006-2008 - bezumie.com. Всички права запазени
*/

function SetCookie (name, value) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name, DefaultVal) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return DefaultVal;
}

function rand(x, y) {
	return x + Math.round((y - x) * Math.random());
}

var alphabet = 'EN';

var lettersEN = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
var codesEN = new Array(  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90);

var lettersBG_PHO = new Array('А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ь', 'Ю', 'Я');
var codesBG_PHO = new Array(  65,  66,  87,  71,  68,  69,  86,  90,  73,  74,  75,  76,  77,  78,  79,  80,  82,  83,  84,  85,  70,  72,  67,  192, 219, 221, 89,  88,  222, 81);

var lettersBG_BDS = new Array('А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ь', 'Ю', 'Я');
var codesBG_BDS =  new Array(  68,  191, 76,  72,  79,  69,  71,  80,  82,  88,  85,  190, 59,  75,  79,  77,  188, 73,  74,  87,  66,  78,  219, 222, 84,  89,  67,  65,  90,  83);
	
function trans(el, i) {
	if (el.filters) {
		el.filters[0].opacity = i;
	} else {
		el.style.opacity = i / 100;
	}
}

function Pool(parent) {
	this.parent = parent;
	this.els = new Array();
	for (var i = 0; i < 100; i++) {
		this.newEl();
	}
	this.z = 0;
}

Pool.prototype.newEl = function() {
	var t = document.createElement('div');
	t.className = 'def';
	this.parent.appendChild(t);
	this.els.push(t);
}

Pool.prototype.getEl = function() {
	if (this.els.length == 0) {
		this.newEl();
	}
	var ret = this.els.pop();
	ret.style.zIndex = this.z++;
	return ret;
}

Pool.prototype.putEl = function(el) {
	el.style.display = 'none';
	this.els.push(el);
}

function Letter(pos, vy, maxY, size) {
	switch (alphabet){
		case 'EN': var abc = lettersEN;
			var abcCodes = codesEN;
			break;
		case 'BG_BDS': var abc = lettersBG_BDS;
			var abcCodes = codesBG_BDS;
			break;
		case 'BG_PHO': var abc = lettersBG_PHO;
			var abcCodes = codesBG_PHO;
			break;
	}
	this.pos = {x: pos.x, y: pos.y};
	this.vy = vy;
	this.el = lpool.getEl();
	var i = rand(0, abc.length - 1);
	this.let = abcCodes[i];
	this.el.className = 'letter';
	this.el.innerHTML = abc[i];
	this.el.style.fontSize = size + 'px'
	this.el.style.left = this.pos.x + 'px';
	this.el.style.top = this.pos.y + 'px';
	this.el.style.display = 'block';
	this.maxY = maxY;
}

Letter.prototype.update = function () {
	this.pos.y += this.vy;
	this.el.style.top = Math.round(this.pos.y) + 'px';
	return this.pos.y < this.maxY;
}

Letter.prototype.release = function () {
	lpool.putEl(this.el);
}


function Sparcle(pos, vel, maxX, maxY) {
	this.pos = {x: pos.x, y: pos.y};
	this.vel = {x: vel.x, y: vel.y};
	this.el = spool.getEl();
	this.el.className = 'sparcle';
	this.el.innerHTML = '';
	this.el.style.left = Math.round(this.pos.x) + 'px';
	this.el.style.top = Math.round(this.pos.y) + 'px';
	this.el.style.display = 'block';
	this.maxX = maxX;
	this.maxY = maxY;
	
	this.size = 2;
	this.t = 100;
}

Sparcle.prototype.update = function() {
	this.pos.x += this.vel.x;
	this.pos.y += this.vel.y;
	this.t -= 5;
	this.size += 0.25;
	
	this.el.style.left = Math.round(this.pos.x - this.size / 2) + 'px';
	this.el.style.top = Math.round(this.pos.y - this.size / 2) + 'px';
	this.el.style.width = Math.round(this.size) + 'px';
	this.el.style.height = this.el.style.width;
	trans(this.el, this.t);
	
	this.vel.x *= 0.9;
	this.vel.y *= 0.9;
	
	return (this.t > 0) && (this.pos.x > 0) && (this.pos.y > 0) && ((this.pos.x + this.size) < this.maxX) && ((this.pos.y + this.size) < this.maxY);
}

Sparcle.prototype.release = function () {
	spool.putEl(this.el);
}


function Game() {
	this.sprites = new Array();
	this.score = 0;
	this.lives = 5;
	this.minSpeed = 0.5;
}

Game.prototype.update = function() {
	var i = 0;
	var n = this.sprites.length;
	while (i < n) {
		if (!this.sprites[i].update()) {
			if (this.sprites[i].let) {
				if (this.lives > 0) {
					this.lives --;
					hit();
				}
			}
			this.sprites[i].release();
			this.sprites[i] = this.sprites[n - 1];
			this.sprites.pop();
			n--;
		} else {
			i++;
		}
	}
}

Game.prototype.addLet = function() {
	var pos = {x: rand(0, this.width - 24), y: 0};
	var vy = this.minSpeed + Math.random() * 2;
	var size = Math.round((vy - this.minSpeed) * 5 + 12);
	var t = new Letter(pos, vy, this.height, size);
	this.sprites.push(t);
}

Game.prototype.check = function(let) {
	var i = 0;
	var n = this.sprites.length;
	var ok = false;
	
	var sppos = new Array();
	
	while (i < n) {
		if ((this.sprites[i].let) && (this.sprites[i].let == let)) {
			this.sprites[i].release();
			sppos.push(this.sprites[i].pos);
			this.sprites[i] = this.sprites[n - 1];
			this.sprites.pop();
			n--;
			ok = true;
		} else {
			i++;
		}
	}
	
	for (var i = 0; i < sppos.length; i++) {
		this.addSparcles(sppos[i]);
	}
	
	if (ok) {
		this.score ++;
		updateScore();
	} else {
		if (this.lives > 0) {
			this.lives --;
			hit();
		}
	}
}

var dest = new Array({x: 1, y: 0}, {x: 0.5, y: 0.866}, {x: -0.5, y: 0.866}, {x: -1, y: 0}, {x: -0.5, y: -0.866}, {x: 0.5, y: -0.866});

Game.prototype.addSparcles = function(pos) {
	for (var i = 0; i < dest.length; i++) {
		var vel = 1.5 + Math.random() * 1.5;
		var t = new Sparcle(pos, {x: vel*dest[i].x, y: vel*dest[i].y}, this.width, this.height);
		this.sprites.push(t);
	}
}


var lpool, spool;
var game;
var running = true;
var terminate = false;
var topScore = 0;

function init() {
	alphabet = GetCookie('Letters_Keyboard', 'EN');
	lpool = new Pool(document.getElementById('arena'));
	spool = new Pool(document.getElementById('arena'));
	game = new Game();
	game.width = document.getElementById('arena').offsetWidth;
	game.height = document.getElementById('arena').offsetHeight;
	game.addLet();
	setTopScore(GetCookie('Letters_topScore', 0));
	hideKeyboards();
	loop();
}

var freq = 15;
var nextlevel = 10;
var hitcols = new Array('#ffffff', '#ffe0e0', '#ffc0c0', '#ffa0a0', '#ff8080', '#ff6060', '#ff4040', '#ff2020');
var col = -1;

function loop() {
	if (!running) return;
	if (terminate) return;
	setTimeout('loop()', 30);
	if (rand(0, freq) == 0) game.addLet();
	if (game.score >= nextlevel) {
		game.minSpeed += 0.2;
		if (freq > 5) freq--;
		nextlevel += 10;
	}
	if (col >= 0) {
		document.getElementById('livesdiv').style.background = hitcols[col];
		col--;
	}
	game.update();
	if (game.lives <= 0) {
		terminate = true;
		showMessage(msgNewGame);
		if (game.score > topScore){
			setTopScore(game.score);
		}		
	}
}

function checkKeyCode(keyCode) {
	switch (alphabet){
		case 'EN': 
			if ((keyCode>=65) && (keyCode<=90)) return keyCode;
			else return false;
			break;
		case 'BG_BDS': var abcCodes = codesBG_BDS; break;
		case 'BG_PHO': var abcCodes = codesBG_PHO; break;
	}

	for (var i=0; i<abcCodes.length; i++){	
		if (keyCode == abcCodes[i]) return keyCode;
	}
	return false;
}

function key(event) {
	if (terminate) return;
	var l = checkKeyCode(event.keyCode);
	if (running && l) game.check(l);
	
	if (event.keyCode == 13) {
		if (running) {
			running = false;
			showMessage(msgPaused);
		} else {
			hideMessage();
			running = true;
			loop();
		}
	}
}

function updateScore() {
	document.getElementById('score').innerHTML = game.score;
}

function hit() {
	col = hitcols.length - 1;
	document.getElementById('livesdiv').style.background = hitcols[col];
	document.getElementById('lives').innerHTML = game.lives;
}

function showMessage(s) {
	with (document.getElementById('message')) {
		innerHTML = s;
		style.display = 'block';
	}
}

function hideMessage() {
	document.getElementById('message').style.display = 'none';
}

function setTopScore(top){
	topScore = top;
	document.getElementById('topscore').innerHTML = topScore;
	SetCookie('Letters_topScore', topScore);
}

var cancelHide = false;

function showKeyboards(){
	var cp = document.getElementById('kbds');
	if (cp.style.display == 'none'){
		cp.style.display = 'block';
		cancelHide = true;
	}
	else {
		cancelHide = false;
		hideKeyboards();
	}
}

function selectKeyboard(kbd) {
	alphabet = kbd;
	SetCookie('Letters_Keyboard', kbd);
	if (GetCookie('Letters_Keyboard', 0) == 0){
		alert('Cookies must be enabled.');
	}
	else {
		window.location.reload();
		cancelHide = false;
		hideKeyboards();
	}
}

function hideKeyboards() {
	if (cancelHide) return;
	document.getElementById('kbds').style.display = 'none';
}