var active_object = null;
var spielfeld = false;
var nSp = 0; 		// Anz Spalten
var nZl = 0;		// Anz Zeilen
//var sSp = 1; 		// Start mit Spalte
//var sZl = 1;		// Start mit Zeile
var bild_br =  0; 	// Bildchen-Breite +1
var bild_ho = 0; 	// Bildchen-Höhe +1

// Position angeklicktes Objekt
var start_x = 0;
var start_y = 0;

// Aktuelle Position Mauszeiger
var mouse_x = 0;
var mouse_y = 0;

// Abstand vom Rahmen
var oben  = 5;
var links = 5;

// ist alles richtig ?
var ok = false;

function zufall_sort (a, b) {
  return a[2] - b[2];
}

//Positionen der Hintergrundbilder mischen
function mischen(){

  document.getElementById("BildBox").style.border = "solid 1px #000";

	spielfeld = new Array(nZl-1);

	var n = nSp * nZl;
	var zufall = new Array(n);
	var i,z,sp = 0;
	for (z = 0; z < nZl; z++){
		spielfeld[z] = new Array(nSp-1);
		for (sp = 0; sp < nSp; sp++){
			zufall[z*nSp+sp] = new Array(z,sp,Math.random());
		}
	}

	zufall.sort(zufall_sort);

	var element = null;
	var austausch = null;
	var z_neu = 0;
	var sp_neu = 0;
	var x = 0;
	var y = 0;

	for (i = 0; i < n; i++){
		z_neu  = zufall[i][0];
		sp_neu = zufall[i][1];
		x= i % nSp;
		y= Math.floor(i/nSp);
		element = document.getElementById("P"+(z_neu+1)+(sp_neu+1));
		element.style.top   = oben + y  * bild_ho + "px";
		element.style.left  = links + x * bild_br + "px";
		spielfeld[y][x] = element;
	}

	// prüfen ob nicht schon an der richtigen Position
	for (z = 0; z < nZl; z++){
		for (sp = 0; sp < nSp; sp++){
			if (spielfeld[z][sp].id == "P"+(z+1)+(sp+1)) {
				if (0 === z+sp) {
					z_neu = nZl-1;
					sp_neu = nSp-1;
				} else {
					z_neu = 0;
					sp_neu = 0;
				}

				element = document.getElementById(spielfeld[z][sp].id);
				element.style.top   = oben + z_neu  * bild_ho + "px";
				element.style.left  = links + sp_neu * bild_br + "px";

				austausch = document.getElementById(spielfeld[z_neu][sp_neu].id);
				austausch.style.top   = oben + z  * bild_ho + "px";
				austausch.style.left  = links + sp * bild_br + "px";

				spielfeld[z_neu][sp_neu] = element;
				spielfeld[z][sp] = austausch;
			}
		}
	}

	var h3 = document.getElementById("fertig");
	h3.firstChild.data ="Noch ist das Bild nicht richtig!";
	h3.style.color= '#c00';
	//document.getElementById("BildLaden").style.visibility = "hidden";
	ok = false;
}

function alles_ok(){
	var fertig =true;
	var z,sp = 0;
	Loop: for (z = 0; z < nZl; z++){
		for (sp = 0; sp < nSp; sp++){
			if (spielfeld[z][sp].id != "P"+(z+1)+(sp+1)) {
				fertig = false;
				break Loop;
			}
		}
	}
	if (fertig) {
		var top = 0;
		var dx = Math.floor(nSp/2);
		var dy = Math.floor(nZl/2);
		for (z = 0; z < nZl; z++){
			top = oben+ dy + z  * (bild_ho-1) + "px";
			for (sp = 0; sp < nSp; sp++){
				var bild = spielfeld[z][sp];
				bild.style.top = top;
				bild.style.left = links+dx  + sp *(bild_br-1) + "px";
			}
		}

		document.getElementById("BildBox").style.border = "ridge 12px #ffd700";
		var h3 = document.getElementById("fertig");
		h3.firstChild.data = "Perfekt! Genau so muss es aussehen!";
		h3.style.color = "#080";
		ok = true;
	}
}

function glue_ruler() {
	var diffx;
	var diffy;
	var z;
	var sp;

	if(active_object !== null) {

		diffx = active_object.offsetLeft-links;
		if (diffx < 0) {
			sp = 0;
		} else {
			sp = Math.floor((diffx+bild_br/2)/bild_br);
			sp = Math.min(nSp-1,sp);
		}

		diffy = active_object.offsetTop-oben;
		if (diffy < 0) {
			z = 0;
		} else {
			z = Math.floor((diffy+bild_ho/2)/bild_ho);
			z = Math.min(nZl-1,z);
		}

		active_object.style.left = links + sp * bild_br + "px";
		active_object.style.top =  oben + z  * bild_ho + "px";

		var old_object = spielfeld[z][sp];
		if (old_object != active_object) {
			var gefunden = false;
			for (var z1 = 0; z1 < nZl; z1++){
				for (var sp1 = 0; sp1 < nSp; sp1++) {
					if (false === gefunden) {
						if (active_object == spielfeld[z1][sp1]) {
							old_object.style.left = links + sp1 * bild_br + "px";
							old_object.style.top =  oben + z1  * bild_ho + "px";
							spielfeld[z1][sp1] = old_object;
							gefunden = true;
						}
					}
				}
			}
			spielfeld[z][sp] = active_object;
			alles_ok();
		}
		active_object.style.zIndex = 0;
	}
}

