function communityMembership(element){
    if(!Object.isElement(element)) element = this;
    element = $(element);
    var message = element.readAttribute('message');
    if(message) 
		if(!confirm(message)) return false;
    var staticVars = {
	'icoCommsIn':{'text':'<i></i>Вступить в сообщество','ico':'icoCommsOut','funcname':'perl_community-participate_add','vars':[], 'additional': [{ id:'addToFriends', cssclass:'addfriendsDels', newclass:'addfriends'}]},
	'icoCommsOut':{'text':'<i></i>Выйти из сообщества','ico':'icoCommsIn','funcname':'perl_community-participate_delete','vars':[], 'additional': [{ id:'addToFriends', cssclass:'addfriends', newclass:'addfriendsDels' }, { id:'favor', cssclass:'favorites', newclass:'favoritesDels' }]},
	'favorites':{'text':'<i></i>Добавить в избранное','ico':'favoritesDels','funcname':'perl_community-favorite_add','vars':[]},
	'favoritesDels':{'text':'<i></i>Удалить из избранного','ico':'favorites','funcname':'perl_community-favorite_delete','vars':[]},
	'addfriends':{'text':'<i></i>Читать в ленте','ico':'addfriendsDels','funcname':'perl_community-readblog_add','vars':[]},
	'addfriendsDels':{'text':'<i></i>Не читать в ленте','ico':'addfriends','funcname':'perl_community-readblog_delete','vars':[], 'additional': [{ id:'favor', cssclass:'favorites', newclass:'favoritesDels' }]} ,
	'commentsSubscribe':{'text':'<i class="img"></i>Подписаться на комментарии','ico':'commentsUnSubscribe','funcname':'perl_subscribe_comments',
	    'vars':[0,element.readAttribute('entry')]},
	'commentsUnSubscribe':{'text':'<i class="img"></i>Отписаться от комментариев','ico':'commentsSubscribe','funcname':'perl_subscribe_comments',
	    'vars':[1,element.readAttribute('entry')]},
	'removePoll':{'text':'опрос удален','ico':'','funcname':'perl_move_mainpage_poll','vars':[],'func':onRemovePoll}
    };
    element.writeAttribute('request', element.readAttribute('href'));
    element.removeAttribute('href');
    element.removeAttribute('onClick');
    element.stopObserving('click');
    var request = new Ajax.Request(element.readAttribute('request') + 'ajax?ajax_call=1&func_name=' + staticVars[element.className].funcname, {
	method: 'post',
	postBody: 'data=' + staticVars[element.className].vars.toJSON(),
	onSuccess: function(t){
	    if(t.responseText.evalJSON(true)[1] == 'OK') {
		if(t.request.staticVars[t.request.element.className].ico) t.request.element.className = t.request.staticVars[t.request.element.className].ico;
		else t.request.element.removeAttribute('href');
		t.request.element.update(t.request.staticVars[t.request.element.className].text);
		t.request.element.removeAttribute('message');
		var adds = t.request.staticVars[t.request.element.className].additional;
		if(adds) {
		    for(var i=0;i<adds.length;i++) {
			var add=adds[i];
			if($(add.id)) {
			    var a = $(add.id).select('a.'+add.cssclass);
			    if(a[0]) {
				a[0].className = t.request.staticVars[add.cssclass].ico;
				a[0].update(t.request.staticVars[add.newclass].text);
				a[0].removeAttribute('message');
				a[0].observe('click', communityMembership.bindAsEventListener(a[0]));
			    }
			}
		    }
		}
		var func = t.request.staticVars[t.request.element.className].func;
		if(func) (func)(t.request.element);
	    }
	    t.request.element.writeAttribute('href', t.request.element.readAttribute('request'));
	    t.request.element.observe('click', communityMembership.bindAsEventListener(t.request.element));
	}
    });
    request.element = element;
    request.staticVars = staticVars;
    return false;
}

