var interval;													// interval dla czasu
var m = 0;														// czasu minuty
var s = 0;														// czasu sekundy
var end;														// koniec gry?
var he = 35;													// wysokość górnego paska
var aSize = localStorage.getItem('aElements');					// rozmiar planszy / pierwiastek elementów
var aShowBg = localStorage.getItem('aShowBg');					// pokazywanie tła planszy (allways/never/5s)
var c = aSize*aSize;											// ilość elementów
var r = null;													// id przeciąganego puzzla
var zIndex = 1;													// zIndex puzzli
var im = 1;														// numer obrazka (wartość domyślna)
var wi = window.innerWidth;										// szerokość okna
var hi = window.innerHeight-he;									// wysokość okna bez paska
if(hi>=wi)mi=wi;												// jeśli tryb pionowy to mniejszy wymiar to szerokość
if(hi<wi)mi=hi;													// jeśli tryb poziomy to mniejszy wymiar to wysokość
var w  = mi/aSize;												// wymiar puzzla
var er = w*0.1;													// tolerancja przyciągania
var aBoard = new Array(c+1);									// tablica z numerami id kolejnych puzzli
var pa = new Array(c+1);										// tablica przyklejonych puzzli (boolean)
var aImages = 13;												// ilość obrazków
var LSaImg = localStorage.getItem("aImg");						// numer obecnie używanego obrazka
if(LSaImg != null) im = parseInt(LSaImg);	
	
onload=function(){
	if(LSaImg==999){
		pick('image/*', false, 720, 720);
	}else{
		if(aShowBg!="never") document.getElementById("board").style.backgroundImage = 'url(img/'+im+'.jpg)';
		else document.getElementById("board").style.backgroundColor = "#424F5A";
		aStart();
		iTime();
	}
	window.addEventListener("resize", reDraw, false);
}

function pick(type, nocrop, width, height) {
  var data = {type: type};
  if (nocrop) data.nocrop = true;
  if (width) data.width = width;
  if (height) data.height = height;
  var a = new MozActivity({ name: 'pick', data: data});
  a.onsuccess = function(e) {
    var url = URL.createObjectURL(a.result.blob);
	localStorage.setItem("aUrl", url);
	if(aShowBg!="never")  document.getElementById("board").style.backgroundImage = 'url('+url+')';
	else document.getElementById("board").style.backgroundColor = "#424F5A";
	aStart();
	iTime();
  };
}

function iTime() {
	interval = window.setInterval("aTime()", 1000);
}

function aTime(){
	s = s+1;
	if(s == 60){
		m = m + 1;
		s = 0;
		if(m<10) document.getElementById('timem').innerHTML = "0"+m;
		else document.getElementById('timem').innerHTML = m;
	}
	if(s<10) document.getElementById('times').innerHTML = "0"+s;
	else document.getElementById('times').innerHTML = s;
	if(m==0&&s==5&&aShowBg=="5s"){
		document.getElementById("board").style.backgroundColor = "#424F5A";
		document.getElementById("board").style.backgroundImage = null;
	}
}

function aMenu(){
	interval = clearInterval(interval);
	me = document.getElementById("menu").style.display;
	hed = document.getElementById("header");
	if(!end && me != 'block'){
		he.innerHTML = "Menu";
		document.getElementById("nextlevel").style.display = "none";
		document.getElementById("continue").style.display = "block";
		document.getElementById("menu").style.display = "block";
	}else if(!end){
			document.getElementById("menu").style.display = "none";
			iTime();
	}else{
		hed.innerHTML = navigator.mozL10n.get('level-complete');
		if(im<aImages)document.getElementById("nextlevel").style.display = "block";
		document.getElementById("continue").style.display = "none";
		document.getElementById("menu").style.display = "block";
	}
}

function aNext(){
	localStorage.setItem("aImg", im+1);
	location.href='game.html';
}

function getXY(e) {				// punkt dotknięcia
	x =  parseInt(e.changedTouches[0].clientX);
	y =  parseInt(e.changedTouches[0].clientY);
	if(r){						// przenoszony element o id równym r
		rId = parseInt(r.substring(1, 3));
		j1 = rId%aSize-1
		if(j1 < 0)j1=aSize-1;
		j2 = Math.floor((rId-1)/aSize);
		document.getElementById(r).style.top = (y-w/2)+'px'; 
		document.getElementById(r).style.left = (x-w/2)+'px'; 
		document.getElementById(r).style.zIndex = zIndex; 
	}
}

function aGlue(pi,a1,a2){		// przyklej puzzla (id elementu,top,left)
		old_element = document.getElementById(pi);						//
		new_element = old_element.cloneNode(true);						// usuwa eventListener
		old_element.parentNode.replaceChild(new_element, old_element);	//	
		r = null;
		document.getElementById(pi).style.top = a1+'px'; 
		document.getElementById(pi).style.left = a2+'px'; 
		document.getElementById(pi).style.zIndex = 0; 
		document.getElementById(pi).classList.add("opacity");
}

function aVerify(p){			// sprawdza czy element jest na swoim miejscu
	var avId=1;
	for(var i=0;i<aSize;i++){
		for(var j=0;j<aSize;j++){
			if(p == "p"+avId && x > j*w+w/2-er && y > i*w+w/2+he-er && x < j*w+w/2+er && y < i*w+w/2+he+er){
				aGlue(p,he+i*w,j*w);
				pa[avId] = true;
			}
			avId++;
		}
	}
}

