$(function()
{
	/**
	 * Configuration
	 */
	var elementsCount = 16;



	/**
	 * Elements
	 */
	var elements = [];
	for(var i=1;i<=elementsCount;++i)
		{
		elements[i-1] = (i % (elementsCount / 2)) + 1;
		}

	$.each(_.shuffle(elements),function(index,value)
		{
		$('.elements').append('<div class="type_'+value+' covered" data-type="'+value+'" data-element="'+(index+1)+'"/>');
		});

	/**
	 * Click
	 */
	var counter = 0;
	var wrong = 0;

	var clickedPairs = -1;
	var pairs = {type: [0,0], element: [0,0]};

	var click = function()
	{
		if(wrong === 1) {
			for(var i=0;i<2;++i) {
				$('.elements > *').eq(pairs.element[i]-1).addClass('covered').on('click', click);
			}
			counter -= 2;

			clickedPairs = -1;
			pairs = {type: [0,0], element: [0,0]};
			wrong = 0;
		}
		if(wrong !== 1) {
			++counter;
			++clickedPairs;

			pairs.type[clickedPairs] = $(this).data('type');
			pairs.element[clickedPairs] = $(this).data('element');

			$(this).removeClass('covered').off('click');

			if(clickedPairs === 1) {
				if(pairs.type[0] !== pairs.type[1]) {
					wrong = 1;
				} else {
					clickedPairs = -1;
					pairs = {type: [0,0], element: [0,0]};
				}
			}

			if(counter === elementsCount) {
				$('#jplayer_well').jPlayer('play');
			}
		}
	};

	$('.elements > *').click(click);
});
