
$(function()
	{
	/**
	 * Elements
	 */

	var elements = [];
	var zindex = 200;
	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(
			{
			cursor: 'move',
			opacity: .8,
			scope: $this.data('element'),
			start: function(){
				zindex++;
				$(this).css('z-index', zindex);
			}
			});
		});

	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){
					$('main > *').fadeOut(function(){});
					$('.coloring').fadeIn();
					$('.wrapper').css({'background':'#96c7eb'});
				counter=0;
				}
				}
			});
		});

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


	$('.colors > *').draggable({revert:true});
	$('.drop').droppable({
		tolerance: 'pointer',
		drop: function(event,ui)
		{
			if ($(this).data('value') === ui.draggable.data('value')) {
			var classes = $(this).attr('class').split(' ');
			var position = $(this).position();
			$(this).fadeOut().droppable('disable');
			$('.coloring').append('<div style="left:' + (position.left+2) + 'px;top:' + (position.top+3) +'px" class="drop '+classes[1]+' fix"></div>');
			counter++;
			if (counter === 4) $('#jplayer_well').jPlayer('play');
			} else $('#jplayer_wrong').jPlayer('play');

		}
		});

	});