function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function aStart(){
	 document.addEventListener('touchmove', getXY, false);
     n = c;
     var aNum = new Array(n);
	   for (var i=0; i<=n; i++) {
		  aNum[i] = i + 1;
	   }
	   for (var i=0; i<=c; i++) {
		  l = Math.floor(Math.random()*n);
		  aBoard[i+1] = aNum[l];
		  aNum[l] = aNum[n - 1];
		  n--;
	   }   
	for (var i=1; i<=c; i++) {
		b = aBoard[i];
		j1 = b%aSize-1
		if(j1 < 0)j1=aSize-1
		j2 = Math.floor((b-1)/aSize);
		if(hi > mi)ra = random(mi+he,hi+he-w);
		if(wi > mi)rb = random(mi,wi-w);
		if(hi <= mi)ra = random(he,he+mi-w);
		if(wi <= mi)rb = random(0,mi-w);
		document.getElementById("board").innerHTML += "<div class='r"+i+"' id='p"+b+"'></div>";
		document.getElementById("p"+b).style.width = w+'px'; 
		document.getElementById("p"+b).style.height = w+'px'; 	
		document.getElementById("p"+b).style.top = ra+'px'; 
		document.getElementById("p"+b).style.left = rb+'px'; 
		document.getElementById("p"+b).style.zIndex = 1;
		if(LSaImg==999) document.getElementById("p"+b).style.backgroundImage = 'url('+localStorage.getItem("aUrl")+')';
		else document.getElementById("p"+b).style.backgroundImage = 'url(img/'+im+'.jpg)';
		document.getElementById("p"+b).style.backgroundPosition = '-'+j1*w+'px -'+j2*w+'px';
		document.getElementById("p"+b).style.backgroundSize = mi+'px '+mi+'px';
		document.getElementById("board").style.width = mi+'px';
		document.getElementById("board").style.height = mi+'px';
		document.getElementById("board").style.backgroundSize = mi+'px '+mi+'px';
	}
	for (var ci=1; ci<=c; ci++) {
		document.getElementById("p"+ci).addEventListener("touchstart", function(u){aShift(this.id);}, false);
		document.getElementById("p"+ci).addEventListener("touchend", function(u){bTouch(this.id);}, false);
	}
}

function reDraw(){
	wi = window.innerWidth;
	hi = window.innerHeight-he;
	if(hi>=wi)mi=wi;
	if(hi<wi)mi=hi;
	w = mi/aSize;
	for (var i=1; i<=c; i++) {
		b = aBoard[i];
		j1 = b%aSize-1				// oblicza w której linii znajduje się element (od 0 do aSize-1)
		if(j1 < 0)j1=aSize-1;
		j2 = Math.floor((b-1)/aSize);	// oblicza w której kolumnie znajduje się element (od 0 do aSize-1)
		if(hi > mi)ra = random(mi+he,hi+he-w);
		if(wi > mi)rb = random(mi,wi-w);
		if(hi <= mi)ra = random(he,he+mi-w);
		if(wi <= mi)rb = random(0,mi-w);
		leClass= document.getElementById("p"+b).className.length;
		if(leClass<10){	
			document.getElementById("p"+b).style.top = ra+'px'; 
			document.getElementById("p"+b).style.left = rb+'px'; 
			document.getElementById("p"+b).style.zIndex = 1;
		}else{
			wb1top = parseInt(document.getElementById("p"+b).style.top);
			wb1left = parseInt(document.getElementById("p"+b).style.left);
			wb1height = parseInt(document.getElementById("p"+b).style.height);
			wb2top = Math.floor((wb1top - he)/wb1height+0.1);
			wb2left = Math.floor(wb1left/wb1height+0.1);
			document.getElementById("p"+b).style.top = wb2top*w+he+'px'; 
			document.getElementById("p"+b).style.left = wb2left*w+'px'; 
		}
		document.getElementById("p"+b).style.width = w+'px'; 
		document.getElementById("p"+b).style.height = w+'px';
		document.getElementById("p"+b).style.backgroundPosition = '-'+j1*w+'px -'+j2*w+'px';
		document.getElementById("p"+b).style.backgroundSize = mi+'px '+mi+'px';
		document.getElementById("board").style.width = mi+'px';
		document.getElementById("board").style.height = mi+'px';
		document.getElementById("board").style.backgroundSize = mi+'px '+mi+'px';
	}
}

function win(){
	end = true;
	h = parseInt(localStorage.getItem("time_"+aSize+""+aShowBg+"_m"+im));
	i = parseInt(localStorage.getItem("time_"+aSize+""+aShowBg+"_s"+im));
	if(m == h && s < i){
		localStorage.setItem("time_"+aSize+""+aShowBg+"_s"+im, s);
	}else if(m < h || isNaN(h)){
		localStorage.setItem("time_"+aSize+""+aShowBg+"_m"+im, m);
		localStorage.setItem("time_"+aSize+""+aShowBg+"_s"+im, s);
	}
	aMenu();
}

function aShift(e){
	r = e;
	zIndex++;
}

function bTouch(e){
	aVerify(r);
	ou=0;
	for(var i=1;i<=c;i++){
	   if(pa[i]!=true)ou++;
	}
	if(ou==0)win();
	r = null;
}