// Wird bei Mausbewegung aktiviert und berechnet neue Pos Quadrat
function start_moving(event) {
  mouse_x = document.all ? window.event.clientX : event.pageX;
  mouse_y = document.all ? window.event.clientY : event.pageY;
  if(active_object !== null) {
    active_object.style.left = (mouse_x - start_x) + "px";
    active_object.style.top = (mouse_y - start_y) + "px";
  }
}

// Beendet Bewegung
function stop_moving() {
	if(active_object !== null) {
		glue_ruler();
		active_object.style.cursor = "auto";
		active_object = null;
	}
}

function get_ready(nSpalten,nZeilen) {

	var Box = document.getElementById("BildBox");
	var myBild = document.getElementById("Bild");
	nSp = nSpalten;
	nZl  = nZeilen;

	//sSp =  1;
	//sZl  = 1;
	;
	var breite = myBild.width / nSpalten;
	var hoehe  = myBild.height / nZeilen;

	bild_br = breite + 1;
	bild_ho = hoehe + 1;

	var myDiv = 0;
	var myText =0;
	var onmouse = 0;
	var idnr = 0;
	var name = "";

	// erstmal alles unterhalb der Box löschen
	while (Box.hasChildNodes()) {
		Box.removeChild(Box.firstChild);
	}

	// dann für jedes Bildchen ein div anlegen mit name Pzs z.B. P11
	var html = "";
	var proz_links, proz_oben = 0;
	for (var z = 1; z <= nZl; z++){
		for (var sp = 1; sp <= nSp; sp++){
			proz_links = (2>nSp) ? 0:100/(nSp-1)*(sp-1);
			proz_oben =  (2>nZl) ? 0:100/(nZl-1)*(z-1);
			if (document.all) {
				html += "<div id='P"+z+sp+"' onmousedown='prepare_move(this)' style='position:absolute; width:"+breite+"px; height:"+hoehe+"px; background:transparent url(" +myBild.src + ") no-repeat " +proz_links + "% " + proz_oben + "%;'></div>";
			} else {
				idnr = document.createAttribute("id");
				idnr.nodeValue = "P"+z+sp;
				onmouse = document.createAttribute("onmousedown");
				onmouse.nodeValue = "prepare_move(this)";
				myDiv = document.createElement("div");
				myDiv.setAttributeNode(idnr);
				myDiv.setAttributeNode(onmouse);

				myDiv.style.position = "absolute";
				myDiv.style.width = breite+"px";
				myDiv.style.height = hoehe+"px";
				myDiv.style.background = "transparent url(" +myBild.src + ") no-repeat " +proz_links + "% " + proz_oben + "%";

				Box.appendChild(myDiv);
			}
		}
	}
	if (document.all) Box.innerHTML = html;
	Box.style.width = nSp * bild_br + (links-1)*2 + "px";
	Box.style.height = nZl * bild_ho + (oben-1) * 2 + "px";
//
//	idnr = document.createAttribute("id");
//	idnr.nodeValue = "BildLaden";
//	myDiv = document.createElement("div");
//	myDiv.setAttributeNode(idnr);
//	myDiv.style.position = "absolute";
//	myDiv.style.width =  nSp * bild_br + (links-1)*2 + "px";
//	myDiv.style.height = nZl * bild_ho + (oben-1) * 2  + "px";
//	myDiv.style.top =  "1px";
//	myDiv.style.left = "1px";
//	myDiv.style.color = "black";
//	myDiv.style.backgroundColor = "white";
//	myDiv.style.fontSize = "250%";
//	myDiv.style.padding  = "2em";
//	myText = document.createTextNode("Ein bisschen Geduld bitte,das Bild wird geladen");
//	myDiv.appendChild(myText);
//	Box.appendChild(myDiv);

	mischen();
	document.onmousemove = start_moving;
	document.onmouseup =   stop_moving;
}


// Bereitet Bewegung vor
function prepare_move(obj) {
  if (!ok) {
    if (null === active_object){
      active_object = obj;
      start_x = mouse_x - active_object.offsetLeft;
      start_y = mouse_y - active_object.offsetTop;
      active_object.style.zIndex = 1;
      active_object.style.cursor = "move";
    }
  } else {
  	 var antwort = confirm('Dieses Bild neu mischen?');
  	 if (antwort) { mischen(); }
  }
}
