//Image width
//var maxW = Math.round(screen.width - (screen.width / 1.5));
var maxW = 200;
var hidePostImg = false;
var hideSigImg = false;

function imgFit (img, maxW)
{
	if (typeof(img.naturalHeight) == undefined) {
		img.naturalHeight = img.height;
		img.naturalWidth  = img.width;
	}

	if (img.width > maxW) {
		img.height = Math.round((maxW/img.width)*img.height);
		img.width  = maxW;
		//img.title  = 'Click image to view full size';
		img.style.cursor = 'pointer';
		return false;
	}
	else if (img.width == maxW && img.width < img.naturalWidth) {
		img.height = img.naturalHeight;
		img.width  = img.naturalWidth;
		//img.title  = 'Click to fit in the browser window';
		return false;
	}
	else {
		return true;
	}
}

function initPost(context)
{
	initPostImages(context);
	initSpoilers(context);
}
function initPostImages(context)
{
	var $in_spoilers = $('div.sp-body var.postImg', context);
	var banned_image_hosts = /imagebanana|hidebehind|img2\.pict\.com/i;//banned image hosts

	$('var.postImg', context).not($in_spoilers).each(function(){
		var $v = $(this);
		var src = $v.attr('title');
		var img_align = $v.attr('align')!=undefined ? ' align="'+ $v.attr('align') +'"' : '';
		var $img = $('<img src="'+ src +'"'+ img_align + ' class="'+ $v.attr('className') +'" alt="" />');

		var is_signature = $v.parents().hasClass('signature') ? true : false;

		if(!is_signature) {
			if (hidePostImg){ return $(this).replaceWith(''); }

			if (src.match(banned_image_hosts)) {
				return $(this).replaceWith('<a href="#" title="Sorry, images from this server banned"><img  src="./tracker/addons/images/spoiler/tr_oops.gif" alt="Banned!" /></a>');//Link to rules
			}
			else
			{
				$img = fixPostImage($img);
			}

			//Original
			//$img.bind('click', function(){ imgFit(this, maxW); });
			//Default
			//$img.bind('click', function(){ return !window.open(src); });
			//Fancybox
				$img.bind('click', function(){
					$(".postImg").fancybox({
						'modal': false,
						'titleShow': true,
						'titlePosition': 'inside',
						'autoScale': true,
						'autoDimensions': true,
						'type': 'image',
						'href': src,
						'scrolling': 'auto',
						'hideOnContentClick': true,
						'titleFormat': function(title, currentArray, currentIndex, currentOpts)
						{
							return '<div style="width:100%;white-space:pre-wrap;background-color:#FFFFFF;overflow:auto"><a href="' + htmlspecialchars(src) + '" target="_blank">' +  htmlspecialchars(src) + '</a></div>';
						}
					});
				 });

			$('#preload').append($img);
			var loading_icon = '<a href="'+ src +'" target="_blank"><img src="./tracker/addons/images/spoiler/pic_loading.gif" alt="" /></a>';
			$v.html(loading_icon);

			if ($.browser.msie || $.browser.opera) {
				$img.one('load', function(){ imgFit(this, maxW); });
				$v.empty().append($img);
				$v.after('<wbr>');
			}
			else
			{
				$img.one('load', function(){
					imgFit(this, maxW);
					$v.empty().append(this);
				});
			}
			var is_href = $v.parent().attr('href');

			if(is_href)
			{
				$img.unbind('click');
			}
		}
		else
		{
			if (hideSigImg){ return $(this).replaceWith(''); }
			$v.empty().append($img);
		}
	});
}
function initSpoilers(context)
{
	$('div.sp-body', context).each(function(){
		var $sp_body = $(this);
		var name = this.title || 'Скрытый текст';
		this.title = '';
		$('<div class="sp-head folded clickable">'+ name +'</div>').insertBefore($sp_body).click(function(e){
			if (!$sp_body.hasClass('inited')) {
				initPostImages($sp_body);
				$sp_body.prepend('<div class="clear"></div>').append('<div class="clear"></div>').addClass('inited');
				$sp_body.after('<div class="sp-head unfolded clickable" onclick="spoilerHide($(this));">Закрыть</div>').addClass('inited');
			}
			else
			{
				$sp_body.next().slideToggle('fast');
			}
			if (e.shiftKey) {
				e.stopPropagation();
				e.shiftKey = false;
				var fold = $(this).hasClass('unfolded');
				$('div.sp-head', $($sp_body.parents('td')[0])).filter( function(){ return $(this).hasClass('unfolded') ? fold : !fold } ).click();
			}
			else {
				$(this).toggleClass('unfolded');
				$sp_body.slideToggle('fast');
			}
		});
	});
}
function fixPostImage ($img)
{
	var src = $img[0].src;
	// keep4u
	if (src.match(/keep4u/i)) {
		var new_src = src.replace(/http:\/\/keep4u.ru\/imgs\/\w\/(.*)\/(.*)\.(.*)/, "http://keep4u.ru/imgs/s/$1/$2.$3");
		//var new_url = src.replace(/http:\/\/keep4u.ru\/imgs\/\w\/(.*)\/(.*)\.(.*)/, "http://keep4u.ru/full/$1/$2/$3");
		$img.attr('src', new_src).addClass('clickable');
	}
	return $img;
}
//From rustorka.com
function spoilerHide(ctx)
{
	if($(document).scrollTop() > ctx.prev().offset().top)
	{
		$(document).scrollTop(ctx.prev().offset().top - 200);
	}
	ctx.slideToggle('fast');
	ctx.prev().slideToggle('fast');
	ctx.prev().prev().toggleClass('unfolded');
}
function htmlspecialchars(html)
{
      html = html.replace(/&/g, "&amp;");
      html = html.replace(/</g, "&lt;");
      html = html.replace(/>/g, "&gt;");
      html = html.replace(/"/g, "&quot;");

      return html;
}

$(document).ready(function(){
	$(this).each(function(){ initPost( $(this) ) });

});
