/* ------------------------------ */
/**
 * Resizes a large image
 * 
 * @param	{element}	elem	The image to resize
*/
_global.prototype.global.resizeImage = function( elem )
{
	if( elem.tagName != 'IMG' ){ return; }
	if( elem.readAttribute('handled') ){ Debug.write("Handled..."); return; }
	
	// Check we have a cached post size
	if( !ipb.global.post_width )
	{
		var post	= $( elem ).up('.post');

		if( !Object.isUndefined( post ) )
		{
			var extra = parseInt( post.getStyle('padding-left') ) + parseInt( post.getStyle('padding-right') );
			ipb.global.post_width = $( post ).getWidth() - ( extra * 2 );
		}
	}
	
	var quotewidth	= 0;
	var quote	= $( elem ).up('.quote');
	
	if( !Object.isUndefined( quote ) )
	{
		var extra = parseInt( quote.getStyle('padding-left') ) + parseInt( quote.getStyle('padding-right') );
		quotewidth = $( quote ).getWidth() - ( extra * 2 );
	}
	
	// Uses post width if it can work it out, otherwise screen width
	var widthCompare = ( ipb.vars['image_resize_force'] ) ? ipb.vars['image_resize_force'] : ( quotewidth ? quotewidth : ( ipb.global.post_width ? ipb.global.post_width : ipb.global.max_w ) );
	var dims = elem.getDimensions();

	if( dims.width > widthCompare )
	{
		//elem.width = ipb.global.max_w;
		var percent = Math.ceil( ( widthCompare / dims.width) * 100 );

		if( percent < 100 )
		{
			elem.height = dims.height * ( percent / 100 );
			elem.width = dims.width * ( percent / 100 );
		}
		
		var temp = ipb.templates['resized_img'];
		
		var wrap = $( elem ).wrap('a').addClassName('resized_img').writeAttribute('rel', 'lightbox').writeAttribute('href', $(elem).readAttribute('src'));
		$( elem ).insert({ before: temp.evaluate({ percent: percent, width: dims.width, height: dims.height }) });
		
		$( elem ).addClassName('resized').setStyle('cursor: pointer;');
		$( elem ).writeAttribute( 'origWidth', dims.width ).writeAttribute( 'origHeight', dims.height ).writeAttribute( 'shrunk', 1 );
		$( elem ).writeAttribute( 'newWidth', elem.width ).writeAttribute( 'newHeight', elem.height ).writeAttribute( 'handled', 1 );
		
		// SKINNOTE: Add event handler
		//$( elem ).observe('click', ipb.global.enlargeImage);
	}	
};

document.observe('dom:loaded', function () {
    $$('.bbc_spoiler_show').each(function (btn) {
	    btn.observe('click', function (e) {
	    	setTimeout(function () {
				$$('img.bbc_img').each(function(elem) {
				    var force = ipb.vars['image_resize_force'];
				    if( !ipb.global.screen_w ) {
				        ipb.global.initImageResize();
				    }

				    if (elem.parentNode.className.match(/bbc_spoiler_content/)) {
				        ipb.vars['image_resize_force'] = Math.ceil( elem.parentNode.offsetWidth * .98 );
				    }

				    ipb.global.resizeImage( elem );

				    ipb.vars['image_resize_force'] = force;
				});
			}, 100);
		});
	});
});
