// ==UserScript==
// @name           Drag Everything
// @namespace      Webnick.UI
// @description    Lets you drag all elements on a page. This is just a fun little work in progress. Released under the GPL license, http://www.gnu.org/copyleft/gpl.html
// @include        *
// ==/UserScript==

(function() {
	var draggableOutline = "3px lime solid";
	
	// Load jQuery APIs
	var o = document.createElement('script');
	o.src = 'http://jqueryjs.googlecode.com/files/jquery-1.3.min.js';
	o.type = 'text/javascript';
	document.body.appendChild(o);
	
	// Load jQuery UI APIs
	var a = document.createElement('script');
	a.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.3/jquery-ui.min.js';
	a.type = 'text/javascript';
	document.body.appendChild(a);
	
	// Create an interval beacse we're not sure when the dynamically added jQuery scripts are goo to go.
	var intervalID = setInterval(function() {
		var i = this;
		
		if (typeof(unsafeWindow) != 'undefined' && typeof(unsafeWindow.jQuery) != 'undefined') {
			$ = unsafeWindow.jQuery;
			var lastHovered;
			
			function makeAllDraggable() {
				$("*",document.body).each(
					function() {
						$(this).draggable();
						$(this).hover(
							function(e) {
								// We check if their was a last hovered element so that we don't get every containing element of the current element
								// keeping their outline.
								if(lastHovered) {
									lastHovered.style.outline = "none";
								}
								
								this.style.outline = draggableOutline;
								
								// Prevent hovering from bubbling so everything doesn't get outlined.
								e.stopPropagation();
								e.cancelBubble = true;
								lastHovered = this;
								this.style.cursor = "move";
							}
							,function(e) {
								// Clear the outline
								this.style.outline = "none";
								this.style.cursor = "";
								e.stopPropagation();
								e.cancelBubble = true;
							}
						)
					}
				)
			}

			// Make our button to allow things to become draggable. As well, the button itself will become draggable, so you can move it out of the way if you want.
			var myButton = $("<input type=\"button\" value=\"Make Draggable\" />");
			myButton.click(makeAllDraggable);

			var myDiv = $("<div style=\"position: fixed;top:0px;left: 0px;padding: 7px;text-align: center;background-color: #999;border: 1px solid #000;color: #000\"></div>");

			myButton.appendTo(myDiv);
			myDiv.appendTo(document.body);
			clearInterval(intervalID);
		}
	}, 40);

})();