//DRAG AND DROP
//
//Pinquin.nl
//Date: 2010-11-02
//Version: 0.3
//Jquery version: 1.4.2
//
/*Changes
 * Compatible with other js plugins
 * Transparency added while dragging
 * localStorage, remembers element position (HTML5 browser req.)
 */
//$("div.draggable").dragdrop();

( function(jQuery) {
	var draggable, prev_drag, mouseX, mouseY, z;
    
	jQuery.fn.dragdrop = function() {
		return this.each( function() {
			if( window.localStorage ) {
				if( window.localStorage.getItem(jQuery(this).attr('id') ) ) {
					var tmp_storage = window.localStorage.getItem(jQuery(this).attr('id') ).split("x")[1];
					jQuery(this).css( {
						left: tmp_storage.split("y")[0] + "px",
						top: tmp_storage.split("y")[1] + "px"
					} );
				}
			}
			
    		jQuery(jQuery(this)).mousedown( function(e) {
    			jQuery("*").onselectstart = function() { return false; }; 
				jQuery("*").unselectable = "on"; 
				jQuery("*").css('user-select', 'none').css('-o-user-select', 'none').css('-moz-user-select', 'none').css('-khtml-user-select', 'none').css('-webkit-user-select', 'none');
		
				if( prev_drag ) 
					prev_drag.css( 'z-index', z );
				draggable = jQuery(this);
				z = draggable.css( 'z-index' );
				draggable.css( { 'z-index': '999', filter: 'alpha(opacity=50)', '-khtml-opacity': '0.5', '-moz-opacity': '0.5', opacity: '0.5' });
				mouseX = e.pageX - draggable.position()['left'];
				mouseY = e.pageY - draggable.position()['top']; 
			});
	
    		jQuery(document).mouseup( function() {
    			if( draggable ) {
    				if(window.localStorage)
    					window.localStorage.setItem(draggable.attr('id'), "x" + draggable.position()['left'] + "y" + draggable.position()['top']);
    				
    				prev_drag = draggable;
    				draggable.css( { 'cursor': 'pointer', filter: 'alpha(opacity=100)', '-khtml-opacity': '1', '-moz-opacity': '1', opacity: '1' });
    				draggable = null;
    			}
    		}).mousemove( function( e ) {
    			if( draggable) {
    				draggable.css('cursor', 'move');
    				draggable.css("left", ( ( e.pageX - mouseX ) <= 1 ? 1 : ( e.pageX - mouseX ) ) );
    				draggable.css("top", ( ( e.pageY - mouseY ) <= 1 ? 1 : ( e.pageY - mouseY ) ) );
    			}
    		});
    	});
	};
} )( jQuery );
