$(function()
{

        var elements = [6, 12, 17, 18, 23, 35, 40, 52, 58, 75 , '+', '&ndash;', '='];
	var dataValue;
	var cloneText;
	var boxes = [0,0,0,0,0,0];
        var turn = 0;
	var offset = 0;
	var left = 95;
	var top = 395;

	for (var i = 0; i < elements.length; i++)
	{
		$('main').append('<div style="left:'+left+'px;top:'+top+'px;" class="textbox dragg" data-dropped="0" data-value="'+elements[i]+'">'+elements[i]+'</div>');
		top +=40;
		offset++;
		if (offset===5) {
			top -=200;
			left +=50;
			offset=0;
		}
	}

	left=510;
	top=100;
	for (var i = 0; i < 5; i++)
	{
		$('main').append('<div id="t'+i+'" style="left:'+left+'px;top:'+top+'px;" class="target" data-value="'+i+'"></div>')
		left +=52;
	}
	$('main').append('<div id="t'+i+'" style="left:660px;top:177px;" class="target" data-value="'+i+'"></div>')

	$(".textbox").draggable({revert: true, helper: 'clone'});

	var dropableOptions = 	{
			addClasses: false,
			drop: function(event,ui)
				{
				if (ui.draggable.data('dropped') === 0)
					{
						top = $(this).position().top + ($(this).height() / 2) - (ui.draggable.height() / 2);
						left = $(this).position().left + ($(this).width() / 2) - (ui.draggable.width() / 2);
						dataValue = ui.draggable.data('value');
						cloneText = ui.draggable.text();
						$('.droppat'+$(this).data('value')).fadeOut(function(){$(this).remove();});
						var el = $('<div data-value="'+dataValue+'" data-dropped="1" style="position: absolute; top: '+ui.helper.position().top+'px; left: '+ui.helper.position().left+'px;" class="textbox clone droppat'+$(this).data('value')+'">'+cloneText+'</div>');
						$('main').append(el);
						ui.helper.remove();
						console.log(ui.draggable.data('value'))
						boxes[$(this).data('value')]=ui.draggable.data('value');
						el.animate({left:left, top:top},{duration: 500, easing: 'easeOutBounce',complete: function() {
							$(this).draggable({stack: ".textbox"});
							if ($.grep(boxes, function( n, i ) {return n === 0;}).length === 0) checkTurn();
						}});


					}
				},
				out: function(event, ui) {
					if (ui.draggable.data('dropped') === 1)
					{
						ui.draggable.removeClass('droppat'+$(this).data("value"));
						ui.draggable.data('dropped',0);
						boxes[$(this).data('value')]=0;
					}
				}
			}

	$('.target').droppable(dropableOptions);

var q = ['O ile mniej jest wiewiórek niż zajęcy?','Ile jest wiewiórek i jeży?','Ile zwierząt mieszka w lesie?'];
var a = ['Wiewiórek jest o &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mniej niż zajęcy.','Wiewiórek i jeży jest razem &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.','W lesie mieszka &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; zwierząt.'];
var p = [710,890,748];

function makeTurn() {
	if (turn < 3)
	{
	boxes = [0,0,0,0,0,0];
	}
	if (turn === 3)
	{
	boxes = [0,0,0,0,0,0,0,0];
	left=460;
	top=100;
	$('.target').remove();
	for (var i = 0; i < 8; i++)
	{
		$('main').append('<div id="t'+i+'" style="left:'+left+'px;top:'+top+'px;" class="target" data-value="'+i+'"></div>');
		left +=52;
	}
	$('.target').droppable(dropableOptions);
	}
	if (turn === 4)
	{
	$('.target, .bar > *').fadeOut();
	$('.end').fadeIn();
	}

	$('.clone').fadeOut(function(){$(this).remove();});
	$('#question').text(q[turn-1]);
	$('#answer span:last-child').html(a[turn-1]);
	$('.target').last().css('left',p[turn-1]+'px')
				.css('top','177px');
};


function checkTurn() {
	var ok = false;
	var wrong = [];
	var right = [];
	var temp = [];
	var dif = [];
		if (turn === 0)
		{
			right = [35,'–',23,'=',12,12];
			ok = true;
			for (var i=0;i < boxes.length;i++)
			{
				if (boxes[i] !== right[i])
				{
				ok = false;
				wrong.push(i);
				}
			}
		}
		if (turn === 1)
		{
			right = [23,'–',17,'=',6,6];
			ok = true;
			for (var i=0;i < boxes.length;i++)
			{
				if (boxes[i] !== right[i])
				{
				ok = false;
				wrong.push(i);
				}
			}
		}
		if (turn === 2)
		{
			ok = false;
			right = [17,35];

			right.forEach(function(entry) {
					var toClear = getAllIndexes(boxes,entry);
					if (toClear.length > 1)
					{
					toClear.shift()
					wrong = wrong.concat(toClear);
					}
				    });

			temp = [boxes[0],boxes[2]];
			dif = _.difference(temp,right);
			if (dif.length === 0 && boxes[1] === '+' && boxes[3] === '=' && boxes[4] === 52 && boxes[5] === 52) ok = true;
				else
				{
					if (boxes[1] !== '+') wrong.push(1);
					if (boxes[3] !== '=') wrong.push(3);
					if (boxes[4] !== 52) wrong.push(4);
					if (boxes[5] !== 52) wrong.push(5);
					_.uniq(dif).forEach(function(entry) {
						var toClear = getAllIndexes(boxes,entry);
						wrong = wrong.concat(toClear);
					    });
				}
		}
		if (turn === 3)
		{
			ok = false;
			right = [17,23,35];

			right.forEach(function(entry) {
						var toClear = getAllIndexes(boxes,entry);
						if (toClear.length > 1)
						{
						toClear.shift()
						wrong = wrong.concat(toClear);
						}
					    });

			temp = [boxes[0],boxes[2],boxes[4]];
			dif = _.difference(temp,right);
			if (dif.length === 0 && boxes[1] === '+' && boxes[3] === '+'  && boxes[5] === '='  && boxes[6] === 75 && boxes[7] === 75) ok = true;
				else
				{
					if (boxes[1] !== '+') wrong.push(1);
					if (boxes[3] !== '+') wrong.push(3);
					if (boxes[5] !== '=') wrong.push(5);
					if (boxes[6] !== 75) wrong.push(6);
					if (boxes[7] !== 75) wrong.push(7);
					_.uniq(dif).forEach(function(entry) {
						var toClear = getAllIndexes(boxes,entry);
						wrong = wrong.concat(toClear);
					    });
				}
		}

	if (ok === true)
	{
	$('#jplayer_well').jPlayer('play');
	turn++;
	makeTurn();
	}
	else
	{
	wrong = _.uniq(wrong);
	for (var i=0;i<wrong.length;i++)
	{
		$('.droppat'+wrong[i]).fadeOut(function(){$(this).remove();});
		boxes[wrong[i]] = 0;
	}
	$('#jplayer_wrong').jPlayer('play');
	}
};

function getAllIndexes(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes;
}


});