var matrix = [],snapping = true,dragGroups = [],game_won=false;
function stop() {
    window['stop'] = false;
}
function eachframe() {
    if (window['stop'] == false) return false;
    can.drawImage(video, 0, 0);
    if (!isNaN(video.duration)) {
        //loop

        if (video.currentTime >= video.duration) {
            video.currentTime = 0;
            video.play();
        }
    }

    $('#can_space canvas').each(function() {
        //todo:update values here to values of the container
        leftt = (this.curLeft > 512) ? 512 : this.curLeft;
        topp = (this.curTop > 240) ? 240 : this.curTop;

        leftt = this.curLeft;
        topp = this.curTop;
        try {
            window['piece_' + $(this).index()].drawImage(can_origin, leftt, topp, elm_width, elm_height, 0, 0, elm_width, elm_height);
        }
        catch(e) {


        }

    })
}

function initializePieces() {
    dummyElm = $('<canvas></canvas>');
    //create as many elm as nessesary
    elm_width = $('#can_space').width() / x_ammount;
    elm_height = $('#can_space').height() / y_ammount;
    _index = 0;
    for (var i = 1; i <= y_ammount; i++) {
        matrix[i] = [];
        for (var j = 1; j <= x_ammount; j++) {
            _index++;
            _elm = dummyElm.clone();
            _elm.attr({'id' : 'piece_' + _index,'width' : elm_width,'height' :elm_height})
                .appendTo('#can_space').data('position','{"row":'+i+',"col":'+j+'}');
            matrix[i].push(_elm);
        }
    };
    matrix.shift();

    $('#can_space canvas').each(function(i,e) {
        window['piece_' + $(this).index()] = $(this)[0].getContext("2d");
        parent_pos = $('#can_space').position();
        pos = $(this).position();
        this._height = $(this).height();
        this._width = $(this).width();
        this.curTop = pos.top - parent_pos.top;
        this.curLeft = pos.left - parent_pos.left;

        getMySiblings(e);
        $(this)
        .css({left:this.curLeft, top : this.curTop})
        .draggable({
            snap: true,
            stack: "#can_space canvas",
            start:function(a,helper){
              elDragStartY = helper.position.top;
              elDragStartX = helper.position.left;
            },
            drag: function(a,helper){

              var grp = $(a.target).data('group');
              if(grp != undefined){
                  //calculate distanse of drag
                  $('#can_space canvas[data-group="'+grp+'"]').each(function(i,elm){
                      if(elm!=a.target){
                          diffY = Math.round($(elm).position().top + (helper.position.top - elDragStartY));
                          diffX = Math.round($(elm).position().left + (helper.position.left - elDragStartX));
                          $(elm).css({'top':diffY,'left':diffX});
                      };
              });
              elDragStartY = helper.position.top;
              elDragStartX = helper.position.left;

               }
            },
            stop: function(a,helper,elm){
                _sibObj = JSON.parse($(a.target).data('siblings'));
                locateSiblings(_sibObj,$(a.target));

                var grp = $(a.target).data('group');
                if(grp != undefined){
                    $('#can_space canvas[data-group="'+grp+'"]').not(a.target).each(function(i,elm){
                        _sibObj = JSON.parse($(elm).data('siblings'));
                        locateSiblings(_sibObj,$(elm));
                    });
                }
            }
        });
    });

}
function randomizeLocations() {
    choises_arr = [];
    elm_arr = $('#can_space canvas');
    elm_arr.each(function() {
        choises_arr[$(this).index()] = $(this).position();
    });
    elm_arr.each(function() {
        rnd_keyt = $.randomBetween(0, 15);
        rnd_index = $.randomBetween(0, choises_arr.length - 1);
        rnd_location = choises_arr[rnd_index];
        movePiece(this, rnd_location.left + rnd_keyt, rnd_location.top + rnd_keyt);
        choises_arr.splice(rnd_index, 1);
    });

    //clear all groups
    $("#can_space canvas").each(function(){
        $(this).data('group',null).attr('data-group',undefined);
    });
}
function getMySiblings(elm){
    var _top,_bottom,_left,_right,_elm = $(elm),_pos;
    pos = JSON.parse($(elm).data('position'));
    _top = (pos.row == 1) ? 0 : matrix[pos.row-2][pos.col-1];
    _bottom = (pos.row == y_ammount) ? 0 : matrix[pos.row][pos.col-1];
    _left = (pos.col == 1) ? 0 : matrix[pos.row-1][pos.col-2];
    _right = (pos.col == x_ammount) ? 0 : matrix[pos.row-1][pos.col];
    str = {"top":$(_top).attr('id'),"bottom":$(_bottom).attr('id'),"left":$(_left).attr('id'),"right":$(_right).attr('id')};
    _elm.data('siblings',JSON.stringify(str));
    return;
}
function locateSiblings(sibObj,elm){
    if(game_won) return;
    thisPos = $(elm).position();
    $.each(sibObj,function(i,e){
        sibPos = $("#"+e).position();
        if(snapping == false) return;
        switch(i){
            case 'top':
                if(sibPos.top == Math.round(thisPos.top - elm_height) && thisPos.left == sibPos.left){
//                    console.log('found top');
                    addPiecesToGroup($(elm),$('#'+e));
                };
            break;
            case 'bottom':
                if(sibPos.top == Math.round(thisPos.top + elm_height) && thisPos.left == sibPos.left){
//                    console.log('found bottom');
                    addPiecesToGroup($(elm),$('#'+e));
                };
            break;
            case 'left':
                if(sibPos.left == Math.round(thisPos.left - elm_width) && thisPos.top == sibPos.top){
//                    console.log('found left');
                    addPiecesToGroup($(elm),$('#'+e));
                };
            break;
            case 'right':
               if(sibPos.left == Math.round(thisPos.left + elm_width) && thisPos.top == sibPos.top){
                    addPiecesToGroup($(elm),$('#'+e));
               };
            break;
        }
    });
}
function addPiecesToGroup(piece,sibling){
    if(piece.data('group') == undefined && sibling.data('group') == undefined){
        var grpName = piece.attr('id');
        if($.inArray(grpName,dragGroups) == -1){
            dragGroups.push(grpName);
            piece.attr('data-group',grpName).data('group',grpName);
            sibling.attr('data-group',grpName).data('group',grpName);
        }
    }else if(piece.data('group') != undefined && sibling.data('group') == undefined){
            sibling.attr('data-group',piece.data('group')).data('group',piece.data('group'));
    }else if(piece.data('group') == undefined && sibling.data('group') != undefined){
            piece.attr('data-group',sibling.data('group')).data('group',sibling.data('group'));
    }else if(piece.data('group') != sibling.data('group')){
            var tmp = piece.data('group');
            var tmp2 = sibling.data('group');
            var grp1 = $('#can_space canvas[data-group="'+tmp+'"]');
            var grp2 = $('#can_space canvas[data-group="'+tmp2+'"]');
            if(grp2.length > grp1.length){
                $('#can_space canvas[data-group="'+tmp+'"]').data('group',tmp2).attr('data-group',tmp2);
                dragGroups.splice($.inArray(tmp,dragGroups),1);
            }else{
                $('#can_space canvas[data-group="'+tmp2+'"]').data('group',tmp).attr('data-group',tmp);
                dragGroups.splice($.inArray(tmp2,dragGroups),1);
            }
    }else{
        if($('#can_space canvas').length ==  $('#can_space canvas[data-group="'+dragGroups[0]+'"]').length){
            alert('you win!!!!');
            game_won = true;
        }
    }
//     piece.addClass('dragGroup');
//     sibling.addClass('dragGroup');
}
function movePiece(el, x, y) {
    $(el).animate({
        'left' : x,
        'top' : y
    }, 1900);
}
function playControl(elm) {
    if (video.paused == false) {
        window['stop'] = false;
        video.pause();
        if (elm != null) {
            $(elm).html = 'Play';
        }
    } else {
        window['stop'] = true;
        video.play();
        if (elm != null) {
            $(elm).html = 'Play';
        }
    }
}
