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

componentMatchDots = function(name) 
{
	this.__componentText = __componentText;
	this.__componentText(name);
	
	this.spaceBetween = 0;
	this.inArea = null;
	
	this.textsLeft = new Array();	
	this.textsRight = new Array();	
	
	this.imagesLeft = new Array();	
	this.imagesRight = new Array();	
	this.text = "";
	
	this.interactions = true;
	this.interactionsType = "matching";	
	
	this.workArea = null;	
	this.compAudio = null;	
	this.startPoint = null;
};

componentMatchDots.prototype = new __componentText;
componentMatchDots.prototype.type = "componentMatchDots";

componentMatchDots.prototype.onBaseCreate = function(obj) {
	this.captureMouseEvents();
};

componentMatchDots.prototype.onCreate = function(obj)
{
	if ( PageInterface.GetValue("state") != psDesigning && lms && this.disableOnlineOfflineMix != false ) 
	{
		this.resourcesStatus 	= lms.resourcesStatus();
		this.resourcesURL 		= lms.resourcesURL();
	} else this.resourcesURL = resourcesURL;

	var unEscContentArr = unescape(this.content);
	var contentArr = unEscContentArr.split("||");
		
	var sizeDiv = '<span id="'+this.id+'sizeDiv" style="visibility: hidden; position: absolute; font-family:' + this.fontFamily
	+ '; font-size:' + this.fontSize + 'px; color:' + this.fontColor + ';"></span>';
	
	var ob = document.getElementById(this.id);
	ob.innerHTML += sizeDiv;	
	
	var fontSize = this.getFontSize(this.fontSize, 'px');
	
	var newImg = new Image();
	newImg.src = this.resourcesURL +  this.dotOff;	
	
	var textWidthHeightArr = this.getMaxWidthHeight(contentArr, this.fontFamily, fontSize);
	
	var oneRowHeight = (this.h-10*(contentArr.length-1))/contentArr.length;
	
	this.spaceBetween = parseInt((this.h - oneRowHeight*contentArr.length)/(contentArr.length-1));
	
	var tempX = this.x + 2;
	var tempY = this.y + 2;
	
	var maxFreeSpace = this.w - textWidthHeightArr[0]*2 - 4;	
	
	var drawArea = new componentElement;
	drawArea.myParent = this; 
	drawArea.id = this.id+'_WorkAreaDIV'; 
	drawArea.x = tempX + textWidthHeightArr[0];
	drawArea.y = tempY;
	drawArea.h = this.h;
	drawArea.w = maxFreeSpace;
	drawArea.padding = 0;	
	page.addChild(drawArea);
	this.workArea = drawArea;
	
	for(var i=0; i < contentArr.length; i++){
		var groupArr = contentArr[i].split('#!#');
		for(var j=0; j < groupArr.length; j++){
			var elementText = new __componentText;
			elementText.myParent = this; 
			elementText.id = this.id+'_TEXT_'+j+':'+i; 
			elementText.x = Math.ceil(tempX + (this.w - textWidthHeightArr[0] - 4)*j);
			elementText.y = Math.ceil(tempY);
			elementText.h = Math.ceil(oneRowHeight);
			elementText.w = Math.ceil(textWidthHeightArr[0]);
			elementText.clearText = groupArr[j];
			elementText.text = '<table width="100%" style="background: '+this.headerBckColor+'; border: '+1+'px solid '+this.tableBorderColor+'; font-family: '+this.fontFamily+'; font-size: '+this.getFontSize(this.fontSize, 'px')+'px;"><tr><td style="text-align: '+this.align+'">'+groupArr[j]+'</td></tr></table>';
			elementText.padding = 0;

			elementText.pair = 'pair_'+i;
			elementText.valign = 'middle';
			
			page.addChild(elementText);		
			if (j % 2){			
				this.textsRight.push( elementText ); 
			}else{
				this.textsLeft.push( elementText ); 
			};
			
			var compRollover = new componentRollover;
			compRollover.myParent = this; 
			compRollover.id = this.id+'_IMAGE_'+i+':'+j; 
			compRollover.clearText = groupArr[j]; 
			compRollover.h = Math.ceil(this.dotH);
			compRollover.w = Math.ceil(this.dotW);
			if (j % 2){			
				compRollover.x = Math.ceil(tempX + textWidthHeightArr[0] + maxFreeSpace - compRollover.w);
			}else{
				compRollover.x = Math.ceil(tempX + textWidthHeightArr[0]);
			};			
			compRollover.y = Math.ceil(tempY + (oneRowHeight/2-compRollover.h/2));
			compRollover.srcOut = this.dotOff;
			compRollover.srcIn = this.dotOn;
			compRollover.pair = 'pair_'+i;
			compRollover.side = 'side_'+j;
			compRollover.solve = false;
			compRollover.isLocked = false;
			compRollover.correctPointName = (j % 2) ? this.id+'_IMAGE_0:'+i : this.id+'_IMAGE_1:'+i
			compRollover.connectPoint = null;
			compRollover.cursor = this.elementCursor;			
			compRollover.xArray = [ 0,0,0,0,0 ];
			compRollover.yArray = [ 0,0,0,0,0 ];
			
			compRollover.captureMouseEvents = this.captureMouseEvents;
			compRollover.eventClick = this.clickOnButton;
			
			compRollover.eventMouseOver = this.buttonEventMouseOver;
			compRollover.eventMouseOut = this.buttonEventMouseOut;
			
			page.addChild(compRollover);	
			if (j % 2){
				this.imagesRight.push( compRollover ); 
			}else{
				this.imagesLeft.push( compRollover ); 
			};			
		};			
		tempY += this.spaceBetween + oneRowHeight - 2;	
	};	
	
	//if (page.state != psDesigning) { //pg2-remove
		this.randomElements(this.textsLeft, this.imagesLeft, 0);
		this.randomElements(this.textsRight, this.imagesRight, 1);
	//};
	
	document.getElementById(this.id+"sizeDiv").innerHTML = '';
};

