/* 3e test template
 * sort items in 3 columns
 * requires:
 * jquery.js
 * player_test_template.js
 * iliustraData.js
 */

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

function template3escript() {
	console.log("function template3escript(); 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);
	
	// count items
	var itemsCount = tO['items_count']; 	console.log('items count: ' +itemsCount);

	if (tO['background']) {
		loadSlideBackground();
	}
    
    var p = {	// properties
		end :{
			min:{
				x:500,
				y:10
			},
			max:{
				x:650,
				y:600
			},
		},
		left:{
			caption_1 : 60,
			caption_2 : 414,
			caption_3 : 768
		},
		caption :{
			"position":"absolute",
			'width':'334px',
			'height':'50px',
			'top':'165px',
			"z-index": "10",
			"background":"rgb(26,188,156)",
			'color' : '#ffffff',
			'text-indent':'0px',
			'font-family':'Arial',
			'font-size': '24px',
			'text-align':'center',
			'line-height': '50px'
		},
		container :{
			"position":"absolute",
			'width':'334px',
			'height':'283px',
			'top':'217px',
			"background":"rgb(241,242,242)",
			"z-index": "5"
		},
		text:{
			css	:{
				main	:{
					"position":"absolute",
					'width':'331px',
					'height': 'auto',
					'top':'350px',
					'left':'200px',
					"cursor": "move",
					"z-index": "10",
					"border": "1px solid rgb(252,235,143)",
					//'opacity':'0.5',
					"background":"rgb(254,255,188)"
				},
				text:{
					"position":"absolute",
					'width':'311px',
					'margin-top' : '4px',
					'margin-bottom':'4px',
					'margin-right':'10px',
					'margin-left':'10px',
					"z-index": "7",
					'text-indent':'0px',
					'font-family':'Arial',
					'font-size': '24px',
					'text-align':'left',
					'line-height': '33px'
				},
				hover_on:{
					"background":"rgb(255,255,239)"
				},
				hover_out:{
					"background":"rgb(254,255,188)"
				},
			}
		}
	}	
	
	var zIndexChange=20;
	
	// track to whitch caption(container) belongs item 0 is no one at the beggining
	var items_caption = items;
	
	var draggable_item;
	
	// droppable item top place 
	var containers_top = {
			caption_1 : 2,
			caption_2 : 2,
			caption_3 : 2
		};
	
	// 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);

	loadSlideBackground();
	
	appendQuestion();
	
	append_captions(tO.captions);
	
	append_items(items);
	
	item_mDraggable('.items');
	container_droppable('.container');
	
	console.log('items_caption:');
	console.log(items_caption);
	
	
	$( ".container" ).sortable({
		revert: true,
        // connectWith: "#droppable",
		placeholder: "ui-items",
		connectWith: ".container",
		handle: '.handle',
		cursor: 'move'
    });
	//$( "#sortable" ).disableSelection();
	
	
	function append_captions(captions) {
		for (caption in captions) {
			console.log("caption: " +caption +'; ' + captions[caption]);
			append_caption_text(caption,captions);
		}
	}
	
	function append_caption_text(caption,captions) {
		var left = p.left[caption]; // animation end point
		var css = p.caption; // css of caption
		
		console.log(caption + ' position: left='+left );
		$(ssId)
			.append('<div id="' + ss + caption + '">' + captions[caption] + '</div>')
			.append('<div class="container" id="' + ss + caption + 'container' + '"></div>');

		$(ssId + caption)
			.css(p.caption)
			.css('left',left);
			
		
		$(ssId + caption + 'container')
			.css(p.container)
			.css('left',left)
			.on('drop', function( event, ui ) {	// droppable jquery ui
				console.log( "container: " + caption);
				items_caption[draggable_item] = caption;
				console.log( "Item caption: " + items_caption[draggable_item]);
				
				console.log( "items_caption: ");
				console.log( items_caption);
				
				
				//var c_top = $(ui.draggable).height();
				
				var c_top = 1;
				
				$(this).children().each(function(){
					c_top = c_top + 2+ $(this).outerHeight();
					console.log('Children ' + $(this).attr('id') +' height: '+$(this).outerHeight());
				});
				
				console.log('drop draggable height: '+c_top);
				
				containers_top[caption] = c_top  ;
				
				$(ui.draggable)
					.detach()
					.css({top: containers_top[caption],left: 0})
					.appendTo(this);
				}
			);
	}
	
	function appendQuestion() {						// level 1 function
		$(ssId)
			.append('<div class="" id="' +ss+'question">'+tO['question']+'</div>');
		$(ssId+'question')
			.css({
				"position":"absolute",
				'width':'1043px',
				'height':'70px',
				'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
		
		// startin items caption is 0, couse is not in any caption container
		items_caption[item] = 0;
		
		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(){})
			.animate({ 'top': 0 + 'px', 'left': 0 + 'px'}, 800, function(){})
			.hover(
				function() {
					$( this ).css(css.hover_on);
				},
				function() {
					$( this ).css(css.hover_out);
				}
			)
			.on(
				"dragstart", function( event, ui ) {
					
					
					$(ssId + item)
						.appendTo(ssId); // reappend item to slide from container
						
					draggable_item = item;
					order_items_in_container(items_caption[item]);
					items_caption[item] = 0;
					console.log('Item drag started: '+ draggable_item);
					console.log('Item caption: '+ items_caption[item]);
				}
			);		
		
		$(ssId+item + 'text')
			.css(css.text);
		
		var height = $(ssId+item + 'text').height();

		$(ssId + item)
			.css('height',(height+10));
	}
	
	function order_items_in_container(caption) {
		
	}
	
	function item_mDraggable(classId) {			// level 1 function		// make class dragable and snapable to f_items
		// make all items draggable	
		$( classId).draggable({
			//snap: '.items',
			//snap: '.container',
			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 container_droppable(classId){
		$( classId).droppable({
			drop: function( event, ui ) {
				/*
				$(ui.draggable)
					.detach()
					.css({top: 0,left: 0})
					.appendTo(this);
				
				console.log('draggable height: '+$(ui.draggable).height());
					*/
			},
			out: function( event, ui ) {
			}
		});
	}
	
	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
		// make x and y with diviation for 6 images
		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<i;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;
	};
}

