/*		
 * Copyright (C) 1995-2011 by 4system Polska Sp. z o.o.
 * All Rights Reserved. v4
 */

componentPuzzleText = function(name) {
	this.__componentText = __componentText;
	this.__componentText(name);
	
	this.passed = false;
	this.basketsCount = 0;
	this.texts = new Array();
	this.componentX = 0;
	this.componentY = 0;	
	this.complete = false;
	
	this.interactions = true;
	this.interactionsType = "matching";			
};

componentPuzzleText.prototype = new __componentText;
componentPuzzleText.prototype.type = "componentPuzzleText";
componentPuzzleText.prototype.onBaseCreate = function(obj) {
	this.captureMouseEvents();
};

componentPuzzleText.prototype.componentPuzzleTextBaseOnCreate = componentPuzzleText.prototype.onCreate;
componentPuzzleText.prototype.onCreate = function(obj) {
	this.componentPuzzleTextBaseOnCreate();
	if (PageInterface.GetValue("state") != psDesigning) {
		var sizeDiv = '<span id="sizeDiv" style="visibility: hidden; position: absolute; font-family:' + this.font.family
		+ '; font-size:' + getFontSize(this.font.size, "px") + 'px; color:' + this.font.color + ';"></span>';
		
		var ob = document.getElementById(this.id);
		ob.innerHTML += sizeDiv;

		var width = 0;
		var height = 0;
		var tempX = this.x+this.borderWidth+1;
		var tempY = this.y + this.h - 1;
		var tempWidth = 0;
		var onlyText;
		
		//var match = this.text.split(" ");
		var match = this.getSeparateBlocks(this.text);
		
		this.basketsCount = match.length;
		this.dynamicWidth = false;
		this.maxWidth = 0;
		if (!this.dynamicWidth) {
			for (var i=0; i<this.basketsCount; i++) {
				// Czysty tekst bez nawiasow
				onlyText = match[i];

				// tymczasowy element do ustalania szerokosci i wysokosci ddelementow
				if (document.getElementById("sizeDiv")) {
					document.getElementById("sizeDiv").innerHTML = onlyText;
					width = document.getElementById("sizeDiv").offsetWidth;
					height = document.getElementById("sizeDiv").offsetHeight;// + this.elementPadding;;
				}
				if ( width > this.maxWidth ) this.maxWidth = width;
			}
			width = this.maxWidth + this.elementPadding;
		};
		var baskets = "";
		if (this.showBaskets){
			var divBorder = 1;
			var additonalHeight =  1;//this.elementPadding - 1;
		}else{
			baskets += "<div style='position: relative; height:"+eval(height+2)+"px; display:inline; float:left; border: 1px solid black'>";
			var divBorder = 0;
			var additonalHeight = -3;//this.elementPadding - 3;
		};
		
		for (var i=0; i<this.basketsCount; i++) {
			onlyText = match[i];
			
			if (this.showPunctuationMark){
				if (typeof(match[i-1]) != 'undefined'){
					prevWord = match[i-1];
					onlyText = onlyText.replace(',', '');
					onlyText = onlyText.replace('.', '');
					onlyText = onlyText.replace(';', '');
					
					if (prevWord.indexOf(',') != -1){
						baskets += "<div style='position: relative; display:inline; float:left; border: "+divBorder+"px solid black; width: 0px; height: " + (height+additonalHeight+1) + "px; margin: 0px; font-size: "+getFontSize(this.font.size, "px")+"; font-color: "+this.font.color+"; font-family: "+this.font.family+"' ><b>,</b></div>";
					}else if (prevWord.indexOf('.') != -1){
						baskets += "<div style='position: relative; display:inline; float:left; border: "+divBorder+"px solid black; width: 0px; height: " + (height+additonalHeight+1) + "px; margin: 0px; font-size: "+getFontSize(this.font.size, "px")+"; font-color: "+this.font.color+"; font-family: "+this.font.family+"' ><b>.</b></div>";
					}else if (prevWord.indexOf(';') != -1) {
						baskets += "<div style=position: relative; 'display:inline; float:left; border: "+divBorder+"px solid black; width: 0px; height: " + (height+additonalHeight+1) + "px; margin: 0px; font-size: "+getFontSize(this.font.size, "px")+"; font-color: "+this.font.color+"; font-family: "+this.font.family+"' ><b>;</b></div>";
					};
				};
			};
			var basketName = onlyText.replace(/'/g, '#');
			basketName = basketName.replace(/"/g, '$');
			baskets += "<textarea name='"+this.id+"_"+basketName+"' id=_"+this.id+"_"+i+"_basket style='background:white; display:inline; float:left; border: "+divBorder+"px solid black; width: " + eval(width+this.elementPadding) + "px; height: " + (height+additonalHeight+1) + "px; margin: 0px; font-size: "+getFontSize(this.font.size, "px")+"; font-color: "+this.font.color+"; font-family: "+this.font.family+"; overflow: hidden;' disabled ></textarea>";
			baskets += "<div style='position: relative; display:inline; float:left; width: 1px; height: " + (height+additonalHeight+1) + "px;'></div>";
			
			if (i !=0 ){
				if ( (tempX + tempWidth + width + 2) >  (this.x + this.w) ) {
					if (this.elementsUp){
						tempX = this.x + this.borderWidth + 1;
						tempY += height + 8;//+ (this.elementPadding-3);
					}else{
						tempX = this.x + this.borderWidth + 1;
						tempY -= height + 8;//+ (this.elementPadding-3); 
					};
				}else { 
					tempX += tempWidth + 8 + (this.elementPadding-3);
				}
			}else{ 
				if (this.elementsUp){
					tempY = this.y + 2 + this.borderWidth;//+ (this.elementPadding-3);
					tempX += tempWidth + this.borderWidth;
				}else {
					tempY -= height + 2 + this.borderWidth;//+ (this.elementPadding-3);
					tempX += tempWidth + this.borderWidth;
				};
			};
			
			// powoladnie ddelementow
			var textTemp = new __componentText;
			textTemp.parentText = this; 
			textTemp.id = this.id+'_DDE_'+i; 
			textTemp.destinationBasketId = "_"+this.id+"_"+i+"_basket";
			textTemp.destinationBasketName = basketName;
			textTemp.text = onlyText;
			textTemp.x = tempX;
			textTemp.y = tempY;
			textTemp.x_backup = tempX;
			textTemp.y_backup = tempY;			
			textTemp.w = width;
			textTemp.h = height;
			textTemp.startX = tempX;
			textTemp.startY = tempY;
			
			if (!this.dynamicWidth) {
				textTemp.w = width+this.elementPadding;
				textTemp.h = height+2;//+this.elementPadding;
			};
			
			textTemp.canDragging = true;
			textTemp.borderWidth = 1;
			textTemp.borderColor = this.elementBorderColor;
			textTemp.padding = 0;
			textTemp.bgColor = this.elementBckColor;
			textTemp.step = -1;
			textTemp.align = "center";
			textTemp.valign = 'middle';
			textTemp.font = this.font;
			
			textTemp.onCreate = this.onCreateText;
			textTemp.beginDrag = this.beginDragText;
			textTemp.endDrag = this.endDragText;
			textTemp.onMove = this.mouseMoveText;
			
			textTemp.basketsCount = this.basketsCount; 
			textTemp.basketName = this.id+"_"+basketName; 			
				
			textTemp.solved = false;
			textTemp.orgZ = textTemp.z = this.z+i;
			textTemp.inArea = null;
			textTemp.insideBasketId = '';
			textTemp.insideBasketName = '';
			textTemp.cursor = this.ddelementCursor;
			
			tempWidth = width;
			page.addChild(textTemp);
			this.texts.push( textTemp );
		};
		this.randomDDElements();
		
		if (this.showPunctuationMark){
			if (typeof(match[i-1]) != 'undefined'){
				prevWord = match[i-1];
				if (prevWord.indexOf('.') != -1){
					baskets += "<div id=_"+this.id+"_"+i+"_basket style='position: relative; display:inline; float:left; border: "+divBorder+"px solid black; width: 0px; height: " + (height+additonalHeight) + "px; margin: 0px; font-size: "+getFontSize(this.font.size, "px")+"; font-color: "+this.font.color+"; font-family: "+this.font.family+"' ><b>.</b></div>";
				};
			};
		};
		
		if (!this.showBaskets){
			baskets += '</div>';
		};
		
		var rowsNumber = parseInt((tempY-this.y+height)/height);

		if (this.elementsUp){
			var rows = '<table height="'+eval(this.h-(rowsNumber+1)*height)+'"><tr><td></td></tr></table>';
		}else {
			var rows = '';
		};
	
		this.text = rows + baskets;
		
		var button = new componentRollover;
		button.parentText = this; 
		button.id = this.id+'buttonAdd'; 
		button.x = tempX + tempWidth + 3 + this.elementPadding;;
		button.y = tempY;
		button.w = this.addButtonW;
		button.h = this.addButtonH;
		button.srcOut = this.addButtonSrcOut;
		button.srcIn  = this.addButtonSrcIn;
		button.onClick = this.addNewElement;
		button.cursor = 'hand';
		button.active = true;
		
		this.texts.push(button);
		page.addChild(button);
		
		var content = this.findContentObj();
		content.innerHTML = baskets;
	};
	
	this.componentX = this.x;
	this.componentY = this.y;
};

componentPuzzleText.prototype.onCreateText = function(text) 
{
	this.captureMouseEvents();
};

componentPuzzleText.prototype.getSeparateBlocks = function(text) 
{
	var wordsArr = new Array();
	text = text.replace(/&nbsp;/gi, ' ');
	var splited = text.split('');
	var closeChar = ' ';
	var newBlock = '';
	
	for (var i=0; i < splited.length; i++){
		if (i == eval(splited.length-1) || splited[i] == closeChar && newBlock != '') {
			if (i == eval(splited.length-1) && splited[i] != closeChar) newBlock += splited[i];
			wordsArr[wordsArr.length] = newBlock;
			newBlock = '';
		};
		
		if (splited[i] == '{'){
			closeChar = '}';
 		}else if (splited[i] == '}'){
			closeChar = ' ';
		};
		
		if (splited[i] != '{' && splited[i] != '}'){
			if (splited[i] == ' ' && closeChar == '}') {
				newBlock += splited[i];
			}else if (splited[i] != ' '){
				newBlock += splited[i];
			}
		};
	};
	return wordsArr;
};

componentPuzzleText.prototype.randomSeparateBlocks = function(arr) 
{
	for (var i=0; i < arr.length; i++){
		j = parseInt(Math.random()*(arr.length));
		do{
			k = parseInt(Math.random()*(arr.length));
		}while(k == j)
		
		var before = arr[j];
		var after  = arr[k];
		var remember = {
			id : before.id, 
			destinationBasketId : before.destinationBasketId,
			text : before.text
		};
		
		before.id = after.id;
		before.destinationBasketId = after.destinationBasketId;
		before.text = after.text;
		
		after.id = remember.id;
		after.destinationBasketId = remember.destinationBasketId;
		after.text = remember.text;
	};
	return arr;
};

componentPuzzleText.prototype.onLoad = function() {

}

componentPuzzleText.prototype.componentPuzzleTextBaseOnPaint = componentPuzzleText.prototype.onPaint;
componentPuzzleText.prototype.onPaint = function() {
	this.componentPuzzleTextBaseOnPaint();
	var newX = this.componentX - this.x;
	var newY = this.componentY - this.y; 
	
	this.componentX = this.x;
	this.componentY = this.y;
	
	for (var i=0; i < this.basketsCount; i++) {
		this.texts[i].x = this.texts[i].x_backup;
		this.texts[i].y = this.texts[i].y_backup;
		this.texts[i].startX = this.texts[i].x_backup;
		this.texts[i].startY = this.texts[i].y_backup;
		
		this.texts[i].insideBasketId = '';
		this.texts[i].solved = false;
		
		this.texts[i].startX -= newX;
		this.texts[i].startY -= newY;
		
		this.texts[i].x -= newX;
		this.texts[i].y -= newY;
		
		this.texts[i].setX(this.texts[i].x);
		this.texts[i].setY(this.texts[i].y);
		
		this.texts[i].obj.style.border = this.elementBorderColor + " solid 1px";
		this.texts[i].obj.style.background = this.elementBckColor;
	};
	this.setButtonActivity(this.texts[this.texts.length-1], true) ;
};

componentPuzzleText.prototype.onShow = function() 
{
	if (PageInterface.GetValue("state") != psDesigning){
		for (var i=0; i < this.texts.length; i++) {
			this.texts[i].show();
		};
	};
};

componentPuzzleText.prototype.addNewElement = function() 
{
	if (this.parentText.complete) return;
	if (this.parentText.texts){
		var lastIndex = this.parentText.texts.length;
		var obj = this.parentText.texts[lastIndex-1];
		if (obj){
			if (obj.active) {
				for (var i=0; i < this.parentText.basketsCount; i++){
					var empty = true;
					var basketName = "_"+this.parentText.id+"_"+i+"_basket";
					
					for (var j=0; j < this.parentText.basketsCount; j++){
						if (this.parentText.texts[j].insideBasketId == basketName){
							empty = false;
							break;
						};
					};
					if (empty){
						if (this.parentText.texts[i].insideBasketId != ''){
							for (var k=0; k < this.parentText.basketsCount; k++){
								if (this.parentText.texts[i].id != this.parentText.texts[k].id
									&& this.parentText.texts[i].text == this.parentText.texts[k].text ){
										var ddelement = document.getElementById(this.parentText.texts[k].id);
										var basket = document.getElementById(basketName);
										this.parentText.setIntoBasket(this.parentText.texts[k], ddelement, basket);
									break;
								};
							};
						}else{
							var ddelement = document.getElementById(this.parentText.texts[i].id);
							var basket = document.getElementById(basketName);
							this.parentText.setIntoBasket(this.parentText.texts[i], ddelement, basket);
						};
						break;
					};
				};
				if (this.parentText.checkIsCorrectSequence()) this.parentText.setButtonActivity(this, false);
			};
		};
	};
};

componentPuzzleText.prototype.findPosX = function (obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}else if (obj.x){
		curleft += obj.x;
	};
	return curleft;
};

componentPuzzleText.prototype.findPosY = function(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		};
	} else if (obj.y) {
		curtop += obj.y;
	};
	return curtop;
}

