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

componentDDBasket = function(name)
{
	this.componentElement = componentElement;
	this.componentElement(name);
	this.text = this.addChild(new __componentText(null));
	this.text.text = '';
	this.text.wrap = false;
	this.text.allowGF = false;
	this.correctDDElements = new Array();
	this.dockSite = true;
	this.isChanged = false;

	this.listOfElementInside = '';

	this.interactions = true;
	this.interactionsType = "matching";
	this.lastDroppedElement = null; //pg2-AF action
};

componentDDBasket.prototype = new componentElement();
componentDDBasket.prototype.type = "componentDDBasket";

componentDDBasket.prototype.onCreate = function(obj)
{
	this.captureMouseEvents();

	if (PageInterface.GetValue("state") == psDesigning){
		this.text.text = this.DisplayText(this.correctAnswer);
	} else {
		this.setDDElements(this.correctAnswer); 
		if (this.correctDDElements.length > 1) {
			this.interactionsType = "matching"; //"numeric"; //pg2-"matching" -4scorm2004
		};
	};
};

componentDDBasket.prototype.setDDElements = function(answ)
{
	if (answ != null && answ != "null" && answ != "") {
		elemArray = new Array();
		tempArray = new Array();
		var answerSplitChar = "|";
		var index = 0;

		var parentComp = page; //pg2-FPC -DnD within container
		if (this.parent.type == 'componentContainer') parentComp = this.parent;
		for (var i = 0; i < parentComp.children.length; i++) { //pg2-FPC -parentObj instead of page
			if (parentComp.children[i].type == "componentDDElement") {
				elemArray[index] = parentComp.children[i].id;
				index++;
			};
		};
		elemArray.sort();

		tempArray = answ.split(answerSplitChar);
		index = 0;

		for (var i = 0 ; i < tempArray.length; i++) {
			for (j = 0; j< elemArray.length; j++) {
				if (tempArray[i] == elemArray[j]) {
					this.correctDDElements[index] = tempArray[i];
					index++;
					break;
				};
			};
		};
	};
};

componentDDBasket.prototype.DisplayText = function(answ)
{
	var dispText = "";
	if (answ != null && answ != "null" && answ != "") {  
		var answerSplitChar = "|";
		var answArray = answ.split( answerSplitChar );
		for (var i = 0; i < answArray.length; i++) {
			if (dispText != "") dispText += "<br>&nbsp;";
			dispText += "<i>-" + answArray[i] + "</i>";
		};
		dispText = "<br>&nbsp;" + dispText;
	};
	if (dispText == "") return "<b>&nbsp&nbsp" + this.id + "</b>";
	else return "<b>&nbsp&nbsp" + this.id + "</b>" + dispText;
};

componentDDBasket.prototype.onPaint = function(obj)
{
};

componentDDBasket.prototype.onAfterLoad = function()
{
	if (PageInterface.GetValue("state") != psDesigning) {
		if ((page.isExec && PageInterface.GetValue("allowCAI") && this.showCorrectAnswerIndicator) ||
			(this.showCorrectAnswerIndicator && this.showCAIOnEachAttempt && page.countAnswers != page.baseTryCount)) //pg2-giub_cai_dnd
		{
			//this.checkAnswer();
			var parentComp = page;
			if (this.parent.type == 'componentContainer') parentComp = this.parent;
			for (var i = 0; i < parentComp.children.length; i++) {
				var elem = parentComp.children[i];
				if (elem.type == "componentDDElement" && this.checkIfBelongsToMe(elem)) {
					elem.showCAI();
					if (elem.getState() == 1) elem.lock();
				};
			};
		};
	};
};

/**
 * Sprawdza czy obiekt podany na wejsciu znajduje sie w granicach
 * obieku bazowego.
 */
