$(function ()
{
    var zindex = 10;
    var top;
    var left;

    for (var copy = 0; copy < 3; copy++) {
	for (var i = 1; i <= 10; i++) {
	    left = 53;
	    top = 25 + ((i - 1) * 46);
	    $('main').append('<div style="left:' + left + 'px;top:' + top + 'px;" class="textbox dragg" data-dropped="0" data-value="' + i + '">' + i + '</div>');
	}
	$('main').append('<div style="left:53px;top:484px;" class="textbox dragg" data-dropped="0" data-value="+">+</div>');
	$('main').append('<div style="left:53px;top:529px;" class="textbox dragg" data-dropped="0" data-value="-">&minus;</div>');
    }
    
    $('main').append('<div class="textbox less sprite btn dragg" data-dropped="0" data-value="<"></div>');
    $('main').append('<div class="textbox more sprite btn dragg" data-dropped="0" data-value=">"></div>');

    $(".dragg").draggable({
	start: function () {
	    zindex++;
	    $(this).css('z-index', zindex);
	}
    });

    var drop = function (event, ui) {
	if (ui.draggable.data('dropped') === 0) {
	    ui.draggable.data('dropped', 1).attr("data-dropped", "1");
	    $(this).data('value', ui.draggable.data('value'));
	    var a = $(this).attr('id');
	    var b = a.substr(1, 1);
	    if (b === "1") {
		check1();
	    }
	    if (b === "2") {
		check2();
	    }
	    if (b === "3") {
		check3();
	    }
	}
    };

    var out = function (event, ui) {
	if (ui.draggable.data('dropped') === 1) {
	    ui.draggable.data('dropped', 0).attr("data-dropped", "0");
	    $(this).data('value', 0);
	}
    };

    $(".target").droppable({
	accept: ".textbox",
	tolerance: "pointer",
	drop: drop,
	out: out
    });
    
    function check1() {
	var t11 = $("#t11").data('value');
	if (t11 === '>')
	{
	    $('#jplayer_well').jPlayer('play');
	    $("#z1 > *").css("border-bottom-color", "#35B105");
	} else {
	    if (t11 !== 0) {
		$('#jplayer_wrong').jPlayer('play');
		$("#z1 > *").css("border-bottom-color", "#DA251C");
	    }
	}
    }
    
    function check2() {
	var t21 = $("#t21").data('value');
	var t22 = $("#t22").data('value');
	var t23 = $("#t23").data('value');

	if (
		(t21 + t23 === 10) &&
		(t22 === '+') &&
		(t21 === 8 || t21 === 2) &&
		(t23 === 8 || t23 === 2)
		)
	{
	    $('#jplayer_well').jPlayer('play');
	    $("#z2 > *").css("border-bottom-color", "#35B105");
	} else {
	    if (t21 !== 0 && t22 !== 0 && t23 !== 0) {
		$('#jplayer_wrong').jPlayer('play');
		$("#z2 > *").css("border-bottom-color", "#DA251C");
	    }
	}
    }
    
    function check3() {
	var t31 = $("#t31").data('value');
	var t32 = $("#t32").data('value');
	var t33 = $("#t33").data('value');

	if (
		(t31 + t33 === 9) &&
		(t32 === '+') &&
		(t31 === 2 || t31 === 7) &&
		(t33 === 2 || t33 === 7)
		)
	{
	    $('#jplayer_well').jPlayer('play');
	    $("#z3 > *").css("border-bottom-color", "#35B105");
	} else {
	    if (t31 !== 0 && t32 !== 0 && t33 !== 0) {
		$('#jplayer_wrong').jPlayer('play');
		$("#z3 > *").css("border-bottom-color", "#DA251C");
	    }
	}
    }
});