componentPuzzleText.prototype.mouseMoveText = function(e) {
};

componentPuzzleText.prototype.get_random = function(from, to) {
    var ranNum = Math.floor( Math.random() * (to-from+1) ) + from;
    return ranNum;
};

componentPuzzleText.prototype.randomDDElements = function() 
{
	var indexes = new Array();
	var sizes = new Array();
	for (var i=0; i<this.basketsCount; i++) {
		indexes.push(i);
		sizes.push( 
			{
				x: this.texts[i].x, 
				y: this.texts[i].y,
				x_backup: this.texts[i].x_backup,
				y_backup: this.texts[i].y_backup
			}
		);
	};
	var randomIndexes = new Array();
	
	while( indexes.length != 0 ) {
		randomIndexes.push( indexes.splice( this.get_random(0, indexes.length-1),1 ) );
	};
	
	for (var i=0; i<this.basketsCount; i++) {
		this.texts[i].x = sizes[ randomIndexes[i] ].x;
		this.texts[i].y = sizes[ randomIndexes[i] ].y;
		this.texts[i].x_backup = sizes[ randomIndexes[i] ].x_backup;
		this.texts[i].y_backup = sizes[ randomIndexes[i] ].y_backup;

		this.texts[i].startX = this.texts[i].x;
		this.texts[i].startY = this.texts[i].y;
		this.texts[i].startY = this.texts[i].x_backup;
		this.texts[i].startY = this.texts[i].y_backup;
	}
};