function communitySubscribe(element) {
    if(Object.isElement(element)) {
	if(element.nodeName == 'FORM') {
	    element.select('[type="submit"]').each(function(el){el.disabled = true});
	    var request = new Ajax.Request(element.readAttribute('request') + 'ajax?ajax_call=1&func_name=perl_subscribe_community', {
		method:'post',
		postBody: 'data=' + [
		    (element.photo.checked ? 1 : 0),
		    (element.journal.checked ? 1 : 0),
		    (element.guestbook.checked ? 1 : 0)
		].toJSON(),
		onSuccess: function(t){
		    if(t.responseText.evalJSON(true)[1] == 'OK') t.request.form.hide();
		    t.request.form.select('[type="submit"]').each(function(el){el.disabled = false});
		}
	    });
	    request.element = this.element;
	    request.form = form;
	} else {
	    if(this.form) this.form.show();
	    else {
		this.element = element;
		var pos = getPosition(element);
		this.form = document.body.appendChild(new Element('div', {'class':'subscribeCommunity','style':'left:'+pos.left+';top:'+pos.top+';'})).update($('subscribeCommunity').innerHTML);
		this.form.select('[name="hide"]').each(function(el){el.observe('click', communitySubscribe.bindAsEventListener())});
	    }
	}
    } else this.form.hide()
    return false;
}
function onRemovePoll (el){ 
    if(el.nodeName) {
	$(el).insert({'after':'<p class="mt10">опрос убран</p>'});
	el.style.display = 'none';
	return onRemovePoll.bind(el, 1).delay(2);
    }
    el = $(this);
    el.style.color = 'black';
    el.style.cursor = 'none';
    var txt = '<h3 class="grey2">На странице сообщества нет опроса.</h3><div class="grey2">Как администратор сообщества, вы можете его <a href="http://'
	+ el.readAttribute('request') + 'jupdate">создать</a></div>';
    var poll = $('poll_container');
    if(!poll) return;
    poll.update(txt);
    return;
}
function showPopup(url,w,h,hideClose,shadowColor,showScroling,className) {
	//var div = document.createElement('div');
	var div = createDiv();
	var frameID = "popupIframe";
	var width = w ? w : 500;
	var height = h ? h : 465;
	var left = parseInt(document.body.scrollWidth/2)-width/2;
	var top = parseInt(getClientHeight()/2)+getBodyScrollTop()-height/2;
	
	var html = hideClose ? '' : '<img src="http://img0.imgsmail.ru/r/blogs/ico_del.png" width="16" height="16" border="0" alt="Закрыть" title="Закрыть" onclick="hidePopup();" class="IEpng popupDivClose" />';
		html +='<iframe src="http://img1.imgsmail.ru/0.gif" frameborder="0" width="'+width+'" height="'+height+'" scrolling="'+(showScroling?'auto':'no')+'" id="'+frameID+'" style="margin-top:-2px;"></iframe>';
	div.innerHTML = html;
	div.id = "popupDiv";
	div.className = className ? "popupDiv "+className : "popupDiv";
	
	div.style.left = (left>0?left:10)+'px';
    div.style.top = (top>0?top:10)+'px';
	
	document.body.appendChild(div);
	gebi(frameID).src=url;
	
	shadowColor ? shadowDiv(1,shadowColor) : shadowDiv(1,'#FFF');
	div.style.display = "block";
}
function hidePopup() {
	div = gebi('popupDiv');
	if(div) {
		shadowDiv(0);
		//div.parentNode.removeChild(div);
		removeDiv(div);
	}
}

function createDiv() {
	return document.createElement('div');
}
function removeDiv(div) {
	div.parentNode.removeChild(div);
}

