$(function()
{

	var boxes = [0,0,0,0,0,0];
	var numbers = [25,26,27,35,36,37]
	var right = [26,37,35,27,36,25];
	var dataValue;
	var cloneText;
	var left = 20;
	var top = 456;
	var prezents = 30;
	var interval;

	for (var i = 0; i < 30; i++)
	{
		$('.boxes').append('<div class="box"></div>');
	}

	for (var i = 0; i < 6; i++)
	{

		left += 70;
		$('main').append('<div style="left:'+left+'px;top:'+top+'px;" class="textbox dragg " data-dropped="0" data-value="'+numbers[i]+'">'+numbers[i]+'</div>');

	}

	$('.start').click(function(){
		$(this).fadeOut();
		$('.math,.target').fadeIn();
		interval = setInterval(function(){
		$('.boxes > *:last-child').fadeOut(function(){$(this).remove();});
		prezents--;
		if (prezents <= 0)
		{
		$('#jplayer_wrong').jPlayer('play');
			setTimeout(function(){
				document.location.reload();
			},2500);
		intervalclearInterval(interval);
		}
		},8000);
	});




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

	$('.target').droppable(
			{
			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();
						el.animate({left:left, top:top},{duration: 500, easing: 'easeOutBounce',complete: function() {
							$(this).draggable({stack: ".textbox"});
						}});
						boxes[$(this).data('value')] = ui.draggable.data('value');

						if ($.grep(boxes, function( n, i ) {return n === 0;}).length === 0)
						{
							if (right.toString() === boxes.toString())
							{
							clearInterval(interval);
							$('#jplayer_well').jPlayer('play');
							} 
							else
							{
							$('#jplayer_wrong').jPlayer('play');
							
							
							for (var i=0;i < boxes.length;i++)
							{
								if (boxes[i] !== right[i])
								{
								$('.droppat'+i).fadeOut(function(){$(this).remove();});
								boxes[i] = 0;
								}
							}
							
							}
						}

					}
				},
				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;
					}
				}
			});

});