componentPuzzleText.prototype.beginDragText = function() {
	/**
		var obj = document.getElementById(this.destinationBasketId);
		obj.style.borderColor = "red";
	*/
	this.setZIndex(1000);
};

componentPuzzleText.prototype.endDragText = function(e) 
{
	this.setZIndex(this.orgZ);

	var ddbasket = document.getElementById(this.destinationBasketId);
	var ddelement = document.getElementById(this.id);
	/** ddbasket.style.borderColor = "black"; */

	var middlePoint = { 
		x: (ddelement.offsetLeft + ddelement.offsetWidth/2), 
		y: (ddelement.offsetTop + ddelement.offsetHeight/2)
	};

	for (var i=0; i < this.basketsCount; i++) {
		var ddbasket = document.getElementById("_"+this.parentText.id+"_"+i+"_basket");
		var left = this.parentText.findPosX(ddbasket);
		var right = this.parentText.findPosX(ddbasket) + ddbasket.offsetWidth;
		var top = this.parentText.findPosY(ddbasket);
		var bottom = this.parentText.findPosY(ddbasket) + ddbasket.offsetHeight;
		this.inArea = null;
		
		if ( middlePoint.x > left && middlePoint.x < right && middlePoint.y > top && middlePoint.y < bottom ){
			this.inArea = ddbasket;
			break;
		};
	};
	
	if (this.inArea && !this.parentText.checkIsBasketFilled(this, this.inArea.id)) {
		this.parentText.setIntoBasket(this, ddelement, this.inArea)
	}else{
		this.parentText.moveToStart(this, ddelement);
	};
	
	if (this.parentText.texts){
		var active = this.parentText.checkIsCorrect();
		var lastIndex = this.parentText.texts.length;
		var obj = this.parentText.texts[lastIndex-1];
		this.parentText.setButtonActivity(obj, active);
	};
};