function addPoll(el, type, approve) {
// type = 1 - add poll, type = 0 - remove poll
// approve = 0 - no, approve = 1 - yes
    el = $(el);
    var ID = el.readAttribute('pollid');
    var pt = el.readAttribute('atype');
    if(pt != undefined) type = pt;
    if(type != 0 && approve == undefined) {
	el.writeAttribute('atype', 0);
	var fader = new Element('div', {'id':'pollFader','style':'position: absolute; background-color: rgb(51, 51, 51); width: 100%; height: 10000px; opacity: 0.5; z-index: 200;'});
	var form = new Element('div', {'id':'pollContent','class':'popupFaderInfomessage'});
	form.style.top = document.body.scrollTop + (document.body.clientHeight/2) - 45 + 'px';
	form.style.left = (document.body.clientWidth/2) - 250 + 'px';
	form.insert(new Element('img', {'src':'http://img.mail.ru/r/blogs/ico_del.png','class':'popupClose IEpng','width':16,'height':16,'onClick':'return addPoll(this,1,0)'}));
	form.insert('<h2 class="mr20">Поставить опрос на главную страницу сообщества, заменив предыдущий опрос?</h2>');
	var yes = new Element('input', {'type':'button','onClick':'return addPoll(this,1,1)','value':'Да','class':'popupButton'});
	yes.writeAttribute('pollid', ID);
	yes.link = el;
	form.insert(yes);
	var no = new Element('input', {'type':'button','onClick':'return addPoll(this,1,0)','value':'Нет','class':'popupButton'}); 
	form.insert(no);
	$($(document.body).cleanWhitespace().firstChild).insert({'before':fader});
	document.body.appendChild(form);
    } else {
	if(type != 0) {
	    document.body.removeChild($('pollContent'));
	    document.body.removeChild($('pollFader'));
	    if(!approve) return false;
	} else el.link = el;
	var path = el.link.href
	var req = new Ajax.Request(path + 'ajax?ajax_call=1&func_name=perl_move_mainpage_poll', {
	    'method':'post',
	    'postBody': 'data=' + [type != 0 ? el.readAttribute('pollid') : 0].toJSON(),
	    'onSuccess': function(t) {
		if(t.request.type != 0) t.request.link.update('<i class="img icoCommunity"></i>Убрать со страницы сообщества');
		else {
		    t.request.link.update('<i class="img icoCommunity"></i>Добавить на страницу сообщества');
		    t.request.link.writeAttribute('atype', 1);
		}
	    }
	});
	req.link = el.link;
	req.type = type;
    }
    return false;
}

// new blogs little part

function _getOffsetPosition(el) {
    el = $(el);
    if (!el) return;

    var width = el.offsetWidth, height = el.offsetHeight;
    var left = 0, top = 0;
    while (el) {
        left += el.offsetLeft;
        top += el.offsetTop;
        el = el.offsetParent;
    }

    return { 'left': left, 'top': top, 'width': width, 'height': height };
}

// dont use this, use getElemPos
function _getBoundingRectPosition(el) {
    el = $(el);
    if (!el || !el.getBoundingClientRect) return;

    var box = el.getBoundingClientRect();

    var body = document.body;
    var docElem = document.documentElement;

    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
 
    var clientTop = docElem.clientTop || body.clientTop || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
 
    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    var width = el.offsetWidth, height = el.offsetHeight;
    return { top: parseInt(top), left: parseInt(left), 'width': width, 'height': height };
}

function getElementPosition(el) {
    el = $(el);
    if (!el) return;

    var saved_props = ['display','visibility','position','top','left'], save = {};
    if (el.style.display == 'none') {
        var len = saved_props.length;
        while (len--) {
            var prop = saved_props[len];
            save[prop] = el.style[prop];
        }
        el.style.visibility = 'hidden';
        el.style.position = 'absolute';
        el.style.top = el.style.left = '-1000px';
        el.style.display = '';
    }

    var position;
    if (el.getBoundingClientRect) {
        position = _getBoundingRectPosition(el);
    } else {
        position = _getOffsetPosition(el);
    }

    if (save[saved_props[0]]) {
        var len = saved_props.length;
        while (len--) {
            var prop = saved_props[len];
            el.style[prop] = save[prop];
        }
    }

    return position;
}
function getElemPos(el) { return getElementPosition(el) }

function getClientHeight() {
    var dEH = (document.documentElement ? parseInt(document.documentElement.clientHeight) : 0);
    var dbH = (document.body ? parseInt(document.body.clientHeight) : 0);
    if (!dEH) return dbH;
    if (!dbH) return dEH;
    return Math.min(dEH, dbH);
}
function getViewportHeight() { return getClientHeight() }

