jQuery.fn.resizeImg = function(maxh, maxw){
    var ratio = maxh / maxw;
    if (this.context.height / this.context.width > ratio) {
        if (this.context.height > maxh) {
            this.context.width = Math.round(this.context.width * (maxh / this.context.height));
            this.context.height = maxh;
        }
    }
    else {
        if (this.context.width >= maxh) {
            this.context.height = Math.round(this.context.height * (maxw / this.context.width));
            this.context.width = maxw;
        }
    }
}

jQuery.fn.varToImg = function(resize){
    var element = $(this);
    var attrs = $(this).attr("title").split("|");
    var image = new Image();

    if (resize) {
        $(image).load(function(){
            $(this).hide();
            if (this.width > maximgsize) {
                $(this).resizeImg(maximgsize, maximgsize);
                $(this).css("cursor", "hand").css("cursor", "pointer");
                $(this).click(function(){
                    window.open(this.src);
                });
            }
			$(this).css("display", "inline");
            $(element).after(this).remove();
            $(this).fadeIn(500);
        });
    }
    else {
        $(image).load(function(){
            $(this).hide();
            $(element).after(this).remove();
            $(this).show();
        });
    }

    $(image).error(function(){
       throw "Error...";
    })

    if (attrs.length == 1) {
        $(image).attr("src", attrs);
    }
    else {
        $(image).attr({
            src: attrs[0],
            align: attrs[1]
        });
    }
}

//var maximgsize = 500;
var maximgsize = screen.width-700;

$(document).ready(function(){
    if ($("#detailposterleft").length)
	    maximgsize = screen.width-(600+$("#detailposterleft").attr("width"));
	else
		if ($("#detailposterright").length)
			maximgsize = screen.width-(600+$("#detailposterright").attr("width"));

    $("var").each(function(){
        if (!$(this).parent().hasClass("spoilermain"))
            $(this).varToImg(true);
    });

    $(".spoilertop").click(function(){
        $(this).next().next().toggle();
        $(this).next().slideToggle(200);
        if ($(this).next().find("var img").length === 0) {
            var vars = $(this).next().children("var");
            if (vars.length > 0)
                $(vars).each(function(index){
                    $(this).varToImg(true);
                });
        }
    });
    $(".spoilerbottom").click(function(){
        if($(document).scrollTop() > $(this).prev().prev().offset().top)
            $(document).scrollTop($(this).prev().prev().offset().top-100);
        $(this).prev().prev().click();
    });
});