componentPuzzleText.prototype.setButtonActivity = function(obj, status) 
{
	if (status){
		obj.standardSrc = this.addButtonSrcOut;
		obj.mouseOverSrc = this.addButtonSrcIn;		
		obj.active = true;
	}else{
		obj.standardSrc = this.addButtonInactiveSrcOut;
		obj.mouseOverSrc = this.addButtonInactiveSrcIn;	
		obj.active = false;
	};
	obj.eventMouseOut();
};

componentPuzzleText.prototype.setIntoBasket = function(sender, dde, obj) 
{
	var x = sender.parentText.findPosX(obj)+sender.parentText.borderWidth;
	var y = sender.parentText.findPosY(obj)+sender.parentText.borderWidth;

	dde.style.left = x;
	dde.style.top = y;
	
	sender.x = x;
	sender.y = y;
	sender.insideBasketId = obj.id;
	sender.insideBasketName = obj.name.replace(this.id+"_", "");
	sender.solved = (obj.name == sender.basketName);
	//sender.solved = (obj.id == sender.destinationBasketId);
};

componentPuzzleText.prototype.moveToStart = function(obj, elem) 
{
	obj.insideBasketId = '';
	obj.inArea = null;
	obj.solved = false;
	obj.x = obj.startX;
	obj.y = obj.startY;
	
	elem.style.left = obj.startX;
	elem.style.top = obj.startY;
};

