// ==UserScript==
// @name           Image Grabber
// @namespace      http://arantius.com/misc/greasemonkey/
// @description    Grab all the images in all the pages linked in the selection.
// @include        *
// ==/UserScript==

var gLinks=[], gAtLink=-1, gImages=[];
var gWin=null;
var gIndicator=null;

function setUpGrab() {
	var el=window.getSelection().getRangeAt(0).commonAncestorContainer;
	if (!el) el=document.body;
	if (3==el.nodeType) return;

	var iframe=document.createElement('iframe');
	iframe.src='about:blank';
	iframe.style.position='absolute';
	iframe.style.top='-500px';
	iframe.style.left='0px';
	document.body.appendChild(iframe);
	gWin=window.frames[ window.frames.length-1 ];

	gIndicator=document.createElement('div');
	gIndicator.style.backgroundColor='blue';
	gIndicator.style.position='fixed';
	gIndicator.style.top='50%';
	gIndicator.style.left='50%';
	gIndicator.style.height='20px';
	gIndicator.style.width='200px';
	gIndicator.style.marginLeft='-100px';
	gIndicator.style.marginTop='-10px';
	var d=document.createElement('div');
	d.style.height='20px';
	d.style.width='1px';
	d.style.backgroundColor='lime';
	gIndicator.appendChild(d);
	document.body.appendChild(gIndicator);

	gLinks=el.getElementsByTagName('a');
	getNextLink();
}

function grabImage(response) {
	gWin.document.body.innerHTML=response.responseText;
	
	var keepImg=null, keepSize=-1, s;
	for (var i=0, img=null; img=gWin.document.images[i]; i++) {
		s=img.offsetWidth*img.offsetHeight;

		if (s>keepSize) {
			keepSize=s;
			keepImg=img;
		}
	}
	if (keepImg) {
		var src=keepImg.src;
		if ('http'!=src.substr(0, 4)) {
			if ('/'==src.charAt(0)) {
				var host=String(gLinks[gAtLink]);
				host=host.replace(/(.*\/\/[^/]+).*/, '$1');
				src=host+src;
			} else {
				var path=String(gLinks[gAtLink]);
				if ('/'!=path.charAt(path.length-1)) {
					path=path.replace(/(.*)\/.*/, '$1/');
					src=path+src;
				}
			}
		}
		gImages.push(src);
	}

	getNextLink();
}

function getNextLink() {
	gAtLink++;

	if (!gLinks[gAtLink]) {
		printImages();
		return;
	}

	if (gAtLink>0) {
		var perc=(gLinks.length-gAtLink)/gLinks.length;
		gIndicator.firstChild.style.width=( 200 - 199*perc )+'px';
	}

	GM_xmlhttpRequest({
		method:'GET',
		url:gLinks[gAtLink].href,
		onload:grabImage
	});
}

function printImages() {
	if (0==gImages.length) return;

	var s='<ul>';
	for (var i=0, img=null; img=gImages[i]; i++) {
		s+='<li><a href="'+img+'">'+img+'</a></li>';
	}
	s+='</ul>';

	document.write(s);
	document.close();
}

GM_registerMenuCommand('Grab images!', setUpGrab);