componentDDBasket.prototype.checkIfBelongsToMe = function(aDDElement)
{
	if (this.autoCompose) {
		if (this.puzzleMode) { //pg2-puzzleMode_dndComponents -for Drag'n'drop elements, docking mechanism - not based on elements' corners- is different and checking answer as well
			var result = (aDDElement.x >= this.x && aDDElement.x <= this.x + parseInt(this.w/3)) && (aDDElement.y >= this.y && aDDElement.y <= this.y + parseInt(this.h/3));
			return result;
		} else {
			return (aDDElement.x >= this.x && aDDElement.x < this.x + this.w) && (aDDElement.y >= this.y && aDDElement.y < this.y + this.h);
		};
	} else {
		var halfW = parseInt( aDDElement.w / 2 );
		var halfH = parseInt( aDDElement.h / 2 );
		var centreX = aDDElement.x + halfW;
		var centreY = aDDElement.y + halfH;

		return ((this.x + halfW) <= centreX) && (centreX <= (this.x + this.w - halfW )) &&
				((this.y + halfH) <= centreY) && (centreY <= (this.y + this.h - halfH ));
	};
};

componentDDBasket.prototype.getDDElementsArray = function()
{
	var dropArray = new Array();
	var index = 0;

	for (var i=0; i<page.children.length; i++) { 
		if (page.children[i].type == "componentDDElement") {
			if (this.checkIfBelongsToMe(page.children[i])) {
				dropArray[index] = page.children[i].id;
				index++;
			};
		};
	};
	dropArray.sort();
	return dropArray;
};

componentDDBasket.prototype.ElementIsCorrectAnswer = function(name)
{
	for (var i=0; i<this.correctDDElements.length; i++) {
		if (this.correctDDElements[i] == name) {
			return true;
		};
	};
	return false;
};

componentDDBasket.prototype.getAnswer = function()
{
	var dropArray = this.getDDElementsArray();
	var sep = "";
	var s = "";
	for (var i=0; i < dropArray.length; i++) { //pg2-missing 'var'
		s += sep + dropArray[i];
		if (sep == "") sep = "|";
	};

	// //pg2-removed -it will not work, 'cause in exam there are not attached correctAnswers of elements
	//pg2-in case of exam, comparition of answers (correctAnswer and userAnswer) is performed at lms side. In this case "ddelem1|ddelem2" isn't equal "ddelem2|ddelem1"
	var s2 = '|' + s + '|';
	var arrCorrectAnswer = this.correctAnswer.split('|');
	var isCorrect = true;
	var elem = '';
	for (var i=0; i<arrCorrectAnswer.length; i++) {
		//isCorrect = (isCorrect && true);
		elem = '|' + arrCorrectAnswer[i] + '|';
		if (s2.indexOf(elem) == -1) {
			isCorrect = false;
			break;
		};
	};
	if (isCorrect) s = this.correctAnswer; else
	if (PageInterface.GetValue("isExam")) {
		try {
			var wbtsTop = getWBTServerTop();
			if (wbtsTop && wbtsTop.document) {
				var title = wbtsTop.document.title;
				if (title.indexOf('WBTServer 5') > -1) { //pg2-in case of WBTServer 5, if only one element is in the basket (one of possible few) and answer is correct, lms.StudentExam doesn't check answer properly
					if (this.checkAnswer()) s = this.correctAnswer;
				};
			};
		} catch(e) {};
	};
	//
	return s;
};

componentDDBasket.prototype.setAnswer = function(v)
{
	if (v == null || v == '') return;
	if (v.indexOf('|') > -1) var dropArray = v.split("|");
	else var dropArray = v.split(",");

	for (var i = 0; i < page.children.length; i++) { 
		if (page.children[i].type == "componentDDElement") {
			if (this.checkIfBelongsToMe(page.children[i]) && !this.checkAnswer()) {
				page.children[i].moveToStart();
			};
		};
	};

	//if (!this.checkAnswer()) {//pg2-inproper - basket remembers answer until page isn't failed- then, if emptyBasket=1, then remove element(s) to its start position
	var tryLeft = PageInterface.GetValue('countAnswers');
	var baseTryCount = PageInterface.GetValue('baseTryCount');
	//if (!this.emptyBasket || tryLeft > 0 || baseTryCount == 0) { //pg2-removed -if option 'moveElementsToStartPositionInCaseOfWrongAnswer' is enabled, action 'showCorrectAnswer' is not working
	{
		for (var i=0; i < dropArray.length; i++) {
			for (var j=0; j < page.children.length; j++ ) {
				if (page.children[j].type == "componentDDElement"
						&& page.children[j].id == dropArray[i]
						&& page.children[j].getState() != 1) {
					if (this.autoCompose) this.composeElement(page.children[j]);
					else {
						page.children[j].x = this.x;
						page.children[j].y = this.y;
						page.children[j].setZIndex(this.getZIndex() + 1);
						page.children[j].paint();
						//page.setOnTop(page.children[j]);
					};
					break;
				};
			};
		};
	};

	this.paint();

	for (var i = 0; i < page.children.length; i++) { 
		if (page.children[i].type == "componentDDElement") {
			page.children[i].invokeEvent("Repaint");
		};
	};
};

