var imageGallery = new function() {

    var images, imageGalleryCoverDiv, imageGalleryPasseDiv, imageGalleryImg, imageGalleryImgDiv;
    var cachedImages = {};
    var isLoaded = false;

    this.init = function() {
        images = $('a.imageGallery img');
        images.css({cursor: "pointer"}).click(onclick);

        imageGalleryCoverDiv = $("<div id='imageGalleryCoverDiv'><div>");
        imageGalleryCoverDiv.hide();
        imageGalleryCoverDiv.css({opacity: 0.6});
        imageGalleryCoverDiv.click(imageGallery.hideImage);
        $("body").append(imageGalleryCoverDiv);

        imageGalleryPasseDiv = $("<div id='imageGalleryPasseDiv'><table><tr valign='top'>" +
                                 "<td align='left'><span id='imageGalleryNavigation'>&nbsp;</span></td>" +
                                 "<td align='center'><span id='imageGalleryName'>&nbsp;</span></td>" +
                                 "<td align='right'><a href='#' id='imageGalleryClose' onclick='imageGallery.hideImage(); return false;'>закрыть&nbsp;</a></td>" +
                                 "</tr><tr>" +
                                 "<td colspan='3' align='center'><div id='imageGalleryImgDiv'><img id='imageGalleryImg' onload='imageGallery.finalLoad()' title='Закрыть' onclick='imageGallery.hideImage(); return false;'></span></td>" +
                                 "</tr><tr>" +
                                 "<td colspan='3' align='center'><span id='imageGalleryText'>&nbsp;</span></td>" +
                                 "</tr></table></div>");
        imageGalleryPasseDiv.hide();
        $("body").append(imageGalleryPasseDiv);

        imageGalleryImg = $('#imageGalleryImg');
        imageGalleryImg.fadeOut(1);

        imageGalleryImgDiv = $('#imageGalleryImgDiv');

        $(document).keyup(function (event) {
            if (isLoaded && imageGalleryPasseDiv.is(":visible")) {
                switch (event.keyCode) {
                    case 27: // escape
                        imageGallery.hideImage();
                        break;
                    case 37: // left
                        imageGallery.navigate(imageGalleryImg.pos - 1);
                        break;
                    case 39: // right
                        imageGallery.navigate(imageGalleryImg.pos + 1);
                        break;
                }
            }
        });
    };

    this.hideImage = function(isTemprary, img, url) {
        isLoaded = false;
        isTemprary = (isTemprary == true);
        $('#imageGalleryImg').fadeOut(1, function() {
            if (!isTemprary) {
                imageGalleryPasseDiv.hide();
                imageGalleryCoverDiv.hide();
            } else {
                continueShowImage(img, url);
            }
        });
    };

    this.showImage = function(img, url) {
        this.hideImage(true, img, url);
    };

    function continueShowImage(img, url) {
        var pos = images.index(img);
        var maxHeight = 0;
        var maxWidth = 0;
        $(img).parents().each(function (i, val) {
            var offset = $(val).offset();
            var w = $(val).width();// + offset.left;
            var h = $(val).height() + offset.top;
            maxWidth = maxWidth > w ? maxWidth : w;
            maxHeight = maxHeight > h ? maxHeight : h;
        });

        maxWidth = window.innerWidth || $(window).width();
        imageGalleryCoverDiv.width(maxWidth);
        imageGalleryCoverDiv.height(maxHeight);
        imageGalleryCoverDiv.show();

        $('#imageGalleryName').parent("td").css("width", img.width+"px");
        $('#imageGalleryText').parent("td").css("width", img.width+"px");
        centerPasse();
        imageGalleryPasseDiv.show();

        if ($(img).parents("a").attr("url")) url = $(img).parents("a").attr("url");
        else if (!url) url = img.src.replace('viewThumbnail.jsp', 'viewImage.jsp');
        
        if (!cachedImages[pos]) {
            cachedImages[pos] = new Image();
            cachedImages[pos].pos = pos;
            cachedImages[pos].onload = onload;
            cachedImages[pos].src = url;
        } else {
            onload(cachedImages[pos]);
        }

        var navigator = $('<span>&nbsp;' + (pos + 1) + ' / ' + images.length + '&nbsp;<a>&lt;&lt;</a>&nbsp;<a>&gt;&gt;</a></span>');
        $('#imageGalleryNavigation').html(navigator.html());
        var a1 = $('#imageGalleryNavigation').children("a:nth-child(1)");
        if (pos > 0) {
          a1.attr({href: "#", onclick: 'imageGallery.navigate(' + (pos - 1) + '); return false;'});
          a1.click(function() { imageGallery.navigate(pos - 1); return false;})
        }
        var a2 = $('#imageGalleryNavigation').children("a:nth-child(2)");
        if (pos < images.length - 1) {
          a2.attr({href: "#", onclick: 'imageGallery.navigate(' + (pos + 1) + '); return false;'});
          a2.click(function() { imageGallery.navigate(pos + 1); return false;})
        }
        
        if (!window.getImageGalleryName) {
        	getImageGalleryName = function (img) { return $(img).attr('alt') || ""; }
        }
        if (!window.getImageGalleryText) {
        	getImageGalleryText = function (img) { return $(img).parents("div").children(".imageGalleryDescription").html(); }
        }
        $('#imageGalleryName').html(getImageGalleryName(img));
        $('#imageGalleryText').html(getImageGalleryText(img));
    };

    this.navigate = function (n) {
        if (n >= 0 && n < images.length) {
            this.showImage(images[n]);
        }
    };

    function onload(img) {
        if (!img || !img.src) {
        	img = this;
        	// для IE и анимированных гифов будет вызываться в цикле, поэтому стираем
        	if (img.onload) img.onload = "";
       	}
        if (!img.isAdjusted) {
            var maxWidth = (window.innerWidth || $(window).width()) * .9 - 30;
            var maxHeight = (window.innerHeight || $(window).height()) * .8 - 20;

            var dx = img.width / maxWidth;
            var dy = img.height / maxHeight;
            // Уменьшим картинку
            if (dx < dy) dx = dy;
            if (dx > 1) {
                var w = img.width;
                var h = img.height;
                img.width = w / dx;
                img.height = h / dx;
            }
            img.isAdjusted = true;
        }
        imageGalleryImg.pos = img.pos;
        imageGalleryImg.get(0).src = img.src;
    }

    this.finalLoad = function() {
        var img = cachedImages[imageGalleryImg.pos];
        imageGalleryImgDiv.css({
            width: img.width + "px",
            height: img.height + "px"
        });
        imageGalleryImg.css({
            width: img.width + "px",
            height: img.height + "px"
        });
        $('#imageGalleryImg').fadeIn(400);
        centerPasse();
        isLoaded = true;
    };

    function onclick() {
        imageGallery.showImage(this);
    }

    function centerPasse() {
        imageGalleryPasseDiv.css(
        {
            left: (document.documentElement.scrollLeft || document.body.scrollLeft)
            		 + ((window.innerWidth || $(window).width()) - imageGalleryPasseDiv.width()) / 2,
            top: (document.documentElement.scrollTop || document.body.scrollTop)
            		 + ((window.innerHeight || $(window).height()) - imageGalleryPasseDiv.height()) / 2 - 6
        });
    }

	this.onload = function () {
		$(function () { imageGallery.init(); });
	}
};

if (!window.$) {
	load_script("/opencms/resources/jquery/unpacked/jquery.js", 'js');
    var h = setInterval(
    	function () { 
		  if (window.$) {
	  		clearInterval(h);
	  		imageGallery.onload();
		  }
  		} , 100);
} else {
	imageGallery.onload();
}
