// ==UserScript==
// @name         amazon popup image script for blog parts
// @author       kamo
// @namespace    http://www.yasui-kamo.com/
// @description  When the mouse is put on the image, a large image is displayed.
// @include      http://*
// @exclude      http://www.amazon*
// ==/UserScript==


//show image list
appendEventListener(window, "load", function(){startPopupImage(true);}, false);
//popup image only
//appendEventListener(window, "load", function(){startPopupImage(false);}, false);

//---------------------------
//set condition
//---------------------------
var g_popupImg   = true;  // When the mouse is put on the image, a large image is displayed.
var g_listImg    = true;  // When left-click while right-click in the image, all of the image is displayed.
//---------------------------

var g_asin;
var g_link;

//get asin
function getASIN(url)
{
	//get asin
	var asin = "";
	var asin_ePos;
	var asin_sPos = url.indexOf("/exec/obidos/asin/");
	if(asin_sPos != -1)
	{
		asin_ePos = url.indexOf("/", asin_sPos+18);
		asin = url.substring(asin_sPos+18, asin_ePos);
		return asin;
	}
	asin_sPos = url.indexOf("/exec/obidos/ASIN/");
	if(asin_sPos != -1)
	{
		asin_ePos = url.indexOf("/", asin_sPos+18);
		asin = url.substring(asin_sPos+18, asin_ePos);
		return asin;
	}
	asin_sPos = url.indexOf("/o/ASIN/");
	if(asin_sPos != -1)
	{
		asin_ePos = url.indexOf("/", asin_sPos+8);
		asin = url.substring(asin_sPos+8, asin_ePos);
		return asin;
	}
	asin_sPos = url.indexOf("/dp/");
	if(asin_sPos != -1)
	{
		asin_ePos = url.indexOf("/", asin_sPos+4);
		asin = url.substring(asin_sPos+4, asin_ePos);
		if(asin.length == 10 && checkAlphanumeric(asin) == true)
		{
			return asin;
		}
		else
		{
			asin_ePos = url.indexOf("?", asin_sPos+4);
			asin = url.substring(asin_sPos+4, asin_ePos);
		}
	}

	return asin;
}

//get country code
function getCountryCode(link)
{
	return "09";
}

//display image
function popupImg(asin, link, evt)
{
	//get country code
	var country = getCountryCode();

	//get image size
	var imageSize = 400;
	imageSize = document.body.clientWidth/2 - imageSize/2;

	if(g_popupImg == true)
	{
		document.getElementById('popc').style.left =  imageSize + "px";
		document.getElementById('popc').style.top = "0px";
		document.getElementById('popc').innerHTML = "<img style='border:solid 1px black' src='http://images.amazon.com/images/P/"+asin+"."+country+"._SCLZZZZZZZ_.jpg'>";
		var imgLinkObj = document.getElementById("imageLink");
		imgLinkObj.setAttribute("href", link);
	}
	g_link = link;
	g_asin = asin;
}

//clear image
function clearOriginalImg(asin, evt)
{
	//check display image
	var country = getCountryCode();
	var imgObj = new Image();
	imgObj.src = "http://images.amazon.com/images/P/"+asin+"."+country+"._SCLZZZZZZZ_.jpg";
	if(imgObj.width != 0)
	{
		var imageSize = 400;
		imageSize = document.body.clientWidth/2 - imageSize/2;
		var imgtruesize = img_true_size(imgObj);
		var img_width = imgtruesize.width;
		var img_height = imgtruesize.height;
		var img_width_s = imageSize;
		var img_width_e = img_width_s + img_width;
		var img_height_s = 0;
		var img_height_e = img_height_s + img_height;
		var mouseX = evt.clientX;
		var mouseY = evt.clientY;
		if((mouseX >= img_width_s && mouseX <= img_width_e) && (mouseY >= img_height_s && mouseY <= img_height_e))
		{
			return;
		}
	}

	//clear image
	clearImg();
}