componentPuzzleText.prototype.checkIsCorrect = function() 
{
	for (var i=0; i < this.basketsCount; i++) {
		if (!this.texts[i].solved && this.texts[i].insideBasketId != '') return false;
	};
	//if (this.parseCheckAnswer()) return false;  //pg2-removed
	return true;
};

componentPuzzleText.prototype.checkIsCorrectSequence = function() 
{
	for (var i=0; i < this.basketsCount; i++) {
		if (!this.texts[i].solved) return false;
	}
	return true;
};

componentPuzzleText.prototype.checkIsBasketFilled = function(obj, basketId) 
{
	for (var i=0; i < this.basketsCount; i++) {
		if (this.texts[i].id != obj.id && this.texts[i].insideBasketId == basketId){
			if (this.replaceElements){
				this.moveToStart(this.texts[i], this.texts[i]);	
				return false;
			}else{
				this.moveToStart(obj, obj);	
				return true;
			}
		}
	}	
	return false;
};

componentPuzzleText.prototype.onRepaint = function() 
{
	if (PageInterface.GetValue("allowCAI") && this.showCorrectAnswerIndicator) {
		for (var i=0; i < this.basketsCount; i++) {
			if (!this.texts[i].solved) {
				//if (this.showCorrectAnswerIndicator == true) { //pg2-removed, it's above too
					this.texts[i].obj.style.border = this.elementInCorrectBorderColor + " solid 1px";
					this.texts[i].obj.style.background = this.elementInCorrectBckColor;
				//}
			} else
			//if (this.showCorrectAnswerIndicator == true)  //pg2-removed, it's above too
			{ 
				this.texts[i].obj.style.border = this.elementCorrectBorderColor + " solid 1px";
				this.texts[i].obj.style.background = this.elementCorrectBckColor;
			}
		}
	}
}