componentMatchDots.prototype.buttonEventMouseOver = function(e)
{
	if (this.isLocked) return;
	
	this.setValue(this.resourcesURL + this.srcIn);
};

componentMatchDots.prototype.buttonEventMouseOut = function(e)
{
	if (this.isLocked) return;
	
	this.setValue(this.resourcesURL + this.srcOut);
};

componentMatchDots.prototype.drawLine = function( lineIndex, x1, y1, x2, y2, lineImgPath )
{
	objectHandle = document.getElementById( "line"+ lineIndex + this.startPoint.id )
	if( !objectHandle )
	{
		var workArea = document.getElementById(this.id);
		var newdiv = document.createElement('img');
		newdiv.setAttribute("id", "line"+ lineIndex + this.startPoint.id);
		workArea.appendChild(newdiv);	
		
		var objectHandle = document.getElementById( "line"+ lineIndex + this.startPoint.id)
		objectHandle.style.position = 'absolute';
		objectHandle.style.zIndex = this.z+1;
		
		workArea.style.visibility = 'inherit';
	};
	
	this.updateLine( objectHandle, x1, y1, x2, y2, lineImgPath )
};

componentMatchDots.prototype.updateLine = function( lineObjectHandle, Ax, Ay, Bx, By )
{
	var
		xMin		= Math.min( Ax, Bx ),
		yMin		= Math.min( Ay, By ),
		xMax		= Math.max( Ax, Bx ),
		yMax		= Math.max( Ay, By ),
		boxWidth	= Math.max( xMax-xMin, 1 ),
		boxHeight	= Math.max( yMax-yMin, 1 ),
		tmp			= Math.min( boxWidth, boxHeight ),
		smallEdge	= 1,
		newSrc

	while( tmp >>= 1 && smallEdge < 512 )
		smallEdge <<= 1;

	newSrc = smallEdge +( (Bx-Ax)*(By-Ay) < 0 ? "up.gif" : "down.gif" );
	
	if( lineObjectHandle.src.indexOf( newSrc )==-1 )
		lineObjectHandle.src = this.resourcesURL + newSrc;
	
	with( lineObjectHandle.style )
	{
		width = boxWidth + "px";
		height = boxHeight + "px";
		left = xMin + "px";
		top = yMin + "px";
	}
};