componentDDBasket.prototype.parseCheckAnswer = function(obj)
{
	if (this.ignoreAnswer) return true; //pg2-obsluga pomijania odpowiedzi
	return this.checkAnswer();
};

componentDDBasket.prototype.checkAnswer = function()
{
	var correct = true;
	var maxCountDock = this.ddeRowDock * this.ddeColDock;
	var usedDDElements = '';
	var elementsInsideList = this.getListOfBasketsInsideMe();
	if (this.correctDDElements.length == 0 && elementsInsideList != "") correct = false;
	if (maxCountDock == 1) {
		var isElementInMe = false;
		var parentComp = page; //pg2-FPC -DnD within container
		if (this.parent.type == 'componentContainer') parentComp = this.parent;
		for (var i = 0; i < parentComp.children.length; i++) {
			var elem = parentComp.children[i];
			if (elem.type == "componentDDElement" && this.checkIfBelongsToMe(elem)) {
				if (this.ElementIsCorrectAnswer(elem.id)) {
					elem.checkMakeRePaint();				
					correct = true;
				} else {
					elem.checkMoveToStart();
					correct = false;
				};
				isElementInMe = true;

				if (elem.showCorrectAnswerIndicator && this.showCAIOnEachAttempt) { // && elem.showCAIOnEachAttempt) { // && page.countAnswers > 0) { //pg2-giub_cai_dnd
					elem.showCAI();
					if (correct) elem.lock();
				};
			};
		};
		if (!isElementInMe) {
			if (this.correctAnswer == '') correct = true; else correct = false;
		};
	};

	if (this.one) {	
		var count = 0;
		var parentComp = page; //pg2-FPC -DnD within container
		if (this.parent.type == 'componentContainer') parentComp = this.parent;
		for (var i = 0; i < parentComp.children.length; i++) {
			var elem = parentComp.children[i];
			if (elem.type == "componentDDElement" && this.checkIfBelongsToMe(elem)) count++;
		};
		if (count != 0) {
			for (var i = 0; i < parentComp.children.length; i++) {
				var elem = parentComp.children[i];
				if (elem.type == "componentDDElement" && this.checkIfBelongsToMe(elem)) {
					if (this.ElementIsCorrectAnswer(elem.id)){
						elem.checkMakeRePaint();
						correct &= true;					
					} else {
						elem.checkMoveToStart();
						correct &= false;
					};
				};
			};
		} else
		if (this.correctDDElements.length != 0 ) correct = false;
		else correct = true;
	} else
	if (maxCountDock != 1) {		
		for (var i = 0; i < this.correctDDElements.length; i++) {
			var elem = page.all[this.correctDDElements[i]];
			usedDDElements += this.correctDDElements[i] + '_';
			if (elem) {
				switch (elem.getState()) {
					case 0:
						correct &= !this.ElementIsCorrectAnswer(elem.id);
						break;
					case 1:
						correct &= true;
						elem.checkMakeRePaint();						
						break;
					case 2:
						correct &= false;
						elem.checkMoveToStart();
						break;
				};
				elementsInsideList = elementsInsideList.replace(elem.id+'||', '');				
			};
		};

		//check if in basket is more element there use to be
		var additionalElementsArr = elementsInsideList.split('||');
		if (this.correctDDElements.length != 0)
			for (var i = 0; i < additionalElementsArr.length; i++){
				if (additionalElementsArr[i] != '') correct = false;
			};		

		for (var i = 0; i < page.children.length; i++) {
			var elem = page.children[i];
			if (usedDDElements.indexOf(elem.id) == -1 && 
				elem.type == "componentDDElement" && elem.getState() == 2) {
				elem.checkMoveToStart();
			};
		};
	};

	var tryLeft = PageInterface.GetValue('countAnswers');
	var baseTryCount = PageInterface.GetValue('baseTryCount');
	var pageIsShow = PageInterface.GetValue('pageIsShow');

	var attemptsUsed = baseTryCount - tryLeft - 1;

	//empty all baskets if page is failed with emptyBasket property true(1);
	if (!correct && (attemptsUsed < this.tryNumber || this.tryNumber == -1) && pageIsShow) // && baseTryCount > 0) //pg2-if try count is infinite (0)... //pg2-aka -if baseTryCount == 0 (infinite try count) -it has blocked infinite tryCount
	{
		var DDEList = "";
		var DDEListArr = [];
		var DDE = null;

		for (var i = 0; i < page.children.length; i++) {
			var elem = page.children[i];
			if (elem.type == "componentDDBasket" && elem.emptyBasket){
				DDEList = elem.getListOfBasketsInsideMe();
				DDEListArr = DDEList.split('||');
				for (var j = 0; j < DDEListArr.length; j++) {
					DDE = PageInterface.GetValue("getChild", DDEListArr[j]);
					var pageStatus = PageInterface.GetValue("getPageStatus"); //pg2
					if ((pageStatus == "failed" || pageStatus == 'completed') && this.emptyBasket && DDE) { //pg2 //pg2-aka -if baseTryCount == 0 (infinite try count) -at first answer check status is completed
						if (this.checkIfBelongsToMe(DDE) && //pg2-move to start position only elements docked within this basket (otherwise, even if element is in correct one, another basket on the page will remove it from correct one to start position
							!this.ElementIsCorrectAnswer(DDE.id) && DDE.returnWhenIncorect) DDE.moveToStart(); //pg2-return to start position only if within wrong basket
					};
					//if (DDE) {
						//DDE.checkMoveToStart();
					//}
				};
			};
		};
	};

	this.listOfElementInside = elementsInsideList;
	return correct;
};

