/*
 * Copyright (c) 2007-2008 Stardock Systems, Inc.
 * Author: Andrew Powell, 09.09.08
 * Version 1.0
*/

if(!Sd.Post) Sd.Post = Class.create();
Sd.Post.Images = Class.create();
Sd.Post.Images.max = {w: 600, h: 440};
/*
 *contentId: the Base Id of the control which contains the post/reply content.
 *type: tag type/name. 
*/
Sd.Post.Images.init = function(contentId, type)
{
	var contents = $col(contentId, type);
	if(!contents || contents.length == 0) return;
	
	for(var i=0;i<contents.length;i++)
	{
		var images = contents[i]._tags('img');
		for(var j=0;j<images.length;j++)
		{
			var img = images[j];
			if(img.width && img.width > 0)
				Sd.Post.Images.resize(img);
			else
				img.onload = function(){ Sd.Post.Images.resize(this); };
		}
	}
};

Sd.Post.Images.resize = function(img)
{
	var w = Sd.Post.Images.max.w;
	var h = Sd.Post.Images.max.h;
	var nw = img.width,nh = img.height;
	
	if(w > 0 && nw > w)
	{
		nh = (w / nw) * nh;
		nw = w;
	}
	
	if(h > 0 && nh > h)
	{
		nw = (h / nh) * nw;
		nh = h;
	}
	
	if(nw == img.width && nh == img.height) return;
	
	var percent = parseInt((nw / img.width) * 100);

	img.o = {w: img.width, h: img.height, p: percent};
	img.width = nw;
	img.height = nh;
	
	Sd.Post.Images.fancy(img);
	
};

Sd.Post.Images.fancy = function(img)
{
	var div = $new('div', null, 'resized');
	var msg = $new('div', null, 'message');
	var inner = $new('span');
	var orig = $new('div', null, 'orig');
	var meats = $new('div', null, 'meats');
	var f = function(){ window.open(this.src, '_blank'); };

	img.onclick = f;
	inner.onclick = f;
	inner.src = img.src;
	inner.innerHTML = 'Reduced ' + img.o.p + '%';
	orig.innerHTML = 'Original ' + img.o.w + ' x ' + img.o.h;

	msg.appendChild(inner);
	
	div.style.width = img.width + 'px';
	div.appendChild(msg);
	div.appendChild(meats);
	div.appendChild(orig);
	img._parent().insertBefore(div, img);

	meats.appendChild(img);

};
