$.fn.openPopup = function(params){
	// Проверяем, вызывался ли попап раньше. Если не вызывался - инициализируем его
	if(!$(this).hasClass('ispopup')){
		if(typeof params == 'undefined' ){
			params={};
		}

		if(typeof params.marginBottom != 'undefined' ){
			marginBottom = params.marginBottom;
		} else {
			marginBottom = 0;
		}
		// Настраиваем подложку
		if(!$('.backlight').length){
			var backlight = $(document.createElement('DIV'));
			backlight.addClass('backlight');
			if(typeof params.bgColor != 'undefined' ){
				backlight.css({'background':params.bgColor});
			}
			backlight.appendTo('#upyachka');
			backlight.fadeTo(1, 0.9);
			//$('#upyachka').height($(document).height());
			backlight.height($(document).height());
			backlight.width($(document).width());
			$('.backlight').click(function(){
				$(this).closePopup();
				if($("#gallery-line").length)
					$("#gallery-line").hide();
				return false;
			});

			// Вставляем пояснительный текст
		//	var helptext = $(document.createElement('P'));
		//	helptext.addClass('helptext');
		//	helptext.html('Кликните в любом месте, чтобы закрыть окно');
		//	helptext.appendTo('#upyachka');
		}

		// Настраиваем сам попап. Копируем в него классы элемента, который окажется у него внутри
		if(!$('.popup').length){
			var bubble = $(document.createElement('DIV'));
			bubble.addClass('popup');
			if(typeof params.popupClass != 'undefined' ){
				bubble.addClass(params.popupClass);
			}
			bubble.appendTo('#upyachka');
		}

		// Прикручиваем закрывалку
		$('#upyachka .popup').html('<div class="popupcloser"></div>');
		$('#upyachka .popup').append($(this));

		if((typeof params.showCloser!='undefined')&&(params.showCloser==false)){
			$('#upyachka .popupcloser').hide();
		}

		// Вешаем обработчики на закрытие попапа
		$('.popupcloser').click(function(){
			$(this).closePopup();
			if($("#gallery-line").length)
				$("#gallery-line").hide();
			return false;
		});
		$(this).find('.cancel').click(function(){
			$(this).closePopup();
			if($("#gallery-line").length)
				$("#gallery-line").hide();
			return false;
		});

		// Внимательно слушаем клавишу Esc
		$(document).keydown(function(e) {
			if(e.which==27) $(this).closePopup();
			if($("#gallery-line").length)
				$("#gallery-line").hide();
		});


		// Говорим попапу, что он попап и показываем его
		$(this).addClass('ispopup');
		if(typeof params.popupClass != 'undefined' ){
			$(this).addClass(params.popupClass);
		}
		$(this).show();

	//	if($("object").length)
	//		$("object").append('<param name="wmode" value="opaque">').css({"display":"block","z-index":1});
	}

	// Закрываем предыдущий попап и открывам текущий
	//$(this).parent('.popup:visible').closePopup();
	//$(this).parent('.popup').show();

	// Эта хрень должна исчезнуть, когда сделаем предзагрузку
	if ($('#upyachka .popup').width()) {
		var popupWidth = $('#upyachka .popup').width();
	}

	if ($('#upyachka .popup').height()) {
		var popupHeight = $('#upyachka .popup').height();
	}

	// Настраиваем размеры окна попапа в соотвествии с тем, что будет у него внутри
	$(this).parent('.popup').css({marginTop:-popupHeight/2+$(document).scrollTop()-marginBottom,marginLeft:-popupWidth/2,top:"50%",left:"50%"});

	if(jQuery.browser.opera){
		$(document).oneTime(1,"hideDropdown",function(){
			$('.popup').show();
		});
	} else {
		$('.popup').show();
	}

	$('.backlight').css({left:'0px'}).show();
	$('.helptext').css({top:$(document).scrollTop()}).show();

	// Костыли - скрываем селекты в эксплорере, чтобы они не просвечивали через подложку
	if(jQuery.browser.msie){
		$('.supportblock select').hide();
	}
}

// Обрабатываем закрытие попапа
$.fn.closePopup = function() {
	$('.backlight').css({left:'-100000px'});
	$('.popup').css({marginTop:-$('.popup').height()/2+$(document).scrollTop(),marginLeft:-$('.popup').width()/2,top:"50%",left:"50%",display:"none"});
	$('.helptext').hide();
	if(jQuery.browser.msie){
		$('.supportblock select').show();
	}
}

$(function(){
	if($(".image-lightbox").length){
		$(".image-lightbox").click(function(){
			var preloaderDiv = $(document.createElement('DIV'));
			preloaderDiv.html('<div class="img-preloader"></div>');
			preloaderDiv.openPopup({bgColor:"#000",showCloser:false});

			var imgLink = $(this).attr('href');
			var imgTitle = $(this).attr('title');
			var image = $('<img src="'+ imgLink  +'" alt="'+ imgTitle +'" class="popup-image"/>');
                        var imageContainer = $(document.createElement('DIV'));
                        // чтобы Опера 9 начала загружать рисунок, надо сначала вставить его в видимый элемент, а потом уже скрыть его.
                        image.appendTo(imageContainer);
                        imageContainer.appendTo($("body")).hide();
                        
                        image.load(function(){
                            var image = $(this);
                            var imageWidth = image.width();
                            var imageHeight = image.height();
                            var frameWidth = $(".backlight").width()-80;
                            var frameHeight = $(".backlight").height()-80;

                            // Вписываем картинку в размер окна,
                            // если она шире, чем окно
                            if (imageWidth > frameWidth) {
                                    image.width(frameWidth);
                                    imageHeight = image.height();
                            }

                            // Вписываем картинку в размер окна,
                            // если она выше, чем окно
                            if (imageHeight > frameHeight) {
                                    image.height(frameHeight);
                                    imageWidth = image.width();
                            }

                            image.parent().openPopup({popupClass:"popup-image-block"}/*{bgColor:"#000",popupClass:"popup-image-block"}*/);
                        }).each(function () {
                            // это для браузеров, берущих рисунки из кеша - в них событие 'onload' не срабатывает для этих картинок.
                            if (this.complete) {
                                $(this).trigger('load');
                            }
                        });
                        
			return false;
		});
	}
});