componentPuzzleText.prototype.getAnswer = function(obj)
{
	var result = '';
	var sep = '';
	for (var i=0; i < this.basketsCount; i++) {
		if (result != '') sep = '#!#';
		result += sep + this.texts[i].id +'||'+this.texts[i].insideBasketId 
	}
	return(result);
};

componentPuzzleText.prototype.setAnswer = function(valStr, showCorrect)
{
	if ((typeof(valStr) == 'undefined' || valStr == '') && !showCorrect) return;
	if (valStr == '' && (typeof(showCorrect) == 'undefined' || showCorrect == '')) showCorrect = true;

	if (!showCorrect){
		var splited = valStr.split('#!#');
		for (var i=0; i < splited.length; i++){
			var elem = splited[i].split('||');
			var ddelement = document.getElementById(elem[0]);
			var ddbasket = document.getElementById(elem[1]);
			var j=-1;
			do{
				j++;
			}while (this.texts[j].id != elem[0] && j < this.basketsCount)
			
			if (ddbasket) this.setIntoBasket(this.texts[j], ddelement, ddbasket);		
		};
	}else{
		for (var i=0; i < this.basketsCount; i++) {
			var ddelement = document.getElementById(this.texts[i].id);
			var ddbasket = document.getElementById(this.texts[i].destinationBasketId);
			this.setIntoBasket(this.texts[i], ddelement, ddbasket);
		};
	};
};

componentPuzzleText.prototype.checkAnswer = function()
{
	return(this.parseCheckAnswer(this));
};

componentPuzzleText.prototype.parseCheckAnswer = function(index)
{
	var result = true;
	var showCAI = (this.showCorrectAnswerIndicator && this.showAnswerIndicatorAnyTime); //pg2
	for (var i=0; i < this.basketsCount; i++) {
		if (!this.texts[i].solved) {
			if (this.returnWhenIncorrect && page.countAnswers != 0){
				this.moveToStart(this.texts[i], this.texts[i]);	
			};
			result = false;
			
			if (showCAI) { //pg2- wrong answer CAI
				this.texts[i].obj.style.border = this.elementInCorrectBorderColor + " solid 1px"; //pg2-test
				this.texts[i].obj.style.background = this.elementInCorrectBckColor;
			}
		} else
		if (showCAI) {
			this.texts[i].obj.style.border = this.elementCorrectBorderColor + " solid 1px";
			this.texts[i].obj.style.background = this.elementCorrectBckColor;
		}
		
	}
	return result;
};

componentPuzzleText.prototype.onLock = function() {
	for (var i=0; i < this.basketsCount; i++) {
		this.texts[i].canDragging = false;
	};
	this.complete = true;
};

componentPuzzleText.prototype.onUnLock = function() {
	for (var i=0; i < this.basketsCount; i++) {
		this.texts[i].canDragging = true;
	}
	this.complete = false;
};


componentPuzzleText.prototype.interactionsCorrectResponsesCount = function()
{
	return 1;
};

componentPuzzleText.prototype.interactionsCorrectResponses = function(index)
{
	var result = '';
	var sep = '';
	for (var i=0; i < this.basketsCount; i++) {
		if (result != '') sep = '#!#';
		result += sep + this.texts[i].id +'||'+this.texts[i].destinationBasketId; 
	}
	return(result);
};

componentPuzzleText.prototype.interactionsStudentResponse = function()
{
	return this.getAnswer();
};

componentPuzzleText.prototype.interactionsCorrectResponsesAsText = function(index)
{
	var result = '';
	var sep = '';
	for (var i=0; i < this.basketsCount; i++) {
		if (result != '') sep = '#!#';
		result += sep + this.texts[i].text +'||'+this.texts[i].destinationBasketName; 
	}
	return(result);
};

componentPuzzleText.prototype.interactionsStudentResponseAsText = function()
{
	var result = '';
	var sep = '';
	for (var i=0; i < this.basketsCount; i++) {
		if (result != '') sep = '#!#';
		result += sep + this.texts[i].text +'||'+this.texts[i].insideBasketName; 
	}
	return(result);
};
