$(function () {
    var task = 1,
            zindex = 10,
            result = [1, 2, 3, 4, 5],
            dropped = 0,
            drop = function (event, ui) {
                if (ui.draggable.data('value') === $(this).data('value')) {
                    var top = $(this).position().top;
                    var left = $(this).position().left;
                    dropped++;
                    ui.draggable
                            .draggable({revert: false})
                            .draggable("option", "disabled", true);
                    ui.draggable.animate({
                        top: top+23,
                        left: left+16
                    }, 900);
                    task++;
                    if (task < 6) {
                        $('.dropp').data('value', 0);
                        $("#drop" + result[task - 1]).data('value', task);
                        $('#jplayer_sound').jPlayer('setMedia', {mp3: './media/899-' + result[task - 1] + '.mp3'});
                        $('#jplayer_sound').jPlayer('play');
                    }
                    if (task === 6) {
                        $('#jplayer_well').jPlayer('play');
                    }
                } else {
                    $('#jplayer_wrong').jPlayer('play');
                    $('#jplayer_wrong').on($.jPlayer.event.ended, function (event) {
                        $('#jplayer_sound').jPlayer('play');
                    });
                }
            };

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

    $(".dropp").droppable({
        accept: ".dragg",
        tolerance: "pointer",
        drop: drop
    });

    $("#drop" + result[0]).data('value', task);
    
    for(var i=1;i<=5;i++){
        $('#p'+i).css({backgroundImage:'url(styles/images/p'+i+'.png)'});
    }

    $('#jplayer_sound').jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', {mp3: './media/899-' + result[0] + '.mp3'});
        },
        swfPath: '../../styles/flash',
        supplied: 'mp3',
        cssSelectorAncestor: '#jp_container_sound'
    });

    $('#jplayer').on($.jPlayer.event.ended, function (event) {
        $('#jplayer_sound').jPlayer('play');
    });

});