componentMatchDots.prototype.updateFrame = function()
{
	if (!this.startPoint) {
		clearInterval();
		return;
	}

	for( var i=0; i < this.startPoint.xArray.length-1; i++ ){
		this.drawLine( i, this.startPoint.xArray[ i ], this.startPoint.yArray[ i ], this.startPoint.xArray[ i+1 ], this.startPoint.yArray[ i+1 ] );
	}
}

componentMatchDots.prototype.mouseMoveWorkArea = function(evt)
{
	if (this.startPoint){
		if( !evt )
			evt = event
		
		this.startPoint.xArray[ this.startPoint.xArray.length-1 ] = evt.clientX - this.x;
		this.startPoint.yArray[ this.startPoint.yArray.length-1 ] = evt.clientY - this.y;
	};
};

componentMatchDots.prototype.clickOnButton = function()
{
	if (this.isLocked) return;
	
	if (!this.myParent.startPoint){
		var myMiddleX = this.x + this.w/2 - this.myParent.x;
		var myMiddleY = this.y + this.h/2 - this.myParent.y;
		this.xArray = [ myMiddleX, myMiddleX, myMiddleX, myMiddleX, myMiddleX ];
		this.yArray = [ myMiddleY, myMiddleY, myMiddleY, myMiddleY, myMiddleY ];
		
		if (this.connectPoint){
			this.myParent.removeLine(this.connectPoint)
		};
		
		this.myParent.startPoint = this;
		
		window.setInterval('pc.'+this.myParent.id+'.updateFrame();', 25);
	}else{
		this.myParent.startPoint.xArray[ this.myParent.startPoint.xArray.length-1 ] = this.x + this.w/2 - this.myParent.x;
		this.myParent.startPoint.yArray[ this.myParent.startPoint.yArray.length-1 ] = this.y + this.h/2 - this.myParent.y;
		
		this.myParent.updateFrame();
		
		this.xArray = this.myParent.startPoint.xArray;
		this.yArray = this.myParent.startPoint.yArray;
		
		var remStartPoint = this.myParent.startPoint;
		
		if (this.side != this.myParent.startPoint.side){
			this.solve = (this.pair == this.myParent.startPoint.pair);
			remStartPoint.solve = this.solve;
		};		
		
		if (this.connectPoint){
			this.myParent.removeLine(this.connectPoint);
			this.myParent.removeLine(this);
		};
		
		remStartPoint.connectPoint = this;
		this.connectPoint = remStartPoint;
		
		
		this.myParent.startPoint = null;
		//window.setInterval('function (){return;}', 10);
	};
};

componentMatchDots.prototype.removeLine = function(obj)
{	
	var myMiddleX = obj.x + obj.w/2 - this.x;
	var myMiddleY = obj.y + obj.h/2 - this.y;
	obj.xArray = [ myMiddleX, myMiddleX, myMiddleX, myMiddleX, myMiddleX ];
	obj.yArray = [ myMiddleY, myMiddleY, myMiddleY, myMiddleY, myMiddleY ];
	obj.connectPoint = null;
	this.startPoint = obj;
	this.updateFrame();		
	this.startPoint = null;	
};

componentMatchDots.prototype.removeAllLines = function()
{
	for (var i in this.imagesLeft) {
		var o = this.imagesLeft[i];
		if (o.connectPoint){
			this.removeLine(o.connectPoint);
			this.removeLine(o);
		};
	}
	
	this.startPoint = null;
};

