// Drag - Drop on SG 
// Carlos U

function getMatrix( obj )
{
    var matrix = obj.css("-webkit-transform") ||
                 obj.css("-moz-transform")    ||
                 obj.css("-ms-transform")     ||
                 obj.css("-o-transform")      ||
                 obj.css("transform");
    return matrix;
};

function dragF(event, ui){

    var matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*(-?\d*\.?\d+),\s*0,\s*0\)/;

    var matches = getMatrix($('[id=stage]')).match(matrixRegex);
    scaleX = matches[1];
    scaleY = matches[2];

    //Correc SG transform scale !!!!!!!
    var offset = ui.position;
    var xPos = offset.left/scaleX;
    var yPos = offset.top/scaleY ;
    ui.position = { 'top': yPos, 'left': xPos};

}

function acceptF(ui){
    dropKey = $(this).attr('ddKey');
    dragKey =ui.attr('ddKey');

    if( dropKey == dragKey )
    {
        return true;
    }

    return false;
}

function dropF(event, ui){
    var CUSTOM_CLONE = false; // bool
  
    dropKey = $(this).attr('ddkey');
    dragKey= $(ui.draggable).attr('ddkey');

    if( dropKey == dragKey ){
        sg.sound('success-low');
        ui.draggable.addClass( 'dropped' );      // Css  

    
        if ($(".drops").children('.ui-droppable-disabled').length === 6)
        {
             $("#btn-popup-success").click();
        }

        ui.draggable.data('droppedin',$(this)); // Associate the container

        $(this).droppable('disable');           // Disable the drop
        ui.draggable.draggable('option', 'disabled', true);

        if(CUSTOM_CLONE){
            var clone = $(ui.draggable).clone();
            $(clone).addClass('cloned');
            $(this).append(clone);
            snapToMiddle($(clone), $(this))
            ui.draggable.addClass('grayFilterEnabled');
        }else{
            $(this).append(ui.draggable.css('position','relative'));
            snapToMiddle($(ui.draggable), $(this))
        }

        //Reset mouse cursor
        ui.draggable.css('cursor','default');

    }
    else {
        sg.sound('error');
    }

}

function initDragDrop(selectorDrag, selectorDrop) {
    console.log('Init');

    $(selectorDrag).draggable({
        //refreshPositions: true,
        drag: dragF,
        helper: 'clone',
        revertDuration: 400,

        containment: '#contenido',

        // snap: ".drop",   //Adhiere a borde de drop
        snapMode: "fit",
    });

    // Mouse drag cursor
    $(selectorDrag).css('cursor','pointer');

    $(selectorDrop).droppable({
        drop: dropF,
        //accept: acceptF,
        activeClass: 'boxshadow' // BOX SHADOW  CSS STYLE NEEDED 
    });

    // Keeep original drags position for reset
    preserveDragsPosition(selectorDrag);

}

// Funciones de apoyo 

function snapToMiddle(dragObj, target){

    INCLUDE_MARGIN  = false;  // Include or ignore margin to calculate center 

    var topMove = (target.outerHeight(  INCLUDE_MARGIN  ) - dragObj.outerHeight(  INCLUDE_MARGIN  )) / 2;
    var leftMove= (target.outerWidth(  INCLUDE_MARGIN  ) - dragObj.outerWidth( INCLUDE_MARGIN )) / 2;

    dragObj.animate({top:topMove,left:leftMove},{duration:10,easing:'easeOutBack'});
}


//Preserve position to reset
function preserveDragsPosition(selectorDrag){

    var allDrags = $(selectorDrag);
    var offset;

    allDrags.each(function(){

        offset=$(this).position();

        $(this).data({
            'originalLeft': offset.left,
            'origionalTop': offset.top,
            'originalPosition': $(this).css('position'),
            'parentDiv': $(this).parent()

        })
    });

}

function resetDragDrop(selectorDrag, selectorDrop){

    var allDrags = $(selectorDrag).not('.cloned');
    var allDrops = $(selectorDrop);
    var dragClones = $(selectorDrag +'.cloned');

    dragClones.remove();

    // Restore postion of all drags needs same container TODO goback to previous parent -> DONE !!!!
    allDrags.each(function(){
        //$(this).appendTo($(this).data('parent')),
        $(this).appendTo($(this).data('parentDiv'));
        $(this).css({
            'left': $(this).data('originalLeft'),
            'top': $(this).data('origionalTop'),
            'position': $(this).data('originalPosition')
        })

   $(this).draggable('option', 'disabled', false); // Enable Drag
    });

    allDrops.droppable('enable');           // Enable drops
    allDrags.css('cursor','pointer');       // Restore Mouse cursor

} // Drag - Drop on SG - Carlos U