function getBodyScrollTop() {
    return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getBodyScrollHeight() { return document.body.scrollHeight }

function getBodyScrollWidth() {
    return Math.max(
        (document.documentElement ? parseInt(document.documentElement.scrollWidth) : 0),
        document.body.scrollWidth
    );
}

function Preloader(params) {

    var self = this;

    this.timeout = null;
    this.animationHeight = 0;
    this.animationWidth  = 0;

    this.init = function () {
        document.body.appendChild( self.overlay );
        var dims = getElemPos(self.overlay);
        self.animationHeight = dims.height;
        self.animationWidth  = dims.width;

        self.init = function () {};
    };

    if (params.position == 'viewport') {
        this.getPos = function () {
            var dims = {
                'top': parseInt( (getViewportHeight() - self.animationHeight)/2 ),
                'left': parseInt( (getViewportWidth() - self.animationWidth)/2 ),
                'width': self.animationWidth,
                'height': self.animationHeight
            };
            dims.top  += getBodyScrollTop ();
            dims.left += getBodyScrollLeft();
            return dims;
        };
    } else if (typeof params.position == 'object' && !params.position.nodeType) {
        this.getPos = function () { return self._params.position };
    } else if ($(params.position)) {
        this.cover = $(params.position); // what we cover with overlay
        this.getPos = function () { return getElemPos(self.cover) };
    } else {
        throw new Error('wrong Preloader params');
    }

    this.onResize = function () {
        self.init();
        var dims = self.getPos();
        if (dims.height < self.animationHeight*3) dims.height = self.animationHeight*3;
        $H(dims).each(
            function (s) { self.overlay.style[s.key] = s.value + 'px' }
        );
        var heightDelta = dims.height - self.animationHeight;
        if (self.animationHeight) {
            self.animation.style.marginTop = parseInt(heightDelta/2) + 'px';
        } else {
            self.animation.style.marginTop = '0px';
        }
    };

    this.show = function () {
        if (!document.loaded) {
            if (!self.waitDOMReady) {
                document.observe('dom:loaded', self.show);
            }
            self.waitDOMReady = 1;
            return;
        }
        if (!self.overlay.visible()) {
            self.onResize();
            self.overlay.show();
            Event.observe(window, 'resize', self.onResize);
        }
    };

    this.hide = function () {
        if (self.overlay.visible()) {
            self.overlay.hide();
            Event.stopObserving(window, 'resize', self.onResize);
        }
    };

    this.destroy = function () {
        self.overlay.remove();
    };

    ///////////////////////////////////////////////////////////////////////////

    this._params = params;

    // init
    this.overlay = new Element('div').addClassName('preloader_wrap').hide();
    this.animation = new Element('div',{'class':'preloader'}).update(params.text || '');
    this.overlay.appendChild( this.animation );
    if (params.backgroundColor) {
        this.overlay.style.backgroundColor = params.backgroundColor;
    }

}

function Popup(params) {

    var self = this;

    this.init = function () {
        document.body.appendChild(self.popup);

        self.init = function () {};
    };

    if (params.type == 'iframe') {
        this.fill = function (src) {
            self.content.src = src || '';
            // preloader hiding setted in onload
        };
    } else {
        this.fill = function (data) {
            self.content.update().insert(data);
            if (self.preloader) self.preloader.hide();
            var dims = getElemPos(self.content);
            if (dims.height >= self.content.scrollHeight)
                self.content.style.height = 'auto';
            if (self.need_centring) {
                self.centre();
                self.need_centring = 0;
            }
        };
    }

    if (typeof params.onClose == 'function') {
        this.onClose = params.onClose;
    } else {
        this.onClose = function () {};
    }

    this.open = function (width, height, shadowColor) {
        if (!document.loaded) {
            if (!self.waitDOMReady) {
                document.observe('dom:loaded', function () { self.open(width, height, shadowColor) });
            }
            self.waitDOMReady = 1;
            return;
        }
        self.init();
        self.close();

        if (!shadowColor) {
            shadowDiv2(0);
        } else if (shadowColor == 1) {
            shadowDiv2(1);
        } else {
            shadowDiv2(1, shadowColor);
        }

        width  = width  || '';
        height = height || '';
        if (parseInt(width).toString() == width.toString())
            width  = width  + 'px';
        if (parseInt(height).toString() == height.toString())
            height = height + 'px';
        if (self.type == 'iframe') {
            //
            //self.popup.style.width    = 'auto'; // bugz in IE
            self.popup.style.width    = parseInt(width) + 20 + 'px';
            self.content.style.width  = width;
            self.content.style.height = height;
        } else {
            //
            self.popup.style.height   = 'auto';
            self.popup.style.width    = width;
            self.content.style.height = height;
        }

        if (width && height) {
            self.centre();
        } else { // getElemPos(self.popup).height gives zero on that stage
            self.need_centring = 1;
        }

        if (self.paginator) self.paginator._onCtrlLeftRight.On();
        self.popup.show();
        if (self.preloader) self.preloader.show();
    };

    this.centre = function () {
        var dims = getElemPos(self.popup);
        self.popup.style.left = parseInt((getBodyScrollWidth()-dims.width)/2) + 'px';
        var top = getViewportHeight() - dims.height;
        if (top < 100) top = 100;
        top = getBodyScrollTop() + parseInt(top/2);
        self.popup.style.top = top + 'px';
    };

    this.close = function (event) {
        if (event) event.stop();

        shadowDiv2(0);

        if (self.paginator) self.paginator._onCtrlLeftRight.Off();
        if (self.preloader) self.preloader.hide();
        self.popup.hide();
        self.onClose();

        self.fill();
    };

    this.changeTitle = function (text) {
        if (!self.title) return;

        self.title.update(text);
    };

    ///////////////////////////////////////////////////////////////////////////
    this.type  = params.type;

    if (this.type == 'iframe') {
        this.content   = new Element('iframe', {
            'src': 'http://img.mail.ru/0.gif', 'frameborder': 0, 'scrolling': 'no'
        }).observe('load', function () {
            if (self.preloader) self.preloader.hide();
        }).observe('dom:loaded', function () {
            if (self.preloader) self.preloader.hide();
        });
    } else {
        this.content   = new Element('div').addClassName('new_popup_content');
        if (params.paginatorOnClick) {
            this.pager     = new Element('div').addClassName('pager mt15');
            this.paginator = new Paginator({
                'container': this.pager,
                'entries_per_page': params.perpage,
                'pages_per_page': params.pagesperpage,
                'onClick': params.paginatorOnClick
            });
        }
        if (params.title) {
            this.title = new Element('h2').update(params.title);
        }
    }

    var closer = new Element('i',{'class':'imgp icoDell mr0 cp close_popup'}).
                    observe('click', this.close);
    this.popup = new Element('div').addClassName('new_popup').hide().insert(
        new Element('div').addClassName('new_popup_inner').insert(
            this.title ? ( new Element('div',{'class':'ohd'}).insert(closer).insert(this.title) ) : closer
        ).insert(this.content).insert(this.pager || '')
    );

    if (params.preloader) {
        this.preloader = new Preloader({ 'position': this.content, 'text': params.preloaderText || '' });
    }

}

function shadowDiv2(key, color) {
    var id = 'shadow_div2';
    if ($(id)) $(id).parentNode.removeChild(div);

    if (key) {
        div = document.createElement('div');
        div.id = id;
        if (color) div.style.backgroundColor = color;
        div.style.height = document.body.scrollHeight;
        if (document.loaded) {
            document.body.appendChild(div);
        } else {
            document.observe('dom:loaded', function(){document.body.appendChild(div)});
        }
    } 

    return false;
}

function getPluralForm(number, form1, form2, form3) {
    number = parseInt(number);
    if (number % 100 >= 5 && number % 100 <= 20) {
        return form3;
    } else if (number % 10 == 1) {
        return form1;
    } else if ((number % 10) >= 2 && (number % 10) <= 4) {
        return form2;
    } else {
        return form3;
    }
}

var iframePopup  = new Popup({'type': 'iframe', 'preloader': 1, 'preloaderText': 'Загрузка'});
var contentPopup = new Popup({});
