/**
 * Functions for dalliKlick
 *
 * @copyright 	copyright (c) 2008 by GMX GmbH
 * @author 		matthias kurte
 */


// Init dalliKlick-Namespace
var dalliKlick = {

	// Intitial Function
	init: function() {

		/* AB HIER NICHTS MEHR ÄNDERN!!! */

		/*if(navigator.userAgent.indexOf("MSIE 6.0")!=-1) {
			this.pieces = 256;
		}*/

		/* Some last Configurations */
		this.actClick		= 0;
		this.textAfterTipp += " <a href=\"javascript:dalliKlick.newGameLink();\">Lust auf ein neues Spiel?</a>"; // Please don't change
		this.textRight		= "Richtig! " + this.textAfterTipp; // Please don't change
		this.textFalse		= "Falsch! <a href=\"javascript:dalliKlick.showPieces();\">N&auml;chster Spielzug</a>"; // Please don't change
		this.restPieces		= this.pieces;
		this.restClicks		= this.maxClicks;

		// Add CSS
		document.getElementsByTagName('head')[0].appendChild(
			this.newElement('link', {'type':'text/css', 'rel':'stylesheet', 'href':this.cssFile})
		);

		/* Class Definitions */
		if(this.format == 0) {
			this.playgroundClass = "square-div";
			if(this.pieces == 256) {
				this.piecesClass = "square-fewpieces";
			} else if(this.pieces == 1024) {
				this.piecesClass = "square-muchpieces";
			}
		} else if(this.format == 1) {
			this.playgroundClass = "rectangle-div";
			if(this.pieces == 256) {
				this.piecesClass = "rectangle-fewpieces";
			} else if(this.pieces == 1024) {
				this.piecesClass = "rectangle-muchpieces";
			}
		}
		this.newSpanClass = "" + this.piecesClass + "-openpiece";

		// Add Backgroundimage CSS
		/*poma.dom.appendTags(document.getElementsByTagName('head')[0], [
		   {'style': {
			   'type': 'text/css',
			   '#text': '#dalli-klick span.'+ this.newSpanClass +' { background: url('+ this.backgroundImage + ') top left no-repeat; }'
		   }}
		]);*/

		/* BUILD GAME */
		this.buildGame();

	},

	// Get the actual Host
	getHost: function() {
		var hosturl;
		if (window.location.host.indexOf("gmx.net") != -1) {
			hosturl = "portal.gmx.net";
		} else if (window.location.host.indexOf("web.de") != -1) {
			hosturl = "magazine.web.de";
		} else if (window.location.host.indexOf("1und1.de") != -1) {
			hosturl = "portal.1und1.de";
		}
		return hosturl;
	},

	// Build Game
	buildGame: function() {
		poma.dom.$id("dalli-klick").className = this.playgroundClass;
		for(var i=1; i<=this.pieces; i++) {
			poma.dom.appendTags(poma.dom.$id("dalli-klick"), [
					{"span": {
						"id": "dalli-" + i,
						"class": this.piecesClass
					}}
				]);
			poma.dom.$id("dalli-" + i).onclick = function() {
				dalliKlick.showPieces();
			}
		}
		poma.dom.$id("dalli-newcontent").innerHTML = this.initialText;

		//Fill up Array
		if(this.tipps.length < (this.maxClicks-1)) {
			var myKlicksKey = this.maxClicks;
			var mySpeicherKey = this.tipps.length-1;
			var mySpeicherKeyRes = this.tipps.length-1;
			for (var i = myKlicksKey-2; i > mySpeicherKeyRes; i--) {
				this.tipps[i] = this.tipps[mySpeicherKey];
				mySpeicherKey--;
				myKlicksKey--;
				if (mySpeicherKey < 0) {
				mySpeicherKey = mySpeicherKeyRes;
				}
			}
		}
	},

	// Show some Pieces
	showPieces: function() {
		if(this.actClick == 0) {
		  this.changeTippButton('btn-nextturn', 'btn-startgame');
		}
        if(this.actClick <= this.maxClicks) {
			var openPieces;
			if(this.restPieces%this.restClicks != 0) { //we got a modulo
				openPieces = parseInt(this.restPieces/this.restClicks) + 1;
			} else {  // we got no modulo
				openPieces = this.restPieces/this.restClicks;
			}
			this.restPieces -= openPieces;
			this.openRandomPieces(openPieces);
			this.restClicks--;
			if(this.actClick < this.maxClicks-1) {
				this.showTipps(this.actClick);
			} else {
				poma.dom.$id("dalli-newcontent").innerHTML = "Das Spiel ist beendet. " + this.textAfterTipp;
				this.changeTippButton('btn-newgame', 'btn-nextturn');
			}

			//count pi
			countAndRefresh();
			
		} else {
			poma.dom.$id("dalli-newcontent").innerHTML = "Das Spiel ist beendet. " + this.textAfterTipp;
			this.changeTippButton('btn-newgame', 'btn-nextturn');
		}
		this.actClick++;
	},

	// Open up some Pieces
	openRandomPieces: function(count) {
		var i = 0;
		while(i<count) {
			var digit = this.randomNumber(1,this.pieces);
			if(poma.dom.$id("dalli-" + digit).className != this.newSpanClass) {
				poma.dom.$id("dalli-" + digit).className = this.newSpanClass;
				this.openPiece(digit);
				i++;
			}
		}
	},

	// Open up all Pieces
	showAll: function() {
		for(var i=1; i<=this.pieces; i++) {
			if(poma.dom.$id("dalli-" + i).className != this.newSpanClass) {
				poma.dom.$id("dalli-" + i).className = this.newSpanClass;
				this.openPiece(i);
			}
		}
	},

	openPiece: function(digit) {
		var helper;
		if(this.pieces == 256) { helper = 16; } else if(this.pieces == 1024) { helper = 32; }
		var row = parseInt(digit / helper) + 1;
		var col, xpos, ypos;
		// set background position
		if(digit%helper == 0) { row--; }
		if(row == 1) {
			col = digit;
		} else {
			col = ((helper * row) - digit);
			col = helper - col;
			if(col == 0) { col = helper; }
		}
		// in case of format and number of pieces
		switch(this.format) {
			case 0:
				switch(this.pieces) {
					case 256:
						xpos = (col * 22) - 22;
						ypos = (row * 22) - 22;
						poma.dom.$id("dalli-" + digit).style.height = "22px";
						poma.dom.$id("dalli-" + digit).style.width = "22px";
						break;
					case 1024:
						xpos = (col * 11) - 11;
						ypos = (row * 11) - 11;
						poma.dom.$id("dalli-" + digit).style.height = "11px";
						poma.dom.$id("dalli-" + digit).style.width = "11px";
						break;
				}
			break;
			case 1:
				switch(this.pieces) {
					case 256:
						xpos = (col * 28) - 28;
						ypos = (row * 16) - 16;
						poma.dom.$id("dalli-" + digit).style.height = "16px";
						poma.dom.$id("dalli-" + digit).style.width = "28px";
						break;
					case 1024:
						xpos = (col * 14) - 14;
						ypos = (row * 8) - 8;
						poma.dom.$id("dalli-" + digit).style.height = "8px";
						poma.dom.$id("dalli-" + digit).style.width = "14px";
						break;
				}
			break;
		}
		poma.dom.$id("dalli-" + digit).style.backgroundImage = "url("+this.backgroundImage+")";
		poma.dom.$id("dalli-" + digit).style.backgroundRepeat = "no-repeat";
		poma.dom.$id("dalli-" + digit).style.backgroundPosition = "-" + xpos + "px -" + ypos + "px";
	},

	// Show a smashing tipp!
	showTipps: function(tippNumber) {
		poma.dom.$id("dalli-newcontent").innerHTML = this.tipps[tippNumber];
	},

	// Build a form to answer what it is
	answerQuestion: function() {
		var placeHere = poma.dom.$id("dalli-newcontent");
		if(placeHere.firstChild) {
			while(placeHere.firstChild) {
				placeHere.removeChild(placeHere.firstChild)
			}
		}
		if(this.actClick < this.maxClicks) {
    		var formElement = document.createElement("form")
    		if(this.actClick == 1) {
    		  this.changeTippButton('btn-nextturn', 'btn-startgame');
            }
    		formElement.setAttribute("action", "javascript:dalliKlick.checkAnswer();");
    		formElement.setAttribute("name", "dalli-answerform");
    		formElement.setAttribute("id", "dalli-answerform");
    		placeHere.appendChild(formElement);
    		for(var i=0; i<this.answer.length; i++) {
    			placeHere = poma.dom.$id("dalli-answerform");
    			var divElement = document.createElement("div");
    			divElement.setAttribute("class", "dalli-answer");
    			divElement.setAttribute("id", "dalli-answer-div" + i);
    			placeHere.appendChild(divElement);
    			try {
    				formElement = document.createElement("<input type=\"radio\" name=\"dalli-answer\" />");
    			} catch(err) {
    				formElement = document.createElement("input");
    				formElement.setAttribute("type", "radio");
    				formElement.setAttribute("name", "dalli-answer");
    			}
    			formElement.setAttribute("id", "dalli-answer-" + i);
    			formElement.setAttribute("value", i);
    			placeHere = poma.dom.$id("dalli-answer-div" + i);
    			placeHere.appendChild(formElement);
    			var labelElement = document.createElement("label")
    			labelElement.setAttribute("htmlFor", "dalli-answer-" + i);
    			labelElement.setAttribute("for", "dalli-answer-" + i);
    			labelElement.innerHTML = this.answer[i];
    			placeHere.appendChild(labelElement);
    		}
    		divElement = document.createElement("div");
    		divElement.setAttribute("class", "dalli-submit");
    		divElement.setAttribute("id", "dalli-submit-div");
    		placeHere = poma.dom.$id("dalli-answerform");
    		placeHere.appendChild(divElement);
    		var submitElement = document.createElement("input");
    		submitElement.setAttribute("type", "submit");
    		submitElement.setAttribute("name", "dalli-submit");
    		submitElement.setAttribute("id", "dalli-submit-input");
    		submitElement.setAttribute("value", unescape("aufl%F6sen"));
    		placeHere = poma.dom.$id("dalli-submit-div");
    		placeHere.appendChild(submitElement);
    	} else {
    	   poma.dom.$id("dalli-newcontent").innerHTML = "Sie haben die Frage bereits beantwortet. " + this.textAfterTipp;
    	}

	},

	// Was the answer right or false?
	checkAnswer: function() {
		if(poma.dom.$id("dalli-answer-" + this.rightAnswer).checked) {
			this.showAll();
			this.changeTippButton('btn-newgame', 'btn-nextturn');
			this.actClick = this.maxClicks+1;
			poma.dom.$id("dalli-newcontent").innerHTML = this.textRight;
		} else {
			poma.dom.$id("dalli-newcontent").innerHTML = this.textFalse;
		}
	},

	// Change Buttons
	changeTippButton: function(blendInId, blendOutId) {
		poma.dom.$id(blendInId).style.display = "block";
		poma.dom.$id(blendOutId).style.display = "none";

	},

	// Give us a random number, please.
	randomNumber: function(min, max) {
		return Math.floor(min+(max-min+1)*(Math.random()));
	},

	// Go to new target
	newGameLink: function() {
		document.location.href = this.linkAfterGame;
	},

	isUndefined: function(obj) {
		return typeof(obj) == 'undefined';
	},

	isNull: function(obj) {
		return obj === null;
	},

	isNone: function(obj) {
		return dalliKlick.isUndefined(obj) || dalliKlick.isNull(obj);
	},

	isSet: function(obj) {
		return !dalliKlick.isNone(obj);
	},

	newElement: function(name, attr, content) {
		var elem = document.createElement(name);
		if (dalliKlick.isSet(attr)) {
		  for (var a in attr) {
			if (dalliKlick.isNone(Object.prototype[a])) {
			  if (a == 'class') {
				elem.className = attr[a];
			  }
			  else if (a == 'style') {
				elem.style.cssText = attr[a];
			  }
			  else {
				elem[a] = attr[a];
			  }
			}
		  }
		}
		if (dalliKlick.isSet(content)) {
		  if (dalliKlick.isPrimitive(content) && (dalliKlick.isString(elem.text))) {
			elem.text = content;
		  }
		  else {
			elem.appendChild(dalliKlick.isPrimitive(content) ? document.createTextNode(content) : content);
		  }
		}
		return elem;
	}
}
