// ==UserScript==
// @name		WPPreviewDraft
// @version		0.3
// @namespace	http://mrspeaker.webeisteddfod.com/greasemonkey
// @author		Mr Speaker
// @description	Preview draft pages in WP
// @include		http://yoursite.com/wp-admin/edit.php*
// @include		http://yoursite.com/wp-admin/post.php*
// ==/UserScript==

(
function() 
{
	var timer = null;
	var posx = 0;
	var posy = 0;
	
	var DIV_WIDTH = 330;
	var DIV_HEIGHT = 160;
	
	var CLOSE_BUTTON_HTML = "<input type='button' value='close' onclick='this.parentNode.parentNode.removeChild(this.parentNode);'><br/>";
	
	links =  document.getElementsByTagName( "a" );
	
	for( var i = 0; i < links.length; i++ )
	{
		if( links[ i ].title == "Edit this draft" )
		{
			links[ i ].addEventListener( "mouseover", setTimer, false );
			links[ i ].addEventListener( "mouseout", clearTimer, false );
		}
	}
	
	function setTimer( e )
	{
		posx = e.clientX; //Set current mouse positions
		if ( posx + DIV_WIDTH > window.document.width ) posx = window.document.width - DIV_WIDTH - 20;
		//posx = posx % 
		//http://www.quirksmode.org/js/doctypes.html
		posy = e.clientY + 10;
		timer = window.setTimeout( function(){ grabit(e) }, 1000 );
	}
	
	function clearTimer( e )
	{
		clearTimeout( timer );
	}
	
	function grabit( e )
	{
		addOverlay()
		moveOverlay()
		getPostHtml( e.target );//, e.clientX, e.clientY );
	}
	
	function moveOverlay()
	{
		var overlay = document.getElementById( "PreviewDraftWP" );
		overlay.style.left = posx + "px";
		overlay.style.top = posy + "px";
	}
	
	function addOverlay()
	{
		if( !document.getElementById("PreviewDraftWP" ) )
		{
			var overlay = document.createElement( "div" );
			overlay.setAttribute( "id", "PreviewDraftWP" ) 
			overlay.style.width = DIV_WIDTH + "px";
			overlay.style.height = DIV_HEIGHT + "px";
			overlay.style.position = "absolute";
			overlay.style.padding = "4px";
			overlay.style.border = "1px solid #ddd";
			overlay.style.backgroundColor = "#eee";
			overlay.style.overflow = "auto";
		
			document.body.appendChild( overlay );
		}
		
		document.getElementById( "PreviewDraftWP" ).innerHTML = CLOSE_BUTTON_HTML + "<strong>Loading...</strong>";

	}
	
	function getPostHtml( p_address )
	{
		GM_xmlhttpRequest(
		{
			method:"GET",
			url: "" + p_address + "",
			headers:
			{
				"User-Agent":"monkeyagent",
				"Accept":"text/monkey,text/xml",
			},
			onload:function( details )
			{
				ParseResponse( details.responseText );
			}
		});
	}
	
	function ParseResponse( p_response )
	{
		var START_OF_AREA = "id=\"content\">";
		var END_OF_AREA = "</textarea>";
		
		var startIndex = p_response.indexOf( START_OF_AREA ) + START_OF_AREA.length;
		var endIndex = p_response.indexOf( END_OF_AREA, startIndex );
		
		if ( startIndex > 0 && endIndex > 0 )
		{
			moveOverlay();
			document.getElementById("PreviewDraftWP").innerHTML = CLOSE_BUTTON_HTML + p_response.substring( startIndex, endIndex ).replace(/\n/g, "<br/>" );
		}
	}
}
)();