//clear image
function clearImg()
{
	document.getElementById('popc').innerHTML = "";
}

//add pop up image event
function addEventPopUpImg()
{
	var objLink = document.getElementsByTagName("a");
	for (var i = 0; i < objLink.length; i++) {
		var nodes = objLink[i].getElementsByTagName('a');
		if(nodes.length > 0)
		{
			continue;
		}

		var link = objLink[i].href;
		if((link.indexOf("http://www.amazon.") != -1 || link.indexOf("http://amazon.") != -1) &&
		(link.indexOf("/exec/obidos/asin/") != -1 || link.indexOf("/exec/obidos/ASIN/") != -1  || link.indexOf("/o/ASIN/") != -1  || link.indexOf("/dp/") != -1))
		{
			var nameVal = objLink[i].getAttribute("name");
			var idVal = objLink[i].getAttribute("id");
			if(nameVal != "popupImg" && idVal != "imageLink")
			{
				var asin = getASIN(link);
				if(asin.length == 10 && checkAlphanumeric(asin) == true)
				{
					var childNodes = objLink[i].getElementsByTagName('img');
					if(childNodes.length <= 0)
					{
						continue;
					}

					(function(n,m){appendEventListener(childNodes[0], "mouseover", function(){popupImg(n, m, arguments[0])}, false);})(asin, link);
					(function(n){appendEventListener(childNodes[0], "mouseout", function(){clearOriginalImg(n, arguments[0])}, false);})(asin);

					if(g_listImg == true)
					{
						var curDiv = document.createElement('div');
						var curLink = document.createElement('a');
						curLink.innerHTML = "IMAGE ALL";
						curLink.setAttribute("href", "javascript:void(0)");
						curDiv.appendChild(curLink);
						objLink[i].insertBefore(curDiv, objLink[i].childNodes.item(0));
						(function(n,m){appendEventListener(curLink, "click", function(){displayImageList(n, m, arguments[0])}, false);})(asin, 2);
					}
					objLink[i].setAttribute("name", "popupImg");
				}
			}
		}
	}
	setTimeout(addEventPopUpImg, 1000);
}

