
$(function ()
{

	/**
	 * Elements
	 */

	var elements = [];
	for (var i = 1; i <= 16; ++i)
	{
		elements[i - 1] = i;
	}
	var positions = [
		[-47, -38], [85, -38], [218, -38], [351, -38],
		[-47, 100], [85, 100], [218, 100], [351, 100],
		[-47, 235], [85, 235], [218, 235], [351, 235],
		[-47, 370], [85, 370], [218, 370], [351, 370],
	];
	var count = 0;
	$.each(_.shuffle(elements), function (index, value)
	{
		$('.elements').append('<div style="position: absolute; right: ' + positions[count][0] + 'px; top: ' + positions[count][1] + 'px;" class="element_' + value + '" data-element="' + value + '"/>');
		count++;

	});

	$('.elements > *').each(function ()
	{
		var $this = $(this);

		$this.draggable(
			{
				stack: '.elements > *',
				contaiment: '.main',
				cursor: 'move',
				opacity: .7,
				scope: $this.data('element')
			});
	});

	/**
	 * Droppable
	 */
	var counter = 0;

	$('.boxes > *').each(function ()
	{
		var $this = $(this);

		$this.droppable(
			{
				accept: $('.elements > *'),
				addClasses: false,
				scope: $this.data('kind'),
				drop: function (event, ui)
				{
					++counter;

					$(event.target).addClass('ok').droppable('disable');
					$(event.target).css('background', '');
					if (!$("html").hasClass("ie8")) {
						ui.helper.css('display', 'none').draggable('destroy');
					}
					;

					if (counter === 16)
					{
						var top, left;
						$('.dragg,.target').fadeIn()
						$(".dragg").draggable(
							{
								contaiment: $('main'),
								stack: ".dragg"
							});
						$('.target').droppable(
							{
								addClasses: false,
								drop: function (event, ui)
								{

									top = $(this).position().top + ($(this).height() / 2) - (ui.draggable.height() / 2);
									left = $(this).position().left + ($(this).width() / 2) - (ui.draggable.width() / 2);
									ui.draggable.animate({left: left, top: top}, {duration: 500, easing: 'easeOutBounce'});
									if ($(this).data('value') === ui.draggable.data('value'))
									{
										$('#jplayer_well').jPlayer('play');
									} else {
										ui.draggable.animate({left: "+=400", top: "+=100"}, {duration: 1100, easing: 'easeOutBounce'});
										$('#jplayer_wrong').jPlayer('play');
									}
								}

							});
					}

				}
			});
	});
	/**
	 * Hint
	 */
	$('a.hint').click(function (e)
	{
		e.preventDefault();
		$('div.hint').fadeToggle();
	});

});
