// xml variables
var rows;
var cols;
var count;
var csource;
var namepref;
var ext;
var bsource;
var memo_type;

// global vars

var table;
var tds;
var img_arr;
var game_id;

var reset = false;
var free = true;

var selected = new Array(2);

// sounds
var pair;
var end;
var sel;
var maxH;
var maxW;

var iW;
var iH;

var mode;
var prev_menu;
var back_btn;
var divider;

var leafArr;

function createMemo() {

	sel = new Audio("./memory_resources/sounds/click.mp3");
	pair = new Audio("./memory_resources/sounds/applause.mp3");
	end = new Audio("./memory_resources/sounds/win.mp3");
	leafArr = new Array();
	
	adjustStyles2();

	if (memo_type == 1) {
		loadMemo1();
	}
	
	if (memo_type == 2) {
		loadMemo2();
	}
	
	var IE = detectIE();

	var len = rows * cols;
	for (var i = 0; i < len; i++) {
		tds[i] = document.createElement('img');
		tds[i].setAttribute('id', i);
		tds[i].setAttribute('src', bsource);
		tds[i].className = 'in_card';
		tds[i].style.maxWidth = Math.floor(100 / cols) + '%';
		tds[i].style.maxHeight = 100 + '%';
		if(!IE) {
			tds[i].style.height = "100%";
		} else {
			tds[i].style.height = "auto";
		}
		tds[i].style.width = Math.floor(100 / cols) + '%';
		tds[i].setAttribute('onclick', 'clickListener(this)');
		tds[i].setAttribute('ontouchstart', 'clickListener(this)');
		tds[i].onclick = function() {
			clickListener(this);
		};

		tds[i].addEventListener('animationend', function() {
			animListener2(this);
		}, false);

		tds[i].addEventListener('webkitAnimationEnd', function() {
			animListener2(this);
		}, false);

	}

	selected[0] = null;
	selected[1] = null;
	table = document.createElement('table');
	table.setAttribute('id', "memo_table");
	var tmp = 0;
	for (var i = 0; i < rows; i++) {
		var tr = document.createElement('tr');
		tr.style.maxHeight = maxH;
		tr.style.maxHeight = "expression(" + maxH + ")";
		for (var j = 0; j < cols; j++) {
			if (tmp < len) {
				tr.appendChild(tds[tmp]);
				tmp++;
			}
		};
		table.appendChild(tr);
	};

	back_btn = document.getElementById("memo_back_button");
	back_btn.style.display = "inline-block";

	divider = document.createElement('article');
	divider.setAttribute('id', "memo_divider");

	if (mode == 1) {
		divider.className = 'memo_layout_easy';
	}

	if (mode == 2) {
		divider.className = 'memo_layout_medium';
	}

	if (mode == 3) {
		divider.className = 'memo_layout_hard';
	}

	divider.appendChild(table);

	document.body.appendChild(divider);
	prev_menu = document.getElementById("memo_menu");

	/*document.body.appendChild(table);*/
}

//TODO checker

function paired(el) {
	el.className = 'in_card';
	if (selected[0] !== null && selected[1] !== null) {
		var match = true;

		if (memo_type == 1) {
			match = tds[selected[0]].src !== tds[selected[1]].src;
		}

		if (memo_type == 2) {
			var sub1 = tds[selected[0]].src.split('cards/')[1].split('_')[0];
			var sub2 = tds[selected[1]].src.split('cards/')[1].split('_')[0];
			match = sub1 !== sub2;
		}

		if (match) {
			setTimeout(function() {
				reset = true;
				resetImg(tds[selected[0]]);
				resetImg(tds[selected[1]]);
				selected[0] = null;
				selected[1] = null;
				reset = false;
			}, 1000);
		} else {
			sel.pause();
			pair.currentTime = 0;
			pair.play();
			tds[selected[0]].className = 'in_card';
			tds[selected[0]].onclick = null;
			tds[selected[0]].removeAttribute('onclick');
			tds[selected[1]].className = 'in_card';
			tds[selected[1]].onclick = null;
			tds[selected[1]].removeAttribute('onclick');
			tds[selected[0]] = null;
			tds[selected[1]] = null;
			selected[0] = null;
			selected[1] = null;

			var win = true;
			var s = tds.length;
			for (var i = 0; i < s; i++) {
				if (tds[i] !== null) {
					win = false;
					break;
				}
			}

			if (win) {
				sel.currentTime = 0;
				sel.pause();
				pair.currentTime = 0;
				pair.pause();
				end.currentTime = 0;
				end.play();
				var idRemove = $("." + divider.className);
				var leafDiv = document.createElement('div');
				leafDiv.setAttribute('id', 'leaves');
				
				var wd = 0;
				var fd = 0;
				
				if(mode == 1) {
					wd = "30%";
					fd = "2.0vw";
				}
				
				if(mode == 2) {
					wd = "20%";
					fd = "1.5vw";
				}
				
				if(mode == 3) {
					wd = "15%";
					fd = "1.0vw";
				}
				console.log(wd);
				var s = leafArr.length;
				for(var i = 0; i < s; i++) {
					var leaf = document.createElement('div');
					leaf.className = 'leafDiv';
					leaf.style.width = wd;
					var leafImg = new Image();
					leafImg.className = 'leafImg'
					leafImg.src = csource + leafArr[i] + "." + ext;
					leaf.appendChild(leafImg);
					var leafDesc = document.createElement("p");
					leafDesc.setAttribute("class", "leafDesc");
					leafDesc.style.fontSize = fd;
					leafDesc.innerHTML = LEAVES_NAMES[leafArr[i]-1];
					leaf.appendChild(leafDesc);
					leafDiv.appendChild(leaf);
				}
				
				$(idRemove).replaceWith(leafDiv);
			}
		}
	}
	free = true;
}