componentDDBasket.prototype.getListOfBasketsInsideMe = function(obj)
{
	var list = '';
	var parentComp = page; //pg2-FPC -DnD within container
	if (this.parent.type == 'componentContainer') parentComp = this.parent;
	for (var i = 0; i < parentComp.children.length; i++) {
		var elem = parentComp.children[i];
		if (elem.type == "componentDDElement" ){
			if ((elem.x >= this.x && elem.x <= this.x + this.w) 
				&& (elem.y >= this.y && elem.y <= this.y + this.h)){
				list += elem.id + '||';
			};
		};
	};
	return list;
};

componentDDBasket.prototype.composeElement = function(obj)
{
	var x = this.ddeBeginDockX;
	var y = this.ddeBeginDockY;
	var maxCountDock = this.ddeRowDock * this.ddeColDock;
	var currNumDock = 1;

	obj.setZIndex(this.getZIndex() + 1);
	//page.setOnTop(obj);

	for (var r=1; r<=this.ddeRowDock; r++) {
		for (var c=1; c<=this.ddeColDock; c++) {
			// count new pos of element
			var tx = this.x + this.ddeBeginDockX + ((c-1)*this.ddeW) + ((c-1) * this.ddeOffsetDockW);
			var ty = this.y + this.ddeBeginDockY + ((r-1)*this.ddeH) + ((r-1) * this.ddeOffsetDockH);
			// check if count pos is free
			var freePos = true;

			var parentComp = page; //pg2-FPC -DnD within container
			if (this.parent.type == 'componentContainer') parentComp = this.parent;
			for (var i=0; i<parentComp.children.length; i++) { //pg2-FPC -if parent==container, go via all container's children -drop element
				var child = parentComp.children[i];
				if (child.type == "componentDDElement" && child.x == tx && child.y == ty) {
					currNumDock++;
					if (child.id != obj.id) freePos = false;
					break;
				};
			};
			// if basket is full
			// return to start position
			if (currNumDock > maxCountDock) {
				if (obj.type == "componentDDElement") {
					obj.moveToStart();
					return(false);
				};
			};
			// set element on correect place
			if (freePos) {
				obj.moveTo(tx, ty);      
				return(true);
			};
		};
	};
};