componentMatchDots.prototype.getMaxWidthHeight = function(arr, family, size)
{
	var maxWidth = 0; 
	var maxHeight = 0;
	var elem = document.getElementById(this.id+"sizeDiv");
	
	for(var i=0; i < arr.length; i++){
		var groupWord = arr[i].split('#!#');
		for(var j=0; j < groupWord.length; j++){
			elem.innerHTML = groupWord[j];
			elem.style.fontFamily = family;
			elem.style.fontSize = size;
			elem.style.width = (this.w/3);
			height = elem.offsetHeight;
			
 			if ( height > maxHeight ) maxHeight = height;
		};
	};
	var widthHeightArr = [(this.w/3)+4, maxHeight];
	return widthHeightArr;
}

componentMatchDots.prototype.getFontSize = function(value, format)
{
	var fontSizesPX = new Array(10,13,16,18,24,32,48);
	var fontSizesPT = new Array(8,10,12,14,18,24,36,48);
	var pxSize = fontSizesPT[parseInt(value)];
	if (format == "px") {
		pxSize = fontSizesPX[parseInt(value)];
	};	
	return pxSize;
};

componentMatchDots.prototype.componentMatchDotsBaseOnPaint = componentMatchDots.prototype.onPaint;
componentMatchDots.prototype.onPaint = function() 
{
	this.componentMatchDotsBaseOnPaint();
	
	var elem = document.getElementById(this.id+"_WorkAreaDIV");	
	elem.innerHTML = '<div id="'+this.id+'_WorkArea" style="position: relative; width:100%; height:100%" onmousemove="pc.'+this.id+'.mouseMoveWorkArea();" myWbteComp="'+this+'"></div>';
	var zInd = 1000;
	var left = null;
	var right = null;
	elem.style.zIndex = zInd;	
	
	//if (page.state != psDesigning) { //pg2-test
		this.randomElements(this.textsLeft, this.imagesLeft, 0);
		this.randomElements(this.textsRight, this.imagesRight, 1);
	//};
	
	for (var i=0; i < this.imagesLeft.length; i++) {
		left = this.imagesLeft[i];
		right = this.imagesRight[i];
		
		left.srcOut = this.dotOff;
		left.srcIn = this.dotOn;
		left.solve = false;		
		
		right.srcOut = this.dotOff;
		right.srcIn = this.dotOn;
		right.solve = false;		
		
		left.obj.style.zIndex = zInd;	
		right.obj.style.zIndex = zInd++;	
	};
	
	for (var i in this.imagesLeft) {
		var l = this.imagesLeft[i];
		if (l.connectPoint) {
			for (var j in this.imagesRight) {
				var r = this.imagesRight[j];
				if (l.connectPoint == r) {
					this.removeLine(l.connectPoint);
					this.removeLine(l);
					this.drawSetAnswerLine(i, j);
				}
			}
		}
	}
	
};

componentMatchDots.prototype.onRepaint = function() 
{
	if (PageInterface.GetValue("allowCAI") && this.showCorrectAnswerIndicator)
	{
		for (var i=0; i < this.imagesLeft.length; i++) {
			if (this.imagesLeft[i].solve) {
				this.imagesLeft[i].setValue(this.resourcesURL + this.dotCorrect);
			}else { 
				this.imagesLeft[i].setValue(this.resourcesURL + this.dotIncorrect);
			};
			if (this.imagesRight[i].solve) {
				this.imagesRight[i].setValue(this.resourcesURL + this.dotCorrect);
			}else { 
				this.imagesRight[i].setValue(this.resourcesURL + this.dotIncorrect);
			};			
		};
	};
};

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

