/* T3 test template
 * requires:
 * jquery.js
 * player_test_template.js
 * iliustraData.js
 */

console.log('> templateT3.js is iniciated;');

function templateT3script() {
	console.log("function templateT1script(); sectionName=" +sectionName + "; slideName=" +slideName);
	var tO = tObj[sectionName][slideName]; 	console.log("tObj:"); 		console.log(tObj);
	var items = tO['items'];				console.log("items:");		console.log(items);
	var captions = tO['captions'];			console.log("captions:");	console.log(captions);
	
	// count items and captions
	var itemsCount = Object.keys(items).length; 		console.log('items count: ' +itemsCount);
	var captionsCount = Object.keys(captions).length; 	console.log('captions count: ' +captionsCount);
	
	var p = {	// properties
		end :{
			min:{
				x:120,
				y:10
			},
			max:{
				x:600,
				y:350
			},
		},
		text:{
			css	:{
				main	:{
					"position":"absolute",
					'width':'778px',
					'height':'48px',
					'top':'350px',
					'left':'200px',
					"cursor": "move",
					"z-index": "10",
					"border": "1px solid rgb(190,190,190)",
					"background":"rgb(255,255,239)"
				},
				text:{
					"position":"absolute",
					'width':'778px',
					'height':'48px',
					'top':'0px',
					'left':'0px',
					"z-index": "7",
					'text-indent':'30px',
					'font-family':'Arial',
					'font-size': '22px',
					'text-align':'left',
					'line-height': '48px'
				},
			}
		}
	}	
	
	var zIndexChange=20;
	
	
	// generate random end points for items x and y ;
	randomise_items_end_XY();
	
	// randomise items order
	var randPlaces = randomArray(itemsCount);
	
	change_items_to_random();
	
	//  get true - correct ; or falls - incorrect
	this.checkAnswer = checkTestAnswer;
	// check buttton and function to check
	checkTestButton(this.checkAnswer);

	appendQuestion();
/*	
	append_items(items);
	
	image_mDraggable(".items");
	*/
	function appendQuestion() {						// level 1 function
		$(ssId)
			.append('<div class="" id="' +ss+'question">'+tO['question']+'</div>');
		$(ssId+'question')
			.css({
				"position":"absolute",
				'width':'1043px',
				'height':'117px',
				'top':'43px',
				'left':'72px',
				"z-index": "6",
					'text-indent':'0px',
					'font-family':'Arial',
					'font-size': '28px',
					'line-height': '35px'
			});
	}
	
	function append_items(items) {			// level 1 function		// append f or m all items
		for (item in items) {
			console.log("item: " +item +'; ' + items[item]);
			append_item_text(item,items);
		}
	}
	
	function append_item_text(item,items) { 	// level 3 function 	// p stands for f,m params
		var e = p.end[item]; // animation end point
		var css = p.text.css; // css of item
		console.log(item + ' position: top='+e.top+' ; left='+e.left);

		$(ssId)
			.append('<div class="items" id="' + ss + item + '"></div>');

		$(ssId + item)
			.append('<div class="text_t" id="' + ss + item + 'text">' + items[item] + '</div>')
			.css(css.main)
			.animate({ 'top': e.top + 'px', 'left': e.left + 'px'}, 800, function(){})
			.hover(
				function() {
					$( this ).css("background","rgb(254,255,188)");
				},
				function() {
					$( this ).css("background","rgb(255,255,239)");
				}
			);
				
		$(ssId+item + 'text')
			.css(css.text);
	}
	
	function image_mDraggable(classId) {			// level 1 function		// make class dragable and snapable to f_items
		// make all imagem draggable	
		$( classId).draggable({
			containment:ssId,
			snapMode: "inner",
			start: function(){
				console.log("zIndexChange: "+zIndexChange);
				console.log($(this));
				$(this).css('zIndex',zIndexChange++);
			}
		});
		
		// make dragable after click on top
		$(classId).click(function() {
			$(this).css('zIndex',zIndexChange++);
		});	
	}

	function checkTestAnswer() {
		var i=0;
		var right = randPlaces;
		var xPrev=0;
		var correct = true;
		var count = 0; // count right answers
	
		var items_tops = get_items_top_positions();
		
		var items_places = get_items_places(items_tops);
		
		var correct = compareAnswers(right,items_places);
			
		function get_items_top_positions() {		// get top positions of each answer in array
			var itemsTops = [];
			for (item in items) {
				var x = parseInt($(ssId+item ).css('top'), 10);
				console.log(item + ' x = '+x );
				itemsTops.push(x);
			}
			console.log('itemsTops:');
			console.log(itemsTops);
			return itemsTops;
		}
		
		function get_items_places(items_tops) {
			var items_places = [];
			
			var l = items_tops.length;
			var i;
			var j;
			var min;
			var iplace;
			
			for (i=0;i<l;i++) {
				iplace = 0;
				for (j=0;j<l;j++) {
					if (items_tops[i]>items_tops[j]) {
						iplace++;
					}
				}
				items_places.push(iplace);
			}
			console.log('items_places:');
			console.log(items_places);
			return items_places;
		}
			
		function compareAnswers(right,answered) {
			var result_array =[];
			var count=0;
			var l = right.length;
			
			for (var i = 0; i < l; i++) {
				if (right[i] == answered[i]) {
					result_array[i] = true;
					count++;	// count right answers
					$(ssId+'item_'+i).css("border", "1px solid rgb(190,190,190)");
				}
				else{
					result_array[i] = false;
					$(ssId+'item_'+i).css("border", "2px solid rgb(255,72,0)");
				}
			}
			console.log('result_array:');
			console.log(result_array);
			
			if (count == l) {
				return true;
			}
			else{
				return false;
			}
			//return result;
		}

		console.log('Answered: '+ items_places);
		console.log('Right answer: '+ randPlaces);
				
		testAnswer(correct);
		return correct;
	}

	function randomise_items_end_XY() {			// make random x and y coordinates of items between min and max coordinates
		
		randomise();
		// make x and y with diviation for 6 images
		function randomise() {
			var i = itemsCount;
			var e = p.end; // end properties
			var minx = e.min.x,
				miny = e.min.y,
				maxx = e.max.x,
				maxy = e.max.y;
			console.log('minx='+minx+'; maxx='+maxx+'; miny='+miny+'; maxy='+maxy);
			
			// delta x, delta y
			var dx = ((maxx-minx)/i).toFixed(0);
			var dy = ((maxy-miny)).toFixed(0);
			
			console.log('delta dx='+dx+'; delta dy='+dy);
			
			for (var j = 0; j<itemsCount;j++) {
				var xy =[];
				
				var x;
				var y;	
				
				x = +( (j * dx)+ (dx *0.5* Math.random())).toFixed(0);
				y = +( (dy * Math.random())).toFixed(0);
				
				x += +minx
				y += +miny
				console.log('item_'+j+': x='+x+'; y='+y);
				
				e['item_'+j] = {};
				e['item_'+j]['top'] = x;
				e['item_'+j]['left'] = y;
			}
			console.log('randomise_items_end_XY :');
			console.log(e);
		}	
	}
	
	function randomArray(count) {				// make a random array of count numbers; count - 5; result example = [3,2,0,4,1]
		var max = count -1;
		console.log('JSF random(count)');
		var result = [];
		var depth = 0 ;
		var sum = 0;
		
		// get first random element and put in result
		var x = (Math.random() * max).toFixed(0);
		console.log('First element: ' + x);
		result.push(+x);
		console.log('result:');
		console.log(result);
		sum += +x;
		// get second and until the last elements
		for (var i =1;i<count-1;i++) {
			x = randomUnique(max);
			result.push(+x);	
			sum += +x;
			console.log('sum: ' +sum);
			console.log('result:');
			console.log(result);
		}
		
		// get last element : total sum of all numbers minus counted sum
		x = (count-1)/2 * count - sum;
		result.push(x);
		console.log('Last element: ' + x);
		console.log('result:');
		console.log(result);
		
		function randomUnique(max){
			depth++;
			console.log('depth+='+depth);
			
			var r = (Math.random() * max).toFixed(0);
			console.log('random=' + r);
			
			for ( var j=0;j<count-1;j++) {
				console.log('result['+j+']='+result[j] +'; random=' +r);
				if (result[j] === +r) {
					console.log('equal');
					r = randomUnique(max);
				}
			}
			depth--;
			console.log('depth-='+depth);
			return r;
		}
		return result;
	}
	
	function change_items_to_random() {
		var newOrder = {};
		var i=0;
		randPlaces.forEach(function(e){
			newOrder['item_'+i] = items['item_'+e]; // get images in new places by randPlaces set
			i++;
		});
		console.log(newOrder);
		// change real items with random
		items = newOrder;
	};
}