componentDDBasket.prototype.ddeDrop = function(obj)
{
	if (!this.visible) {
		obj.moveToStart();
		return;
	};

	var result = false;
	this.isChanged = true;
	if (this.autoCompose) result = this.composeElement(obj);
	this.lastDroppedElement = obj; //pg2-AF action
	result = this.invokeEvent('Drop', obj);
	return result;
};

componentDDBasket.prototype.clearAnswer = function()
{
	var parentComp = page; //pg2-FPC -DnD within container #2
	if (this.parent.type == 'componentContainer') parentComp = this.parent;

	for (var i = 0; i < parentComp.children.length; i++) { 
		if (parentComp.children[i].type == "componentDDElement") {
			if (this.checkIfBelongsToMe(parentComp.children[i])) {
				parentComp.children[i].moveToStart();
			};
		};
	};
	//...
	/* //pg2-FPC -removed, replaced with above one that works with containers too
	for (var i = 0; i < page.children.length; i++) { 
		if (page.children[i].type == "componentDDElement") {
			if (this.checkIfBelongsToMe(page.children[i])) {
				page.children[i].moveToStart();
			}
		}
	}*/
	this.paint();
};

componentDDBasket.prototype.checkIsChanged = function()
{
	return(this.isChanged);
};

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

componentDDBasket.prototype.interactionsCorrectResponses = function(index)
{
	/*if (this.interactionsType == "numeric") {
		return 1;
	} else {*/
		var res = "";
		for (var i=0; i<this.correctDDElements.length; i++) {
			if (res.length != 0) res += ",";
			res += this.correctDDElements[i];
		};
		return res;
	//}
};

componentDDBasket.prototype.interactionsStudentResponse = function()
{
	/*if (this.interactionsType == "numeric") {
		return (this.parseCheckAnswer()) ? 1 : 0;
	} else {*/
		var res = "";
		var ans = this.getAnswer();
		if (ans != '') {
			var uaList = ans.split("|");
			for (var i=0; i<uaList.length; i++) {
				if (res.length != 0) res += ",";
				res += uaList[i];
			};
		};
		return res;
	//}
};

componentDDBasket.prototype.interactionsCorrectResponsesAsText = function(index)
{
	/*if (this.interactionsType == "numeric") {
		return 1;
	} else {*/
		var res = "";
		for (var i=0; i<this.correctDDElements.length; i++) {
			if (res.length != 0) res += ",";
			var elem = page.all[this.correctDDElements[i]];
			if (elem && elem.displayText && typeof(elem.answerValuesString) != "undefined" && elem.answerValuesString != "") {
				res += escape(elem.answerValuesString);
			} else {
				res += this.correctDDElements[i];
			};
		};
		return res;
	//}
};

componentDDBasket.prototype.interactionsStudentResponseAsText = function()
{
	/*if (this.interactionsType == "numeric") {
		return (this.parseCheckAnswer()) ? 1 : 0;
	} else {*/
		var res = "";
		var ans = this.getAnswer();
		if (ans != '') {
			var uaList = ans.split("|");
			for (var i=0; i<uaList.length; i++) {
				if (res.length != 0) res += ",";
				var elem = page.all[uaList[i]];
				if (elem && elem.displayText && typeof(elem.answerValuesString) != "undefined" && elem.answerValuesString != "") {
					res += escape(elem.answerValuesString);
				} else {
					res += uaList[i];
				};
			};
		};
		return res;
	//}
};
