/**
 * RunAway
 *
 * @author       nori (http://twitter.com/5509)
 * @copyright    (c) 5509
 * @license      The MIT License
 * @link         http://5509.me/log/bookmarklet-runaway
 *
 * @Base-script-written-by
 *               hisasann (http://hisasann.com/housetect/)
 *               http://hisasann.com/housetect/2009/04/jqueryrunawayfrommouse_part2.html
 *
 * $Date: 2010-07-01
 */

 (function() {
 
 	var mouseX, mouseY, d = document, dE = d.documentElement,
 		rate = 60,
 		instance = 3000,
 		anchors = d.getElementsByTagName('a');
 		
 	addEvent(d, 'mousemove', function(e) {
 		mouseY = e.pageY ? e.pageY : e.clientY + dE.scrollTop;
 		mouseX = e.pageX ? e.pageX : e.clientX + dE.scrollLeft;
 	});
 	
 	mover(anchors, instance, rate);
 	
	function mover(selector, instance, rate) {
		var firstPointX = [],
			firstPointY = [];
			
	 	for ( var i=0; i<anchors.length; i++ ) {
			firstPointX[i] = anchors[i].offsetLeft;
			firstPointY[i] = anchors[i].offsetTop;
			
			var span = d.createElement('span');
			setStyles(span, {
				display: 'inline-block',
				width: anchors[i].offsetWidth+'px'
			});
			insertAfter(anchors[i].parentNode, span, anchors[i]);
		}					

		(function(){
			for ( var i=0; i<anchors.length; i++ ) {
				var elem = anchors[i],
					offsetY = elem.offsetTop,
					offsetX = elem.offsetLeft,
					theta = Math.atan2(offsetY - mouseY, offsetX - mouseX),
					d = instance / Math.sqrt(Math.pow(mouseX - offsetX, 2) + Math.pow(mouseY - offsetY, 2)),
					left = parseInt(offsetX) + d * Math.cos(theta) + (firstPointX[i] - offsetX) * 0.1,
					top = parseInt(offsetY) + d * Math.sin(theta) + (firstPointY[i] - offsetY) * 0.1;
					
				if ( !isNaN(top) && !isNaN(left) ) {
					setStyles(elem, {
						left: left+'px',
						top: top+'px'
					});
				} else {
					setStyles(elem, {
						position: 'absolute'
					});
				}
			}
			
			setTimeout(arguments.callee, rate);
		})();
	}
 		
 	function addEvent(elm, listener, fn) {
		try {
			elm.addEventListener(listener, fn, false);
		} catch (e) {
			elm.attachEvent('on' + listener, fn);
		}
	}
	
	function setStyles(elm, hash) {
		for ( var c in hash ) {
			elm.style[c] = hash[c];
		}
	}

	function insertAfter(parent, node, referenceNode) {
		parent.insertBefore(node, referenceNode.nextSibling);
	}
 
 })();
