// "Betsy - a Better Etsy" user script
// version 0.4
// 2006-03-22
// Copyright (c) 2006, Matt Sephton <matt@ewtoo.org>
//
// --------------------------------------------------------------------
//
// This is a user script that requires Greasemonkey (Firefox on Mac, PC 
// or Linux), Creammonkey (Safari on Mac) or Turnabout Advanced (IE on
// on PC). After installing one of the above programs, restart your 
// browser and come back here.
// 
// In Firefox or Safari, clicking on the ECC script of your choice will 
// prompt you to "Install User Script", then click "Install" to do so.
// In Internet Explorer, right click on the ECC script of your choice 
// and choose "Install Script".
// 
// To uninstall, follow the instructions given in Greasemonkey, 
// Creammonkey or Turnabout Advanced.
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          Betsy - a Better Etsy
// @namespace     http://www.gingerbeardman.com/betsy/
// @description   Allow loading of Etsy item images without reloading the page
// @include       http://www.etsy.com/view_item*
// ==/UserScript==

function min(a, b) {
	if (a < b) return a;
	return b;
}

//grab body for replacing
eilBody = document.getElementsByTagName("body").item(0).innerHTML;

//grab thumbs for reference
thumbImages = eilBody.match(/get_jpg_thumb_image\.php\?image_id=\d*/g);

if (thumbImages.length > 2) {
	//grab links to modify
	oldLinks = eilBody.match(/\/view_item\.php\?listing_id=\d*.*?pic_id=\d/g);

	newLinks = new Array();
	anotherBody = eilBody;

	for (i=0; i < min(4,oldLinks.length); i++) {
		oldLinks[i] = oldLinks[i].replace(/(\?|\.)/g, "\\$1");	//regexp escape old links
		thumbImages[i] = thumbImages[i].replace(/get_jpg_thumb_image/g, "get_jpg_detail_image");	//thumb -> main
		newLinks[i] = "#\" onclick=\"javascript:document.images[29].src='"+ thumbImages[i] +"';";	//create new javascript links
		anotherBody = anotherBody.replace(new RegExp(oldLinks[i], "gi"), newLinks[i]);	//replace old links with new links
	}

	//replace page
	document.getElementsByTagName("body").item(0).innerHTML = anotherBody;
}