var ui_dragging = false;



function overwriteGreyBoxLinks(){
    var as = AJS.$bytc('a');
    AJS.map(as, function(a) {
        if(a.getAttribute('href') && a.getAttribute('rel')) {
            oldfunc = a.onclick
            a.onclick = function(e) {
                if(ui_dragging){
                    e.stopPropagation();
                    e.preventDefault();    
                }else{
                    oldfunc();
                }
                ui_dragging = false;
            };
        }
    });
}

function refreshSimplelayoutDragndropOrdering() { 
    
    var sl_content = jq('.simplelayout-content');
    
/*
    jq('.simplelayout-content a[rel]').bind('click', function(e){
        //prevent browser from opening if an image is dragged or greybox installed. wiered stuff
        if(GreyBox){
            e.stopPropagation();
            e.preventDefault();    
        }else{
            ui_dragging = false; 
        }
    });
    */


    jq('.BlockOverallWrapper .sl-controls').bind("mousedown",function(e){
        jq(this).toggleClass('mouseToggler');
        })

    jq('.BlockOverallWrapper .sl-controls').bind("mouseup",function(e){
        jq(this).toggleClass('mouseToggler');
        })

    sl_content.sortable({
		items: '.BlockOverallWrapper',
        handle: jq('.BlockOverallWrapper .sl-controls'),
        scroll : true,
		forcePlaceholderSize : false,
		placeholder: 'placeholder',
        appendTo : '.BlockOverallWrapper',
		opacity: 0.5,
		tolerance:'guess',
		start: function(e,ui) {
		    ui_dragging = true
		    ui.placeholder.css("width", ui.item.width());
		    ui.placeholder.css("height", ui.item.height());

		},
		update: function(e, ui){
            var ids = new Array();
            jq('.BlockOverallWrapper').each(function(i, o) { ids.push(o.id); });
            ids = ids.join(',');
            jq.post('sl_dnd_saveorder', { uids : ids });
		},
		stop: function(e, ui){
		    ui.item.removeAttr("style");
		}

    })
    
    if(gup('edit_mode')){
        sl_content.sortable('enable');
        //setTimeout(overwriteGreyBoxLinks, 500);
    }else{
        sl_content.sortable('disable');
    }
    
    sl_content.bind("toggleeditmode", function(e){
        sl_content.sortable('enable');
        //overwriteGreyBoxLinks();
    });
}

jq(refreshSimplelayoutDragndropOrdering);

