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

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

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

	if (tO['background']) {
		loadSlideBackground();
	}
    
    var p = {	// properties for 3 captions
		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': '22px',
			'text-align':'center',
			'line-height': '49px'
		},
		container :{
			"position":"absolute",
			'width':'334px',
			'height':'283px',
			'top':'217px',
			"background":"rgb(241,242,242)",
			"z-index": "7"
		},
		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': '21px',
					'text-align':'left',
					'line-height': '32px'
				},
				hover_on:{
					"background":"rgb(255,255,239)"
				},
				hover_out:{
					"background":"rgb(254,255,188)"
				},
			}
		}
	}	
	

	var p2 = {	// properties for 2 captions
		end :{
			min:{
				x:500,
				y:10
			},
			max:{
				x:650,
				y:600
			},
		},
		left:{
			caption_1 : 60,
			caption_2 : 590
		},
		caption :{
			"position":"absolute",
			'width':'510px',
			'height':'50px',
			'top':'165px',
			"z-index": "10",
			"background":"rgb(26,188,156)",
			'color' : '#ffffff',
			'text-indent':'0px',
			'font-family':'Arial',
			'font-size': '22px',
			'text-align':'center',
			'line-height': '49px'
		},
		container :{
			"position":"absolute",
			'width':'510px',
			'height':'283px',
			'top':'217px',
			"background":"rgb(241,242,242)",
			"z-index": "7"
		},
		text:{
			css	:{
				main	:{
					"position":"absolute",
					'width':'508px',
					'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':'488px',
					'margin-top' : '4px',
					'margin-bottom':'4px',
					'margin-right':'10px',
					'margin-left':'10px',
					"z-index": "7",
					'text-indent':'0px',
					'font-family':'Arial',
					'font-size': '21px',
					'text-align':'left',
					'line-height': '32px'
				},
				hover_on:{
					"background":"rgb(255,255,239)"
				},
				hover_out:{
					"background":"rgb(254,255,188)"
				},
			}
		}
	}	
	
	var captions_count = tO['captions_count'];
	
	if (captions_count == 2) {
		p =p2;
	}
	
	var zIndexChange=20;
	
	var drop_in = {
		top:{},
		text:{},
		height:{},
		items :{},
		caption: {},
		caption_1 :{},
		caption_2 :{},
		caption_3 :{}
	}
	
	// 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);
	
	image_mDraggable(".items");
	//container_droppable(".container");

	console.log('drop_in:');
	console.log(drop_in);
	
	
	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);
		
		container_droppable(ssId + caption + 'container');
		
		$(ssId + caption + 'container')
			.on('drop', function( event, ui ) {	// droppable jquery ui
				
				var top = $(this).position().top;
				var left = $(this).position().left;
				var container_id = $(this).attr('id');
				var item_id = $(ui.draggable).attr('id');			
				console.log("droped in container id:"+container_id);
				console.log("caption :"+caption);
				console.log("droped item id:"+item_id);
				
				top = sort_dropped_in_items();
				
				// add items to object to track in which caption they are dropped
				drop_in[caption][item_id] = drop_in.items[item_id];
				drop_in.caption[item_id] = caption;
				drop_in.top[item_id] = top;
				console.log('drop_in:');
				console.log(drop_in);
				
				$(ui.draggable)
					.css({top: top, left: left});
				
				
				// count items height in caption and make order
				function sort_dropped_in_items() {
					for (item in drop_in.caption) {
						if (drop_in.caption[item] == caption) {
							$('#'+item).css({top: top, left: left});
							
							top += drop_in.height[item]+3;
							console.log("Item height = " + drop_in.height[item] + '; Item text = '+drop_in.text[item]);
						}
					}
					return top;
				}
				
			})
			.on( "dropactivate", function( event, ui ) {
				
				var top = $(this).position().top;
				var left = $(this).position().left;
				
				var item_id = $(ui.draggable).attr('id');
				drop_in.caption[item_id] = 0;
				
				console.log('dropout item:' + item_id);
				sort_dropped_in_items();
				function sort_dropped_in_items() {
					
					for (item in drop_in.caption) {
						if (drop_in.caption[item] == caption) {
							$('#'+item).css({top: top, left: left});
							
							top += drop_in.height[item]+3;
							console.log("Item height = " + drop_in.height[item] + '; Item text = '+drop_in.text[item]);
						}
					}	
				}
				
			} );;
	}
	
	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': '26px',
					'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(css.hover_on);
				},
				function() {
					$( this ).css(css.hover_out);
				}
			);		
		
		$(ssId+item + 'text')
			.css(css.text);
		
		var height = $(ssId+item + 'text').height();

		$(ssId + item)
			.css('height',(height+10));
		
		drop_in.text[ss + item]= items[item];
		drop_in.items[ss + item]=height+10;
		drop_in.height[ss + item]=height+10;
		drop_in.caption[ss + item]='';
	}
	
	function image_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 ) {
				
			},
			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 answered = items_caption_no();
		
		var new_right = prepare_right_answer();
		
		var correct = compareAnswers(new_right,answered);
		
		
		function prepare_right_answer() {
			var new_right = [];
			var l = right.length;
			for (var i=0;i<l;i++) {
				new_right.push(tO['answer'][right[i]]);
			}
			return new_right;
		}
		
		function items_caption_no() {
			var answered = [];
			for (item in drop_in.caption) {
				var caption_no = drop_in.caption[item];
				caption_no = parseInt(caption_no.replace('caption_',''));
				answered.push(caption_no);
			}
			return answered;
		}

		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: '+ answered);
		console.log('Right answers: '+ right);
		console.log('prepared answer: '+ new_right);
				
		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;
	};
}

