function metaPopup() {

	// Ассоциированный массив данных для AJAX запросов
	this.ajaxParams = {
		"user-community" : {
			"path" : "/ajax/popup_events.php",
			"data" : "type=user-community&id="
		},
		"add-friend" : {
			"path" : "/ajax/popup_events.php",
			"data" : "type=add-friend&id="
		},
		"delete-friend" : {
			"path" : "/ajax/popup_events.php",
			"data" : "type=delete-friend&id="
		}
	}
	
	// Функция добавляет нужный кусок html на страницу
	this.addPopupHtml = function() {
		if ($("#metaShroud").length ==0 && $("#metaPopupBlock").length == 0) {
			$("body").append('<div id="metaShroud" class="metaFader">&nbsp;</div>');
			$("body").append('<div id="metaPopupBlock" class="metaPopup"></div>');
		}
	}
	
	// Функция проверяет, загружен ли на странице нужный css, и если нет - добавляет его
	this.addCss = function() {
		// Ассоциированный массив, используемых стилей
		var useCss = {
			"popup": 	{"exists" : false, "regexp" : /popup.css$/,	"call" : '<link rel="stylesheet" type="text/css" media="screen" href="/css2/popup.css?v.1.0">'},
			"advanced": 	{"exists" : false, "regexp" : /advanced.css$/,	"call" : '<link rel="stylesheet" type="text/css" media="screen" href="/css2/advanced.css?v.1.0">'}
		};

                // Проверяем наличие стилей
		$('head link').each(function() {
			for (i in useCss) {
				if (useCss[i]["regexp"].test($(this).attr("href"))) {
					useCss[i]["exists"] = true;
				}
			}
		});

                // Подключаем не подгруженные стили
		for (i in useCss) {
			if (!useCss[i]["exists"]) {
				$('head').append(useCss[i]["call"]);
			}
		}
	}
	
        // Проверяем наличие всех объектов для работы с классом
	this.addPopupHtml();
	this.addCss();
	
	this.aVisibleSelectsForShoud = new Array();
	
	// Функция возвращает видимые параемтры экрана, width - ширину, height - высоту
	this.getClientSize = function() {
		var w = 0;
		var h = 0;
	
		if (!window.innerWidth) {
			if (!(document.documentElement.clientWidth == 0)) {
				w = document.documentElement.clientWidth;
				h = document.documentElement.clientHeight;
			} else {
				w = document.body.clientWidth;
				h = document.body.clientHeight;
			}
		} else {
			w = window.innerWidth;
			h = window.innerHeight;
		}
	
		return {"width": w, "height": h};
	}
	
}

// Подгружает картинку загрузки	
metaPopup.prototype.setLoadGif = function() {
	$('#metaPopupBlock').empty();
	var divImage = document.createElement('div');
	divImage.id = 'metaPopupBlockDivImage';
	document.getElementById('metaPopupBlock').appendChild(divImage);
	var image = document.createElement('img');
	image.src = '/img/data_loading.gif';
	image.width = 172;
	image.height = 76;
	document.getElementById('metaPopupBlockDivImage').appendChild(image);
	this.showPopupBlock();
}

// Показывает полупрозрачный див на всю видимую область. При этом скрывает в IE некоторые элементы
metaPopup.prototype.showShroud = function() {
	$('#metaShroud').css("height", $('body').height() + 'px');
	$('#metaShroud').css("width", $('body').width() + 'px');
	if ($.browser.msie) {
		_this = this;
		$('select').each(function(){
			if ($(this).css('visibility') != 'hidden') {
				_this.aVisibleSelectsForShoud.push({o: this, c: $(this).css('visibility')});
				$(this).css('visibility', 'hidden');
			}
		});
	}
	    
	$('#metaShroud').show();
}

// Центрирует попап блок
metaPopup.prototype.centerPopupBlock = function() {
	$('#metaPopupBlock').css("left", (this.getClientSize().width/2-($('#metaPopupBlock').width()/2) + $('html').scrollLeft()) + 'px');
	$('#metaPopupBlock').css("top", (this.getClientSize().height/2-($('#metaPopupBlock').height()/2) + $('html').scrollTop()) + 'px');
}

// Показывает попап блок, при этом центрируя его относительно текущего состояния браузера
metaPopup.prototype.showPopupBlock = function() {
	this.centerPopupBlock();
	$('#metaPopupBlock').show();
}

// Убирает попап блок, и для IE востаннавливает прежние значения для ранее скрытых элементов
metaPopup.prototype.hidePopupBlock = function() {
	for (i in this.aVisibleSelectsForShoud) {
		$(this.aVisibleSelectsForShoud[i].o).css('visibility', this.aVisibleSelectsForShoud[i].c);
	}
	$('#metaShroud').hide();
	$('#metaPopupBlock').hide();
}

// Отрисовывает полученный HTML в попап блоке
metaPopup.prototype.showPopupData = function(data) {
	// Отрисовка тени
	this.showShroud();

        // Заполнение контетна попапа
	$('#metaPopupBlock').html(data);

        // Центрирование попап блока
	this.showPopupBlock();

	return true;
}

// Вызывает скрипт с сервера, и отрисовывает полученный HTML в попап блоке
metaPopup.prototype.showPopupFromServer = function(scriptName, dataSend) {
	// Отрисовка тени
	this.showShroud();
	this.setLoadGif();

        // Получение формы через AJAX
	$.ajax({
		async: false,
		type: "GET",
		url: scriptName,
		data: dataSend,
		dataType: "text",
		success: function(data){
			$('#metaPopupBlock').html(data);
		}
	});

        // Вывод попап блока на экран
	this.showPopupBlock();

	return true;
}

// Получает контент попапа через AJAX для указанного типа с параметрами
metaPopup.prototype.getPopup = function(data, type) {
	if (this.ajaxParams[type]) {
		this.showPopupFromServer(this.ajaxParams[type]["path"], this.ajaxParams[type]["data"] + data);
		return false;
	}
	
	return true;
}

function initMetaPopup() {
	window.oMetaPopup = new metaPopup();
}

$(document).ready(function(){
	initMetaPopup();
});