//TODO listeners

function clickListener(element) {
	if (free) {
		free = false;
		var s = parseInt(element.id);
		if ((selected[0] !== s && selected[1] !== s) && (selected[0] === null || selected[1] === null)) {
			pair.pause();
			pair.currentTime = 0;
			sel.currentTime = 0;
			sel.play();
			element.className = 'card';
			var t = parseInt(element.id);
			if (selected[0] === null) {
				selected[0] = t;
			} else {
				selected[1] = t;
			}
		} else {
			free = true;
		}
	}
}

function animListener2(el) {
	if (el.className !== 'card_out') {
		var t = parseInt(el.id);
		el.setAttribute('src', img_arr[t]);
		setTimeout(paired(el), 300);

		//el.setAttribute('className', 'card_out');
		el.className = 'card_out';
	}

}

//TODO misc functions

function resetImg(el) {
	if (el !== undefined) {
		el.src = bsource;
		el.className = 'card_out';
		//el.setAttribute('className', 'card_out');
	}
}

//TODO import images and preload

function loadMemo1() {
	var len = rows * cols;
	tds = new Array(len);
	img_arr = new Array();
	var idx = 0;
	var rand = 0;
	var chosen = new Array();
	while(idx < count) {
		rand = Math.floor(Math.random() * LEAVES_COUNT) + 1;
		if($.inArray(rand, chosen) == -1) {
			chosen.push(rand);
			img_arr.push(csource + rand + '.' + ext);
			img_arr.push(csource + rand + '.' + ext);
			leafArr.push(rand);
			idx++;
		}
	}
	
	arrayShuffle(img_arr);
}

function loadMemo2() {
	var len = rows * cols;
	tds = new Array(len);
	img_arr = new Array(len);
	var idx = 1;
	var chosen = new Array();
	var rand;
	var ln = 39;
	for (var i = 1; i <= len; i += 2) {
		rand = 1 + Math.floor(Math.random() * 38);
		if ($.inArray(rand, chosen) == -1) {
			chosen.push(rand);
			img_arr[i - 1] = csource + rand + "_" + 1 + '.' + ext;
			img_arr[i] = csource + rand + "_" + 2 + '.' + ext;
			idx++;
		} else {
			i = i-2;
		}
	}
	arrayShuffle(img_arr);
}

function initMemo(md) {
	mode = md;
	resourcesLoaded();
}

function errorLog() {
	alert('Nastąpił problem z połączeniem.');
}

function resourcesLoaded() {
	var c;
	if (mode == 1) {
		c = MEMORY_EASY;
	}

	if (mode == 2) {
		c = MEMORY_MEDIUM;
	}

	if (mode == 3) {
		c = MEMORY_HARD;
	}
	parseMemoJSON(c);
	createMemo();

}

function parseMemoJSON(c) {
	memo_type = c.memotype;
	rows = c.rows;
	cols = c.cols;
	count = c.count;
	csource = c.csource;
	ext = c.ext;
	bsource = c.bsource;
}

function go_back() {
	var id_remove = "." + divider.className;
	$(id_remove).remove();
	var leafRemove = ".leafDiv";
	$(leafRemove).remove();
	$("#leaves").remove();
	back_btn.style.display = "none";
	prev_menu.className = 'non_fading';
	prev_menu.style.display = "block";
}

//TODO resizing

function adjustStyles2() {
	maxH = Math.floor(100 / rows) + '%';
	maxW = Math.floor(100 / cols) + '%';

	var params = location.search.substring(1).split('&');
	var tmp = params[0].split('=');
	game_id = unescape(tmp[1]);

	iW = Math.floor(document.documentElement.clientWidth / cols);
	iH = Math.floor(document.documentElement.clientHeight / rows);

}

function showLeaves() {
	var s = leafArr.length;
	for(var i = 0; i < s; i++) {
		console.log(leafArr[i]);
	}
}

// TODO array shuffler
function arrayShuffle(arr) {
	var ct = arr.length;
	var tmp_arr = new Array(ct);
	var rand = 0;
	for (var i = 0; i < ct; i++) {
		tmp_arr[i] = null;
	};

	for (var i = 0; i < ct; i++) {
		rand = Math.floor(Math.random() * ct);
		while (tmp_arr[rand] !== null) {
			rand = Math.floor(Math.random() * ct);
		}
		tmp_arr[rand] = arr[i];
	}

	img_arr = tmp_arr;
}

function detectIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    var trident = ua.indexOf('Trident/');

    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    if (trident > 0) {
        // IE 11 (or newer) => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    // other browser
    return false;
}
