
$(document).ready(scaleImages);
$(window).resize(scaleImages);


function scaleImages()
{
	var ww=(window.innerWidth						? window.innerWidth :
		   (document.body.clientWidth				? document.body.clientWidth :
		   (document.documentElement.clientWidth	? document.documentElement.clientWidth :
		   -1))),
		wh=(window.innerHeight						? window.innerHeight :
		   (document.body.clientHeight				? document.body.clientHeight :
		   (document.documentElement.clientHeight	? document.documentElement.clientHeight :
		   -1)));

	if (ww>0 && wh>0)
	{
		var msg='';

		$("*:not(#map) > img:not(.noscale)")		// scale down
		.each(function()
			  {
				var pw=$(this).parent().width() ? Math.min(ww,$(this).parent().width()) : ww,
					ph=wh,
					iw=$(this).width(),
					ih=$(this).height();

				if (pw>400 && ph>300 && iw>400 && ih>300)
				{
					var	s=Math.min(pw/iw,ph/ih)*0.99,
						nw=Math.round(iw*s),
						nh=Math.round(ih*s);

					if (s<0.99 && nw>200 && nh>150)
					{
						msg+="image scaled down from "
							+iw+"x"+ih
							+" in "+pw+"x"+ph
							+" to "+Math.round(s*100)+"% = "
							+nw+"x"+nh
							+" : "
							+$(this).attr("src")
							+"<br>";

						$(this).css({width:nw+"px",height:nh+"px"});
						$(this).parent().css({overflow:"hidden"});
						$(this).parent().parent().css({overflow:"hidden"});
						$(this).wrap('<a href="'+$(this).attr("src")+'" class="imgLink"></a>');
					}
				}
			  });

		/*
		div.postbody
			center
				div.attachedImg
					a
						img
		*/

		$(".attachedImg img:not(.noscale)")		// images attached to forum messages
		.each(function()
			  {
				var p=$(this).parent().parent().parent().parent(),
					pw=(p && p.width()) ? Math.min(ww,p.width()) : ww,
					ph=wh,
					iw=$(this).width(),
					ih=$(this).height();

				if (pw>400 && ph>300 && iw>200 && ih>150)
				{
					var	s=Math.min(Math.min(pw/iw,ph/ih)*0.99,2),	// scaling<=2
						nw=Math.round(iw*s),
						nh=Math.round(ih*s);

					if ((s<0.99 || s>1.1) && nw>200 && nh>150)		// scale up or down
					{
						msg+="attached image scaled from "
							+iw+"x"+ih
							+" in "+pw+"x"+ph
							+" to "+Math.round(s*100)+"% = "
							+nw+"x"+nh
							+" : "
							+$(this).attr("src")
							+"<br>";

						$(this).css({width:nw+"px",height:nh+"px"});
						p.css({overflow:"hidden"});
					}
				}
			  });


		if (msg!='')
			$("body").append(
				 '<fieldset id="client-side" style="font-size:x-small;margin:1ex;padding:.25ex 1ex .75ex 1ex">'
					+'<legend style="margin:0;padding:0 1ex 0 1ex">'
						+'Client-side post-processing'
					+'</legend>'
					+msg
				+'</fieldset>');

		$("a.imgLink").lightBox({overlayOpacity:0.5,nav:false,imageBtnClose:false});
	}
}