componentMatchDots.prototype.randomElements = function(arr1, arr2, mode) //pg2-test "mode"
{
	var indexes = new Array();
	var sizes = new Array();
	
	for (var i=0; i < arr1.length; i++) {
		indexes.push(i);
		sizes.push( 
			{ 
				x:  arr1[i].x, 
				y:  arr1[i].y,
				x1: arr2[i].x,
				y1: arr2[i].y
			}
		);
	};
	
	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 < arr1.length; i++) {
		arr1[i].x = sizes[ randomIndexes[i] ].x;
		arr1[i].y = sizes[ randomIndexes[i] ].y;
		
		arr2[i].x = sizes[ randomIndexes[i] ].x1;
		arr2[i].y = sizes[ randomIndexes[i] ].y1;
	};
	
	if (mode == 0) { //pg2-test
		this.textsLeft = arr1;
		this.imagesLeft = arr2;
	} else {
		this.textsRight = arr1;
		this.imagesRight = arr2;
	}
};

componentMatchDots.prototype.onShow = function() 
{
	for (var i=0; i < this.textsRight.length; i++) {
		this.textsLeft[i].show();
		this.textsRight[i].show();
		this.imagesLeft[i].show();
		this.imagesRight[i].show();
	};
	this.workArea.show();
};

componentMatchDots.prototype.getAnswer = function()
{
	var result = '';
	var sep = '';
	
	for (var i=0; i < this.imagesLeft.length; i++) {
		if (result != '') sep = '||';
		result += sep + this.imagesLeft[i].id + '##';

		if (this.imagesLeft[i].connectPoint) result += this.imagesLeft[i].connectPoint.id;
	};
	return(result);
};

componentMatchDots.prototype.setAnswer = function(valStr, showCorrect)
{
	this.removeAllLines();
	this.updateFrame();

	if ((typeof(valStr) == 'undefined' || valStr == '') && !showCorrect) return;
	if (valStr == '' && (typeof(showCorrect) == 'undefined' || showCorrect == '')) showCorrect = true;
	
	if (showCorrect){
		for (var i=0; i < this.imagesLeft.length; i++){
			
			var j = -1;
			do{
				j++;
			}while (j < this.imagesRight.length && this.imagesRight[j].pair != this.imagesLeft[i].pair)
			
			this.drawSetAnswerLine(i, j);
			
			//pg2-new
			this.imagesLeft[i].setValue(this.resourcesURL + this.dotCorrect);
			this.imagesRight[i].setValue(this.resourcesURL + this.dotCorrect);
		};
	}else{
		var splited = valStr.split('||');
		
		for (var i=0; i < splited.length; i++) {
			var onePointArr = splited[i].split('##');
			
			var k = -1;
			do{
				k++;
			}while (k < this.imagesLeft.length && this.imagesLeft[k].id != onePointArr[0])
			
			var j = -1;
			do{
				j++;
			}while (j < this.imagesRight.length && this.imagesRight[j].id != onePointArr[1])
			
			if (k < this.imagesLeft.length && j < this.imagesRight.length) { 
			this.drawSetAnswerLine(k, j);
			}
		};
	};
};

componentMatchDots.prototype.drawSetAnswerLine = function(k, j)
{
	var myMiddleX = this.imagesLeft[k].x + this.imagesLeft[k].w/2 - this.x;
	var myMiddleY = this.imagesLeft[k].y + this.imagesLeft[k].h/2 - this.y;
	
	var myMiddleXConP = this.imagesRight[j].x + this.imagesRight[j].w/2 - this.x;
	var myMiddleYConP = this.imagesRight[j].y + this.imagesRight[j].h/2 - this.y;
	
	var xArray = [ myMiddleX, myMiddleX, myMiddleX, myMiddleX, myMiddleXConP ];
	var yArray = [ myMiddleY, myMiddleY, myMiddleY, myMiddleY, myMiddleYConP ];			
	
	this.imagesLeft[k].xArray = xArray;
	this.imagesLeft[k].yArray = yArray;
	
	this.imagesLeft[k].connectPoint = this.imagesRight[j];
	this.imagesRight[j].connectPoint = this.imagesLeft[k];
	
	this.imagesLeft[k].connectPoint.xArray = xArray;
	this.imagesLeft[k].connectPoint.yArray = yArray;
	
	this.startPoint = this.imagesLeft[k];	
	this.updateFrame();
	
	this.imagesLeft[j].solve = (this.imagesLeft[j].pair == this.imagesRight[k].pair);
	this.imagesRight[k].solve = (this.imagesLeft[j].pair == this.imagesRight[k].pair);
		
	this.startPoint = null;
};