//check Alphabet and numeric
function checkAlphanumeric(value)
{
	if(value.match(/[^0-9A-Z]+/) == null)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//get image size
function getImageSize(size)
{
	if(size == 1)
	{
		return "_SCMZZZZZZZ_";
	}
	else if(size == 2)
	{
		return "_SCLZZZZZZZ_";
	}
	else
	{
		return "_SCRMZZZZZZ_";
	}
}

//display image list
var g_imagecount;
function displayImageList(asin, size, evt)
{
	preventDefault(evt);

	g_imagecount = 0;

	document.getElementById('imageList').style.left = "0px";
	document.getElementById('imageList').style.top = "0px";

	//main image
	var imageSize = getImageSize(size);
	var country = getCountryCode();
	var url = "http://images.amazon.com/images/P/"+asin+"."+country+"."+imageSize+".jpg";
	var imgObj = new Image();
	(function(n, m){appendEventListener(imgObj, "load", function(){displayImage(n, m)}, false);})(url, asin);
	imgObj.src = url;

	//sub image
	var number;
	for(number = 1; number <= 30; number++)
	{
		var url = getImageURL(asin, "PT", number, size);
		var imgObj = new Image();
		(function(n, m){appendEventListener(imgObj, "load", function(){displayImage(n, m)}, false);})(url, asin);
		imgObj.src = url;
	}
	for(number = 1; number <= 30; number++)
	{
		var url = getImageURL(asin, "IN", number, size);
		var imgObj = new Image();
		(function(n, m){appendEventListener(imgObj, "load", function(){displayImage(n, m)}, false);})(url, asin);
		imgObj.src = url;
	}
}

//display image
function displayImage(url, asin)
{
	var imgObj = new Image();
	imgObj.src = url;
	if(imgObj.width <= 10)
	{
		return;
	}
	g_imagecount++;
	if(g_imagecount == 1)
	{
		document.getElementById("imageList").innerHTML = "<table id='imageListTbl' style='border-style:none;'><thead><tr><td id='closeLink' style='text-align:center;border-style:none;'></td></tr><tr><td id='sizeLink' style='text-align:center;border-style:none;'></td></tr></thead><tfoot><tr><td id='closeLink2' style='text-align:center;border-style:none;'></td></tr><tr><td id='poweredLink' style='text-align:center;border-style:none;'></td></tr></tfoot><tbody id='imageListTbody'></tbody></table>";
	}

	var tableObj = document.getElementById("poweredLink");
	replaceInnerHtml(tableObj, "<a style='font-size:0.8em;' href='http://www.yasui-kamo.com/' target='_blank'>powered by yasuikamo</a>");
	var closeHTML = "<div><a onclick=\"document.getElementById('imageList').innerHTML='';\" href=\"javascript:void(0);\">Close</a></div>";
	var tableObj = document.getElementById("closeLink");
	replaceInnerHtml(tableObj, closeHTML);
	var tableObj = document.getElementById("closeLink2");
	replaceInnerHtml(tableObj, closeHTML);
	var tableObj = document.getElementById("sizeLink");
	replaceInnerHtml(tableObj, "<div><a id='imageSize1' href=\"javascript:void(0);\">Small</a> <a id='imageSize2' href=\"javascript:void(0);\">Middle</a> <a id='imageSize3' href=\"javascript:void(0);\">Large</a><div>");
	var imageSizeObj1 = document.getElementById("imageSize1");
	var imageSizeObj2 = document.getElementById("imageSize2");
	var imageSizeObj3 = document.getElementById("imageSize3");
	(function(n, m){appendEventListener(imageSizeObj1, "click", function(){displayImageList(n, m, arguments[0])}, false);})(asin, 1);
	(function(n, m){appendEventListener(imageSizeObj2, "click", function(){displayImageList(n, m, arguments[0])}, false);})(asin, 2);
	(function(n, m){appendEventListener(imageSizeObj3, "click", function(){displayImageList(n, m, arguments[0])}, false);})(asin, 3);

	var tableObj = document.getElementById("imageListTbody");
	var insObj = document.createElement('tr');
	tableObj.appendChild(insObj) 
	var sImage = document.createElement('td');
	insObj.appendChild(sImage) 
	sImage.style.textAlign = "center";
	var htmldata = "<a href ="+url+" target='_blank'><img style=\"border-style:none;\" src="+url+"></a>";
	if(imgObj.width >= 500)
	{
		htmldata = "<a href ="+url+" target='_blank'><img style=\"border-style:none;\" width=\"500px;\" src="+url+"></a>";
	}
	replaceInnerHtml(sImage, htmldata);
}

//get number of string
function getNumberStr(number)
{
	if(number < 10)
	{
		return "0"+number;
	}
	else
	{
		return number;
	}
}

//send page
function sendPage()
{
	location.href = g_link;
}

//get image url
function getImageURL(asin, type, number, size)
{
	var country = getCountryCode();
	var imagesize = getImageSize(size);
	var numberStr = getNumberStr(number);
	var url = "http://images.amazon.com/images/P/"+asin+"."+country+"."+type+numberStr+"."+imagesize+".jpg";

	return url;
}

//add event for cross browser
function appendEventListener(element, type, func, capture)
{
	if (element.addEventListener)
	{
		element.addEventListener(type, func, capture);
	}
	else if (element.attachEvent)
	{
		element.attachEvent("on" + type, func);
	}
}

//cancel event for cross browser
function preventDefault(e)
{ 
	if (e.preventDefault)
	{
		e.preventDefault();
	}
	else
	{
		e.returnValue = false;
	}
}

//get Image size for cross browser
function img_true_size(image)
{
	var w = image.width;
	var h = image.height ;

	//Firefox, Safari, Chrome
	if ( typeof image.naturalWidth !== 'undefined' )
	{
		w = image.naturalWidth;
		h = image.naturalHeight;
	}
	//IE
	else if ( typeof image.runtimeStyle !== 'undefined' )
	{
		var run = image.runtimeStyle;
		var mem = { w: run.width, h: run.height };
		run.width  = "auto";
		run.height = "auto";
		w = image.width;
		h = image.height;
		run.width  = mem.w;
		run.height = mem.h;
	}
	//Opera
	else
	{
		var mem = { w: image.width, h: image.height };
		image.removeAttribute("width");
		image.removeAttribute("height");
		w = image.width;
		h = image.height;
		image.width  = mem.w;
		image.height = mem.h;
	}

	return {width:w, height:h};
}

//write innerHTML in table object for cross browser
function replaceInnerHtml(tgtElm, innerHTML)
{
	for (;;)
	{
		if (typeof innerHTML!='string' || typeof tgtElm!='object' || tgtElm.nodeType!=1)
		{
			break;
		}
		try
		{
			tgtElm.innerHTML = innerHTML;
		}
		catch (e)
		{
			var chld;
			while (chld=tgtElm.firstChild) tgtElm.removeChild(chld);
			if (innerHTML.match(/^\s*$/) ) break;

			var tagName=tgtElm.tagName.toLowerCase(), tmp, html='<'+tagName+'>'+innerHTML+'</'+tagName+'>';
			switch (tagName)
			{
				case 'thead' :
				case 'tbody' :
				case 'tfoot' :
					tmp=document.createElement('table');
					replaceInnerHtml(tmp, html);
					break;
				case 'tr' :
					tmp=document.createElement('table');
					replaceInnerHtml(tmp, '<tbody>'+html+'</tbody>');
					tmp=tmp.firstChild;
					break;
				default :
					tmp=document.createElement('div');
					tmp.innerHTML=html;
					break;
			}
			var tmpElm=tmp.firstChild;
			while (chld=tmpElm.firstChild) tgtElm.appendChild(chld);
		}
		break;
	}
	return tgtElm;
}

//main
function startPopupImage(listimg)
{
	if(!document.body)
	{
		return;
	}
	
	if (typeof listimg !== 'undefined')
	{
		g_listImg = listimg;
	}
	else
	{
		g_listImg = true;
	}

	//create image area
	var imageArea = document.createElement('div');
	imageArea.id = "popc";
	imageArea.style.position = "fixed";
	imageArea.style.zIndex = "2002";
	imageArea.style.overflow = "auto";
	imageArea.style.background = "white";
	imageArea.style.opacity = "1.0";

	var curLink = document.createElement('a');
	curLink.setAttribute("id", "imageLink");
	curLink.setAttribute("target", "_blank");
	curLink.appendChild(imageArea);

	var imageListArea = document.createElement('div');
	imageListArea.id = "imageList";
	imageListArea.style.position = "fixed";
	imageListArea.style.zIndex = "2001";
	imageListArea.style.overflow = "auto";
	imageListArea.style.background = "white";
	var height;
	if (document.all)
	{
		height = document.documentElement.clientHeight;
	}
	else
	{
		height = window.innerHeight;
	}
	imageListArea.style.height = height + "px";

	var objBody = document.getElementsByTagName("body").item(0);
	objBody.appendChild(curLink);
	objBody.appendChild(imageListArea);

	var imageObj = document.getElementById('popc');
	if(g_popupImg == true)
	{
		appendEventListener(imageObj, "mouseout", clearImg, false);
		if (document.all)
		{
			appendEventListener(imageObj, "click", sendPage, false);
		}
	}

	//add event
	addEventPopUpImg();
}