componentMatchDots.prototype.onLock = function() 
{
	for (var i=0; i < this.imagesLeft.length; i++) {
		this.imagesLeft[i].isLocked = true;
		this.imagesRight[i].isLocked = true;
	}
};

componentMatchDots.prototype.onUnLock = function() 
{
	for (var i=0; i < this.imagesLeft.length; i++) {
		this.imagesLeft[i].isLocked = false;
		this.imagesRight[i].isLocked = false;
	}
};

componentMatchDots.prototype.checkAnswer = function() 
{
	if (this.showAnswerIndicatorAnyTime && this.showCorrectAnswerIndicator) {
		this.paintMyDots();
	}
	return (this.parseCheckAnswer(this));
};

componentMatchDots.prototype.paintMyDots = function()
{
	for (var i=0; i < this.imagesLeft.length; i++) {
		/* //pg2-removed
		if (this.imagesLeft[i].solve) {
			this.imagesLeft[i].srcOut = this.dotCorrect;
			this.imagesLeft[i].srcIn = this.dotCorrect;
		};
		if (this.imagesRight[i].solve) {
			this.imagesRight[i].srcOut = this.dotCorrect;
			this.imagesRight[i].srcIn = this.dotCorrect;
		};
		*/
		if (this.imagesLeft[i].solve) { //pg2-new
			this.imagesLeft[i].setValue(this.resourcesURL + this.dotCorrect);
		}else { 
			this.imagesLeft[i].setValue(this.resourcesURL + this.dotIncorrect);
		};
		if (this.imagesRight[i].solve) {
			this.imagesRight[i].setValue(this.resourcesURL + this.dotCorrect);
		}else { 
			this.imagesRight[i].setValue(this.resourcesURL + this.dotIncorrect);
		};

			
	
		//this.imagesLeft[i].paint(); //pg2-removed
		//this.imagesRight[i].paint();
	};
};

componentMatchDots.prototype.parseCheckAnswer = function(index)
{
	var result = true;
	for (var i=0; i < this.imagesLeft.length; i++) {
		if (!this.imagesLeft[i].solve) result = false;
	};
	
	return result;
};

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

componentMatchDots.prototype.interactionsCorrectResponses = function(){
	var result = "";
	var sep = "";
	
	for (var i=0; i < this.imagesLeft.length; i++){
		
		var j = -1;
		do{
			j++;
		}while (j < this.imagesRight.length && this.imagesRight[j].pair != this.imagesLeft[i].pair)
		
		if (result != "") sep = "||";
		result += sep + this.imagesLeft[i].id + "#!#" + this.imagesRight[j].id;
	};
	return result;
};

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

componentMatchDots.prototype.interactionsCorrectResponsesAsText = function(index){
	var result = "";
	var sep = "";
	
	for (var i=0; i < this.imagesLeft.length; i++){
		
		var j = -1;
		do{
			j++;
		}while (j < this.imagesRight.length && this.textsRight[j].pair != this.imagesLeft[i].pair)
		
		if (result != "") sep = "||";
		result += sep + this.imagesLeft[i].clearText + "#!#" + this.imagesRight[j].clearText;
	};
	return result;
};

componentMatchDots.prototype.interactionsStudentResponseAsText = function(){
	var result = '';
	var sep = '';
	
	for (var i=0; i < this.imagesLeft.length; i++) {
		if (result != '') sep = '||';
		result += sep + this.imagesLeft[i].clearText + '#!#';
		if (this.imagesLeft[i].connectPoint) result += this.imagesLeft[i].connectPoint.clearText;
	};
	return(result);	
	
}
