$(document).ready(function(){
    (function(){
        var bgs = $('#super__top_bg, #super__bottom_bg');
        if (bgs.length == 0)
            return;
        var body = ($.browser.msie && $.browser.version == '7.0' ? $('html') : $('body'));
        var superDiv = $('#super');
        var sizeMode = -1;
        var onResize = function() {
            var newMode = superDiv.width() <= 1000 ? 0 : 1;
            if (newMode != sizeMode)
            {
                sizeMode = newMode;
                if (newMode == 1)
                {
                    bgs.css('right', '');
                    body.css('overflowX', 'hidden');
                    $(window).scrollLeft(0);
                }
                else
                {
                    body.css('overflowX', 'auto');
                    bgs.css('right', '0px');
                }
            }
        };
        onResize();
        $(window).resize(onResize);
        var onScroll = function() {
            if (sizeMode == 1)
                $(window).scrollLeft(0);
        };
        onScroll();
        $(window).scroll(onScroll);
    })();

    (function(){
        if ($.browser.msie && $.browser.version == '7.0')
            $('#topauth p.c_name a span.c_avatar').click(function(){
                window.location = $('#topauth p.c_name a span.c_avatar').closest('a').attr('href');
            });
    })();

    (function(){
        var logoImg = $('#menu_logo img');
        if (logoImg.length == 2)
        {
            if ($.browser.msie)
            {
                $('#menu_logo').mouseenter(function(){
                    logoImg.eq(0).css('display', 'none');
                    logoImg.eq(1).css('display', 'block');
                }).mouseleave(function(){
                    logoImg.eq(1).css('display', 'none');
                    logoImg.eq(0).css('display', 'block');
                });
            } else
            {
                logoImg.eq(1).css({'display': 'block', 'opacity': '0'});
                $('#menu_logo').mouseenter(function(){
                    logoImg.eq(0).stop();
                    logoImg.eq(1).stop();
                    var time = 400;
                    var duration = (1 - parseInt(logoImg.eq(1).css('opacity'))) * time;
                    logoImg.eq(1).animate({'opacity': '1'}, {'duration': duration});
                    logoImg.eq(0).animate({'opacity': '0'}, {'duration': duration})
                }).mouseleave(function(){
                    logoImg.eq(0).stop();
                    logoImg.eq(1).stop();
                    var time = 250;
                    var duration = time; //parseInt(logoImg.eq(1).css('opacity')) * time;
                    logoImg.eq(1).animate({'opacity': '0'}, {'duration': duration});
                    logoImg.eq(0).animate({'opacity': '1'}, {'duration': duration});
                });
            }
        }
    })();

    (function(){
        var about_nav = $('#about_nav');
        if (about_nav.length > 0)
        {
            var isIE7 = ($.browser.msie && $.browser.version == '7.0');
            var currentState = 0;
            var c1 = about_nav.find('div.c1');
            var initTop = about_nav.offset().top;
            var toBottom = parseInt($('#content').css('paddingBottom')) + 20 + about_nav.height();
            $(window).scroll(function(){
                var scrollTop = $(window).scrollTop();
                var newState = (scrollTop - initTop + 20 <= 0 ? 0 : 1);
                if (newState == 0)
                {
                    if (currentState != newState)
                    {
                        c1.css({'position': 'static'});
                        if (isIE7)
                            c1.css({'left': 'auto'});
                    }
                } else
                {
                    if (isIE7 && currentState != newState)
                        c1.css({'left': about_nav.offset().left + 'px'});
                    c1.css({'position': 'fixed', 'top': Math.min(20, $(document).height() - scrollTop - toBottom) + 'px'});
                }
                currentState = newState;
            });
            if (isIE7)
                $(window).resize(function(){
                    if (currentState == 1)
                        c1.css({'left': about_nav.offset().left + 'px'});
                });
        }
    })();

    (function(){
        var container = $('#about_participants_students');
        if (container.length > 0)
        {
            var divs = container.children('.about_participant');
            var prevWidth = 0;
            var prevInRow = 0;
            var onResize = function() {
                var width = container.parent().width();
                if (width == prevWidth)
                    return;
                prevWidth = width;
                var inRow = Math.floor((width + 25) / 165);
                if (inRow != prevInRow)
                {
                    prevInRow = inRow;
                    divs.removeClass('c_clear');
                    for (var i = 1; i < divs.length; i++)
                        if (i % inRow == 0)
                            divs.eq(i).addClass('c_clear');
                }
                var marginRight = Math.min(60, Math.floor((width - 140 * inRow) / (inRow - 1) - 0.001));
                for (var i = 0; i < divs.length; i++)
                    divs.eq(i).css('marginRight', (i + 1) % inRow == 0 ? '0px' : marginRight + 'px');
            };
            onResize();
            $(window).resize(onResize);
        }
    })();
});

var sfe=true;
var sff=false;
var ufe=true;

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

function sf_focus()
{
 	if(sfe)
 	{
   		var f=document.getElementById('sfield');
   		f.value='';
   		f.style.color='#000000';
   		sff=true;
 	}
 	return true;
}

function sf_blur(s)
{
	var f=document.getElementById('sfield');
	if(f.value=='')
	{
		f.value='';
		sfe=true;
   		f.style.color='#CCCCCC';
		f.value=s;
		sff=false;
	}
	else
   		sfe=false;
 	return true;
}

function sfbtn_over()
{
	var f=document.getElementById('sfbtn');
	f.src="/images/search-icon-a-3.png";
	return true;
}

function sfbtn_out()
{
	var f=document.getElementById('sfbtn');
	f.src="/images/search-icon-3.png";
	return true;
}

function sfform_submit()
{
	var s=document.getElementById('sfield');
	var query=sff?s.value.replace(/[\?#]/g,''):'';
	if(query!='')query+='/';
	window.location=s.form.action+query;
}

function search_submit(frm)
{
	var query=trim(frm.query.value.replace(/[\?#]/g,''));
	if(query!='')query+='/';
	window.location=frm.action+query;
}

function preImages()
{
	var imgs=new Array(
	"/images/search-icon-a-3.png",
	"/images/authwindow.png",
	"/images/authclose.png",
	"/images/authclose-a.png",
	"/images/printer.png",	 // For tables (JIC)
	"/images/printer-a.png",
	"/images/table-asc.png",
	"/images/table-desc.png",
	"/images/table-asc2.png",
	"/images/table-desc2.png",
	"/images/right-sam.png",
	"/images/right-sat.png",
	"/images/right-sab.png",
	"/images/right-b.png",
	"/images/tv_01.png",
	"/images/tv_11.png",
	"/images/dotted-a.gif",
	"/images/topic-bg-a.png",
	"/images/topic-l-a.png",
	"/images/topic-r-a.png",
	"/images/topic-l-s.png",
	"/images/topic-r-s.png",
	"/images/tw.png",
	"/images/tw-t.png",
	"/images/tw-b.png",
	"/images/tw-bg.png",
	"/images/ta_slider.png",
	"/images/loading-simple.gif",
	"/images/extra-a.png",
	"/images/extra-soft-a.png"
	);
	preloadImages(imgs);
	if(/msie|MSIE 6/.test(navigator.userAgent))preloadImages(["/images/tw-bg-ie.png"]);
	return true;
}

preImages();

function r_p2_focus()
{
	document.getElementById('r_p2p').innerHTML='<input type="password" name="password2" class="c0 required" id="r_p2" value="" />';
	sq_feedback_check(forms[0]);
	var f=document.getElementById('r_p2');
	f.style.color='black';
	f.style.fontStyle='normal';
	f.onkeyup=sq_feedback_check;
	setTimeout("document.getElementById('r_p2').focus()",1);
	return true;
}

function p_p2_focus()
{
	document.getElementById('p_p2p').innerHTML='<input type="password" name="password2" id="p_p2" value="" class="c0" />';
	sq_feedback_check(forms[0]);
	var f=document.getElementById('p_p2');
	f.style.color='black';
	f.style.fontStyle='normal';
	f.onkeyup=sq_feedback_check;
	setTimeout("document.getElementById('p_p2').focus()",1);
	return true;
}


function login_sel()
{
	if(document.regfrm)
	{
		document.regfrm.password.value="";
		document.regfrm.login.select();
		document.regfrm.login.focus();
	}else if(document.profrm)
	{
		document.profrm.password.value="";
	}
	return true;
}

function sin_close_over()
{
	document.getElementById('sin_close').style.backgroundImage='url("/images/authclose-a.png")';
	return true;
}

function sin_close_out()
{
	document.getElementById('sin_close').style.backgroundImage='url("/images/authclose.png")';
	return true;
}

function signin_click()
{
	document.getElementById('signin').style.display='block';
	document.getElementById('signin2').style.display='block';
	document.signinfrm.login.select();
	document.signinfrm.login.focus();
	window.scrollTo($('#super').width() - $(window).width(),0);
	return true;
}

function sin_close_click()
{
	document.getElementById('signin2').style.display='none';
	document.getElementById('signin').style.display='none';
	return true;
}

function sin_keydown(e)
{
	var key;
	if(window.event)key=window.event.keyCode;
	else key = e.which;
	var keychar = String.fromCharCode(key);
	if(key==27)sin_close_click();
}

function avsub_check()
{
 	var s=document.getElementById('avfile');
 	var k=document.getElementById('av_del');
 	if((s.value=='')&&!(k&&(k.checked)))document.getElementById('avsub').disabled="disabled";else document.getElementById('avsub').disabled="";
 	return true;
}

function print_over(s)
{
	s.src="/images/printer-a.png";
	return true;
}

function print_out(s)
{
	s.src="/images/printer.png";
	return true;
}

function comfrm_submit()
{
	var iframe=document.getElementById('comtext_iframe');
	var doc=iframe.contentDocument?iframe.contentDocument:iframe.contentWindow.document;
	document.comfrm.com_text.value=textarea_iframe_plaintext(doc.body.innerHTML);
	return true;
}

function sq_dumpVar(v){var s='';for(var a in v){s+=a+': '+v[a]+'\n'}return s;};
function sq_getTop(el){var res=0;while(el!=null){res+=el.offsetTop;el=el.offsetParent;}return res;}
function sq_preventDefault(e){if(!e)e=window.event;if(e.preventDefault)e.preventDefault();e.returnValue=false;}

var textarea_iframe_states=[];
var textarea_iframe_mouseup_event,textarea_iframe_keyup_event,textarea_iframe_keypress_event,textarea_iframe_focus_event,textarea_iframe_blur_event;

function textarea_iframe_getInitHtml(dontbreak)
{
	if(dontbreak)
		return '<html><head><style type="text/css">* {color: black !important; font-weight: normal !important; text-decoration: none !important; margin: 0px !important; padding: 0px !important; float: none !important; font-family: Arial, Helvetica, sans-serif !important; font-size: 12px !important; border-width: 0px !important; position: static !important; background: none !important; width: auto !important; height: auto !important; min-width: 0 !important; min-height: 0 !important; cursor: text !important; vertical-align: baseline !important; white-space: nowrap !important; line-height: 10px !important} body {padding: 2px !important} img,input,iframe {display: none !important; visibility: hidden !important; width: 0px !important; height: 0px !important}</style></head><body><p><br /></p></body></html>';
	else
		return '<html><head><style type="text/css">* {color: black !important; font-weight: normal !important; text-decoration: none !important; margin: 0px !important; padding: 0px !important; float: none !important; font-family: Arial, Helvetica, sans-serif !important; font-size: 12px !important; border-width: 0px !important; position: static !important; background: none !important; width: auto !important; height: auto !important; min-width: 0 !important; min-height: 0 !important; cursor: text !important; vertical-align: baseline !important; white-space: normal !important; line-height: 145% !important} body {padding: 2px !important} img,input,iframe {display: none !important; visibility: hidden !important; width: 0px !important; height: 0px !important}</style></head><body><p><br /></p></body></html>';
}

function textarea_iframe_reset(id,dontFocus)
{
	var iframe=document.getElementById(id);
	var doc=iframe.contentDocument?iframe.contentDocument:iframe.contentWindow.document;
	doc.open();
	doc.write(textarea_iframe_getInitHtml());
	doc.close();
	doc.designMode = "on";
    if(isIE6)doc=iframe.contentWindow.document; // Yes, IE6 just needs it for one more time.

		if(textarea_iframe_mouseup_event)removeEvent('mouseup',textarea_iframe_mouseup_event,doc);
		textarea_iframe_mouseup_event=function(){textarea_iframe_change(id);};
		addEvent('mouseup',textarea_iframe_mouseup_event,doc);

		if(textarea_iframe_keyup_event)removeEvent('keyup',textarea_iframe_keyup_event,doc);
		textarea_iframe_keyup_event=function(){textarea_iframe_change(id);}
		addEvent('keyup',textarea_iframe_keyup_event,doc);

		if(textarea_iframe_keypress_event)removeEvent('keypress',textarea_iframe_keypress_event,doc);
		textarea_iframe_keypress_event=function(e){textarea_iframe_press(e);}
		addEvent('keypress',textarea_iframe_keypress_event,doc);

	if(textarea_outline&&iframe.contentWindow)
	{
		if(textarea_iframe_focus_event)removeEvent('focus',textarea_iframe_focus_event,iframe.contentWindow);
		textarea_iframe_focus_event=function(){textarea_iframe_focus(id);}
		addEvent('focus',textarea_iframe_focus_event,iframe.contentWindow);

		if(textarea_iframe_blur_event)removeEvent('blur',textarea_iframe_blur_event,iframe.contentWindow);
		textarea_iframe_blur_event=function(){textarea_iframe_blur(id);}
		addEvent('blur',textarea_iframe_blur_event,iframe.contentWindow);
	}
	try{doc.execCommand('styleWithCSS',false,false);}catch(e){};
	try{doc.execCommand('insertBrOnReturn',false,false);}catch(e){};
	if(!dontFocus||dontFocus==500)
		setTimeout(function(){iframe.contentWindow.focus();},(dontFocus==500&&(isIE6||isIE7||isIE8)?500:1));
}

var textarea_iframe_plaintext_italic,textarea_iframe_plaintext_top;

function textarea_iframe_plaintext_parse(node,win,depth,italic,prev_italic,prev_top)
{
	if(typeof italic=='undefined')italic=false;
	if(depth==0)
	{
		textarea_iframe_plaintext_italic=false;
		textarea_iframe_plaintext_top=false;
	}
	var result='';
	if(!italic&&node.nodeType==1)
	{
		var nodeName=node.nodeName.toLowerCase();
		if(nodeName=='i'||nodeName=='em'|| win.getComputedStyle&&win.getComputedStyle(node,null).getPropertyValue('font-style').toLowerCase()=='italic' || node.currentStyle&&node.currentStyle.fontStyle.toLowerCase()=='italic')italic=true;
	}
	if(node.nodeType==3&&node.nodeValue.length>0)
	{
		var span=win.document.createElement('span');
		span.innerHTML=node.nodeValue;
		node.parentNode.replaceChild(span,node);
        var top=sq_getTop(span);
		if(textarea_iframe_plaintext_top===false)textarea_iframe_plaintext_top=top;
		span.parentNode.replaceChild(node,span);
		if(!italic&&textarea_iframe_plaintext_italic)result+='[/sq_i]';
		if(top>textarea_iframe_plaintext_top+4)result+='[sq_br]'; // 0 ideally
		if(top>textarea_iframe_plaintext_top+14)result+='[sq_br]'; // 10 ideally, but sometimes world’s just not perfect
		if(italic&&!textarea_iframe_plaintext_italic)result+='[sq_i]';
		result+=node.nodeValue;
		textarea_iframe_plaintext_italic=italic;
		textarea_iframe_plaintext_top=top;
	}
	for(var i=0;i<node.childNodes.length;i++)result+=textarea_iframe_plaintext_parse(node.childNodes[i],win,depth+1,italic);
	if(depth==0)
	{
		if(textarea_iframe_plaintext_italic)result+='[/sq_i]';
	}
	return result;
}

function textarea_iframe_plaintext(html)
{
	var iframe=document.createElement('iframe');
	iframe.style.position='absolute';
	iframe.style.top=iframe.style.left='-500px';
	iframe.style.width=iframe.style.height='100px';
	document.getElementById('super').appendChild(iframe);
	var win=iframe.contentWindow;
	var doc=iframe.contentDocument?iframe.contentDocument:iframe.contentWindow.document;
	doc.open();
	doc.write(textarea_iframe_getInitHtml(true));
	doc.close();
	doc.body.innerHTML=html;
	var result=textarea_iframe_plaintext_parse(doc.body,win,0);
	iframe.parentNode.removeChild(iframe);
	return result;
}

function textarea_iframe_focus(id)
{
	var div=document.getElementById(id).parentNode;
	div.style.outlineColor=textarea_outline[0];
	div.style.outlineStyle=textarea_outline[1];
	div.style.outlineWidth=textarea_outline[2];
	div.style.outlineOffset=textarea_outline[3];
}

function textarea_iframe_blur(id)
{
	var div=document.getElementById(id).parentNode;
	div.style.outlineStyle='none';
}

function textarea_iframe_press(e)
{
    if(!e)e=window.event;
    if(e.ctrlKey&&e.keyCode==0&&e.which==105) // Ctrl + I for Firefox (3.6). Other browsers handle Ctrl + I in a desired manner on their own
    {
		textarea_iframe_command('comtext_iframe','italic');
		sq_preventDefault(e);
		return false;
    }
	if(e.ctrlKey&&(e.keyCode==13||e.keyCode==10) && !document.getElementById('comsbm').disabled)
	{
		comfrm_submit();
		document.comfrm.submit();
	}
	return true;
}

function textarea_iframe_change(id,cm)
{
	var iframe=document.getElementById(id);
	var doc=iframe.contentDocument?iframe.contentDocument:iframe.contentWindow.document;
	if(doc.body.innerHTML.stripHTML().replace(/( | |&nbsp;|\n)/g,'')=='')document.getElementById('comsbm').disabled=true;else document.getElementById('comsbm').disabled=false;

	textarea_iframe_getSelectedState(id);
	var italic_a=document.getElementById(id+'_italic');
	var italic=(cm&&cm=='italic'?!italic_a.sq_active:textarea_iframe_states['italic']);
	if(!italic&&italic_a.sq_active)
	{
		italic_a.sq_active=false;
		italic_a.innerHTML=textarea_iframe_italic;
		italic_a.className='c_italic';
	}else if(italic&&!italic_a.sq_active)
	{
		italic_a.sq_active=true;
		italic_a.innerHTML=textarea_iframe_italic_active;
		italic_a.className='c_italic c_active';
	}
}

function textarea_iframe_command(id,cm)
{
	var iframe=document.getElementById(id);
	var doc=iframe.contentDocument?iframe.contentDocument:iframe.contentWindow.document;
	iframe.contentWindow.focus();
	doc.execCommand(cm,false,null);
	iframe.contentWindow.focus();
	textarea_iframe_change(id,cm);
}

function textarea_iframe_isNodeItalic(node,win)
{
	var italic=false;
	do if(node.nodeType==1)
	{
		var nodeName=node.nodeName.toLowerCase();
		if(nodeName=='i'||nodeName=='em'|| win.getComputedStyle&&win.getComputedStyle(node,null).getPropertyValue('font-style').toLowerCase()=='italic' || node.currentStyle&&node.currentStyle.fontStyle.toLowerCase()=='italic')
		{
			italic=true;
			break;
		}
	}while(node=node.parentNode);
	return italic;
}

/*
function getNextNode(node,endNode,skipChildren)
{
  if(endNode==node)return null;
  if(node.firstChild&&!skipChildren)return node.firstChild;
  if (!node.parentNode)return null;
  return node.nextSibling||getNextNode(node.parentNode,endNode,true);
};
*/

function textarea_iframe_checkTextNodes(node,range,win,italic)
{
	var result=[0,0];
	if(!italic&&node.nodeType==1)
	{
		var nodeName=node.nodeName.toLowerCase();
		if(nodeName=='i'||nodeName=='em'|| win.getComputedStyle&&win.getComputedStyle(node,null).getPropertyValue('font-style').toLowerCase()=='italic' || node.currentStyle&&node.currentStyle.fontStyle.toLowerCase()=='italic')italic=true;
	}
	if(node.nodeType==3&&node.nodeValue.length>0) // textnode
	{
		var inRange_f=range.comparePoint(node,0);
		var inRange_ff=range.comparePoint(node,1);
		var inRange_ll=range.comparePoint(node,node.nodeValue.length-1);
		var inRange_l=range.comparePoint(node,node.nodeValue.length);
        if(inRange_f==0&&inRange_ff==0 || inRange_l==0&&inRange_ll==0 || inRange_f==-1&&inRange_l==1)
        {
        	if(italic)result[0]++;else result[1]++;
        }
	}
	for(var i=0;i<node.childNodes.length;i++)
	{
		var cresult=textarea_iframe_checkTextNodes(node.childNodes[i],range,win,italic);
		result[0]+=cresult[0];
		result[1]+=cresult[1];
	}
	return result;
}

function textarea_iframe_getSelectedState(id)
{
	var iframe=document.getElementById(id);
	var node,selection,range;
	var win=iframe.contentWindow;
	if (win.getSelection)
	{
		selection=win.getSelection();
		range=selection.getRangeAt(0);
        if(range.collapsed)
        	textarea_iframe_states['italic']=textarea_iframe_isNodeItalic(range.endContainer,win);
        else
/*
        if(range.startContainer.tagName&&range.startContainer.tagName.toLowerCase()=='body' && range.endContainer.tagName&&range.endContainer.tagName.toLowerCase()=='body')
        {
        	var body=(range.startContainer.tagName&&range.startContainer.tagName.toLowerCase()=='body')?range.startContainer:range.endContainer;
        	textarea_iframe_states['italic']=true;
        	for(var i=0;i<body.childNodes.length;i++)if(!(textarea_iframe_isNodeItalic(body.childNodes[i],win)))
        	{
	        		textarea_iframe_states['italic']=false;
	        		break;
	       	}
        }
        else
        {
        	console.log(range.startContainer,range.endContainer,range.startOffset,range.endOffset);
        	textarea_iframe_states['italic']=true;
			node=range.startContainer;
			do
			{
				if(node==range.startContainer&&node.nodeType==3&&range.startOffset>=node.nodeValue.length)continue;
				if(node==range.endContainer&&node.nodeType==3&&range.endOffset<=0)continue;
				if(node.tagName&&node.tagName.toLowerCase()=='br')continue;
				if(!textarea_iframe_isNodeItalic(node,win))
				{
					console.log(node);
					textarea_iframe_states['italic']=false;
					break;
				}
			}while(node=getNextNode(node,range.endContainer));
		}
*/
	{
		var doc=iframe.contentDocument?iframe.contentDocument:iframe.contentWindow.document;
        var res=textarea_iframe_checkTextNodes(doc.body,range,win);
        textarea_iframe_states['italic']=(res[0]>0&&res[1]==0);
	}
	}else
	{
		selection=win.document.selection;
		range=selection.createRange();
		textarea_iframe_states['italic']=textarea_iframe_isNodeItalic(range.parentElement(),win);
	}
}

var textarea_outline;

function getTextareaOutline()
{
	if(!window.getComputedStyle)
	{
		textarea_outline=false;
		return false;
	}
	var t=document.createElement('textarea');
	t.style.position='absolute';
	t.style.left='-500px';
	renew_canvas();
	t.style.top=canvas.scrollTop+'px';
	t.style.width='100px';
	t.style.height='20px';
	document.getElementById('super').appendChild(t);
	t.focus();
	var s=window.getComputedStyle(t,null);
	var oo=s.getPropertyValue('outline-offset');
	if(oo=='')oo='-2px'; // Safari 5 bug
	textarea_outline=[s.getPropertyValue('outline-color'),s.getPropertyValue('outline-style'),s.getPropertyValue('outline-width'),oo];
	t.parentNode.removeChild(t);
}

function c_click(n,dontFocus)
{
	if(typeof textarea_outline=='undefined')getTextareaOutline();
	if(cc==n)
	{
		textarea_iframe_reset('comtext_iframe',dontFocus);
	    var comfiles=document.getElementById('comfiles');
	    comfiles.style.display='none';
	    comfiles.innerHTML='';
	    document.getElementById('comcanat').style.display='none';
	    document.getElementById('comatf').style.display='inline';
	    document.getElementById('comsbm').disabled='disabled';
	    return true;
	}
	if(cc>-1)document.getElementById('cl'+cc).className='dashed';
	cc=n;
	document.comfrm.parent.value=n;
	if(n==0)
		document.getElementById('cl'+n).className='comment_active0';
	else
		document.getElementById('cl'+n).className='comment_active';
	var f=document.getElementById('comdiv');
    document.getElementById('cd'+n).appendChild(f);
    f.style.display='block';
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if(isIE6)setProperSizesIE(true);
 	document.comfrm.comsbm.disabled='disabled';
	setTimeout(function(){textarea_iframe_reset('comtext_iframe')},1);
    var comfiles=document.getElementById('comfiles');
    comfiles.style.display='none';
    comfiles.innerHTML='';
    document.getElementById('comcanat').style.display='none';
    document.getElementById('comatf').style.display='inline';
    document.getElementById('comsbm').disabled='disabled';
    if(n==0)window.scroll(0,document.getElementById('content').offsetHeight);
	return true;
}

function c_close()
{
 	if(cc>-1)document.getElementById('cl'+cc).className='dashed';
 	cc=-1;
	document.comfrm.parent.value=-1;
	var f=document.getElementById('comdiv');
	f.style.display='none';
 	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if(isIE6)setProperSizesIE(true);
 	return true;
}

function cattach_del(n,prev)
{
	var el;
	if(arguments.length>1)
	{
		el=document.getElementById('comfile_del'+(n-1));
		el.parentNode.removeChild(el);
	}
	el=document.getElementById('comfile'+n);
	var del=document.createElement('p');
	del.id='comfile_del'+n;
	del.className='x';
	del.innerHTML='<a href="#" onclick="cattach_del_click('+n+'); return false" class="x">&times;</a>';
	del.style.top=(n==0?4:0)+'px';
	el.parentNode.appendChild(del);
}

function cattach_del_click(n)
{
	if(n==0)return ccanat_click();
	document.getElementById('comfiles'+(n-1)).innerHTML='';
	cattach_del(n-1);
}

function cattach_click(hint)
{
	document.getElementById('comatf').style.display='none';
	document.getElementById('comcanat').style.display='inline';
    var comfiles=document.getElementById('comfiles');
    comfiles.innerHTML='<input type="hidden" name="max_file_size" value="2097152" /><input type="file" class="comfile0" size="47" name="comfile0" id="comfile0" onchange="cfile_changed(0)" /><span id="attach_hint">'+hint+'</span><div id="comfiles0"></div>';
    cattach_del(0);
    comfiles.style.display='block';
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if(isIE6)setProperSizesIE(true);
	return true;
}

function cfile_changed(n)
{
	if(n==4)return true;
	var el;
	if(n==0)
	{
		el=document.getElementById('attach_hint');
		el.parentNode.removeChild(el);
	}
	el=document.getElementById('comfile'+n);
	var el2=document.getElementById('comfile'+(n+1));
	if(el.value==''||el2)return true;
	var ccf=document.getElementById('comfiles'+n);
	ccf.innerHTML+='<input type="hidden" name="max_file_size" value="2097152" /><input type="file" class="comfile" size="47" name="comfile'+(n+1)+'" id="comfile'+(n+1)+'" onchange="cfile_changed('+(n+1)+')" /><div id="comfiles'+(n+1)+'"></div>';
    cattach_del(n+1,1);
	ccf.style.display='block';
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if(isIE6)setProperSizesIE(true);
	return true;
}

function ccanat_click()
{
    var comfiles=document.getElementById('comfiles');
    comfiles.style.display='none';
    comfiles.innerHTML='';
    document.getElementById('comcanat').style.display='none';
    document.getElementById('comatf').style.display='inline';
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if(isIE6)setProperSizesIE(true);
    return true;
}

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}


function rsex_click(s1,s2,s3)
{
	var o=document.regfrm.status.options;
	o[1].text=s1;
	o[2].text=s2;
	o[3].text=s3;
	return true;
}

function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function uf_timeout()
{
	uf_ch2(window.mathol_qsfield);
	window.mathol_qsfield_timeout=setTimeout(uf_timeout,1000);
}

function uf_focus()
{
 	if(ufe)
 	{
   		var f=document.getElementById('usearch');
   		f.value='';
   		f.style.color='#000000';

   		window.mathol_qsfield=f;
   		window.mathol_qsfield_timeout=setTimeout(uf_timeout,1000);
 	}
 	return true;
}

function uf_blur(s)
{
	var f=document.getElementById('usearch');
	if(f.value=='')
	{
		clearTimeout(window.mathol_qsfield_timeout);

		f.value='';
		ufe=true;
   		f.style.color='#999999';
		f.value=s;
	}
	else
   		ufe=false;
 	return true;
}

function preg_quote(str)
{
    // Quote regular expression characters plus an optional character
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/preg_quote
    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1');
}

/*
function uf_ch(s)
{
	var uf_ch_cur=trim(s.value);
	if(uf_ch_prev==uf_ch_cur)return false;else uf_ch_prev=uf_ch_cur;
	var nbr=String.fromCharCode(160);
	var str=str_replace(["'",'&rsquo;','&laquo;','&raquo;','&nbsp;'],['’','’','«','»',nbr],preg_quote(uf_ch_cur));
	str=str.replace(/"/g,'(«|»)').replace(eval("/( |"+nbr+")/g"),'( |'+nbr+')').replace(/(³|è)/g,'(³|è)');
	var divs=document.getElementById('users').childNodes,divs2=new Array(),el,i,b,cnt=0,l=divs.length;
	for(i=0;i<l;i++)if(divs[i].nodeType==1)divs2.push(divs[i]);
	divs=divs2;
	l=divs.length;
	if(str=="")
	{
		document.getElementById('nousers').style.display='none';
  		for(i=0;i<l;i++)if(divs[i].className!='c8'&&divs[i].className!='c9')
  		{
  			divs[i].innerHTML=divs[i].innerHTML.replace(eval("/<[/]?i>/ig"),"");
  			divs[i].style.display='';
  			cnt++;
  		}else divs[i].style.display='';
  		document.getElementById('ucnt').innerHTML=cnt;
		document.getElementById('ucntp').style.display='';
 	}
	else
	{
  		for(i=0;i<l;i++)if(divs[i].className=='c8'||divs[i].className=='c9')divs[i].style.display='none';else
  		{
  			divs[i].innerHTML=divs[i].innerHTML.replace(eval("/<[/]?i>/ig"),"");
  			b=false;
  			el=divs[i].getElementsByTagName('p')[0].getElementsByTagName('a')[0];
  			if(el)
  			{
  				el.innerHTML=str_replace(['&rsquo;','&laquo;','&raquo;','&nbsp;'],['’','«','»',nbr],el.innerHTML).replace(eval("/("+str+")/ig"),"<i>$1</i>");
  				if(el.innerHTML.indexOf('<i>')>-1||el.innerHTML.indexOf('<I>')>-1)b=true;
  			}
  			el=divs[i].getElementsByTagName('span')[0];
  			if(el)
  			{
  				el.innerHTML=str_replace(['&rsquo;','&laquo;','&raquo;','&nbsp;'],['’','«','»',nbr],el.innerHTML).replace(eval("/("+str+")/ig"),"<i>$1</i>");
  				if(el.innerHTML.indexOf('<i>')>-1||el.innerHTML.indexOf('<I>')>-1)b=true;
  			}
  			if(b)
  			{
  				divs[i].style.display='';
  				if(cnt%2==0&&cnt>0)divs[i-1].style.display='block';
  				cnt++;
  			}else divs[i].style.display='none';
  		}
  		if(cnt==0)
  		{
  			document.getElementById('nousers').style.display='block';
 	 		document.getElementById('ucnt').innerHTML='0';
			document.getElementById('ucntp').style.display='none';
  		}else
  		{
  			document.getElementById('nousers').style.display='none';
 	 		document.getElementById('ucnt').innerHTML=cnt;
			document.getElementById('ucntp').style.display='';
  		}
	}
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if(isIE6)setProperSizesIE(true);
	return true;
}
*/

function uf_refresh(page,defaultNav)
{
	var from_user=(page-1)*users_on_page,to_user=Math.min(page*users_on_page,users_set.length);
	var cnt=to_user-from_user,cnt2=users_set.length;

	if(cnt2<=users_on_page)
	{
		$('#bnav_client').css('display','none');
		$('#bnav_server').css('display','none');
	}else if(defaultNav)
	{
		$('#bnav_client').css('display','none');
		$('#bnav_server').css('display','block');
	}else
	{
		var pages=Math.ceil(cnt2/users_on_page);
		var html='';
		for(var i=1;i<=pages;i++)
		{
			if(i==page)html+='<span>'+i+'</span>';
			else html+='<a href="#" onclick="uf_refresh('+i+');$(window).scrollTop($(\'#usearch\').position().top-8);return false" class="dashed">'+i+'</a>';
		}
		$('#bnav_server').css('display','none');
		$('#bnav_client').css('display','block').attr('innerHTML',html);
	}
	var html='',user;
	for(var i=from_user;i<to_user;i++)
	{
		user=users_set[i];
		html+='<div class="c'+(8+i%2)+'"></div>'
		html+='<div class="c0">';
		html+='<p class="caption'+(user[2]?'':' silver')+'"><a href="'+users_link+user[3]+'/">'+user[0]+'</a></p>';
		html+='<div class="user">';
		html+='<div class="c1"><a href="'+users_link+user[3]+'/"><img src="'+(user[4]?'/_images/thumb_'+users_thumb_prefix+'_'+user[4]:'/images/noav-big.png')+'" alt="" /></a></div>';
		html+='<div class="c2">';
		if(user[1]||users_cities_index[user[5]])
		{
			html+='<p>';
			if(users_cities_index[user[5]])html+=users_cities_index[user[5]];
			if(users_cities_index[user[5]]&&user[1])html+=', ';
			if(user[1])html+='<span>'+user[1]+'</span>';
			html+='</p>';
		}
		if(users_statuses[user[6]][user[7]])html+='<p>'+users_statuses[user[6]][user[7]]+'</p>';
		html+='<p class="c1">'+users_regday_str[user[7]]+' <strong>'+user[8]+'</strong>';
		if(user[9])
		{
			html+='<br />';
			if(user[9]=='o')html+='<strong>'+users_online_str+'</strong>';
			else html+=users_lvtime_str[user[7]]+' <strong>'+user[9]+'</strong>';
		}
		html+='</p>';
		html+='</div></div></div>';
	}
  		if(cnt==0)
  		{
  			$('#users').css('display','none');
  			document.getElementById('nousers').style.display='block';
 	 		document.getElementById('ucnt').innerHTML='0';
 	 		document.getElementById('ucnt2').innerHTML='0';
			document.getElementById('ucntp').style.display='none';
  		}else
  		{
  			$('#users').css('display','block');
  			document.getElementById('nousers').style.display='none';
 	 		document.getElementById('ucnt').innerHTML=cnt;
 	 		document.getElementById('ucnt2').innerHTML=cnt2;
			document.getElementById('ucntp').style.display='';
  		}
	document.getElementById('users').innerHTML=html;
	if(isIE6)setProperSizesIE(true);
}

function uf_ch2(s)
{
	var uf_ch_cur=trim(s.value);
	if(uf_ch_prev==uf_ch_cur)return false;else uf_ch_prev=uf_ch_cur;
	var nbr=String.fromCharCode(160);
	var str=str_replace(["'",'&rsquo;','&laquo;','&raquo;','&nbsp;'],['’','’','«','»',nbr],preg_quote(uf_ch_cur));
	str=str.replace(/"/g,'(«|»)').replace(eval("/( |"+nbr+")/g"),'( |'+nbr+')').replace(/(³|è)/g,'(³|è)');

	users_set=[];
	if(str=='')
	{
		for(var i=0;i<users_cnt;i++)users_set.push(jQuery.extend({},users[i]));
		uf_refresh(users_page,true);
	}else
	{
		var cur_name,cur_place,cur_user;
		for(var i=0;i<users_cnt;i++)
		{
			cur_name=users[i][0].replace(eval("/("+str+")/ig"),"<i>$1</i>");
			cur_place=users[i][1].replace(eval("/("+str+")/ig"),"<i>$1</i>");
			if(cur_name!=users[i][0]||cur_place!=users[i][1])
			{
				cur_user=jQuery.extend({},users[i]);
				cur_user[0]=cur_name;
				cur_user[1]=cur_place;
				users_set.push(cur_user);
			}
		}
		uf_refresh(1);
	}
}

function users_cities_make_index()
{
	window.users_cities_index=[];
	for(var i=0;i<users_cities.length;i++)users_cities_index[users_cities[i][0]]=users_cities[i][1];
}


function setcookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; path=/; expires="+exdate.toGMTString());
	return true;
}

function ufil_click(n)
{
	setcookie('user_filter',n,3650);
	var els=new Array(document.getElementById('uftags0'),document.getElementById('uftags1'));
	els[1-n].style.display='none';
	els[n].style.display='block';
	var els=new Array(document.getElementById('ufs0'),document.getElementById('ufs1'));
	els[1-n].className='c0';
	els[n].className='c1';
	if(/msie|MSIE 6/.test(navigator.userAgent))document.getElementById('users').innerHTML+='';
}

var isIE6=/msie|MSIE 6/.test(navigator.userAgent),isIE7=/msie|MSIE 7/.test(navigator.userAgent),isIE8=/msie|MSIE 8/.test(navigator.userAgent);
var right_t,right_ip,right_sliders=new Array(),right_els=new Array(),canvas,right_n,right_pos=new Array();
canvas = document.getElementsByTagName((document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY")[0];
function renew_canvas(){if((canvas.scrollTop==0)&&(canvas.scrollLeft==0)&&(document.body&&((document.body.scrollTop!=0)||(document.body.scrollLeft!=0))))canvas=document.body;}
renew_canvas();

function cright(n)
{
	var par=document.getElementById('tright_'+n),par2=document.getElementById('tright_'+n+'_');
	if(isIE6)
	{
		par.style.height=(par.parentNode.offsetHeight+27)+'px';
		el=document.getElementById('tright_bottom_'+n);
		el.style.top=(el.parentNode.offsetHeight-15)+'px';
	}
	if(par2.scrollHeight<=par.offsetHeight+18)
	{
		par2.scrollTop=0;
		document.getElementById('tright_top_'+n).style.display=document.getElementById('tright_bottom_'+n).style.display=document.getElementById('tright_scroll_'+n).style.display='none';
		par2.style.width='100%';
	}
	else
	{
		right_sliders[n].parentNode.style.height=(par.offsetHeight-30)+'px';
        if(isIE7)
        {
        	var prev_sh;
        	do{prev_sh=par2.scrollHeight;par2.scrollTop=par2.scrollHeight;}while(prev_sh!=par2.scrollHeight);
        	par2.scrollTop=0;
        }
		right_sliders[n].style.height=Math.floor(par.offsetHeight/par2.scrollHeight*parseInt(right_sliders[n].parentNode.style.height))+'px';
		par2.style.width='95%';
		par2.scrollTop=Math.round((par2.scrollHeight-par2.offsetHeight)*right_pos[n]);
		right_sliders[n].style.top=Math.round((parseInt(right_sliders[n].parentNode.style.height)-right_sliders[n].offsetHeight)*right_pos[n])+'px';
		document.getElementById('tright_top_'+n).style.display=document.getElementById('tright_bottom_'+n).style.display=document.getElementById('tright_scroll_'+n).style.display='block';
	}
}

function cright_all()
{
	var n=0;
	while(document.getElementById('tright_'+n))
	{
		cright(n);
		n++;
	}
}

function iright(n)
{
	var el,par=document.getElementById('tright_'+n);
	addEvent('mouseover',function(){right_over(n);},par);
	addEvent('mouseout',function(){right_out(n);},par);
	if(isIE6)par.style.height=par.parentNode.offsetHeight+'px';
	el=document.createElement('div');
	el.id='tright_top_'+n;
	el.className='ietrans';
	el.style.display='none';
    el.style.height='15px';
    el.style.width='100%';
    el.style.overflow='hidden';
    el.style.position='absolute';
    el.style.left='0px';
    el.style.top='0px';
    el.style.background='url("/images/right-t'+(isIE6?'-ie':'')+'.png")';
    par.appendChild(el);
	el=document.createElement('div');
	el.id='tright_bottom_'+n;
	el.className='ietrans';
	el.style.display='none';
    el.style.height='15px';
    el.style.width='100%';
    el.style.overflow='hidden';
    el.style.position='absolute';
    el.style.left='0px';
    el.style.bottom='0px';
    el.style.background='url("/images/right-b'+(isIE6?'-ie':'')+'.png")';
    par.appendChild(el);

	el=document.createElement('div');
	el.id='tright_scroll_'+n;
	el.style.display='none';
	el.style.position='absolute';
	el.style.right='0px';
	el.style.top='15px';
	el.style.height=(par.offsetHeight-30)+'px';
	el.style.width='1px';
	el.style.background='#e9e9e9';
	el.innerHTML='<div id="tright_slider_'+n+'" style="position: absolute; width: 9px; font-size: 0px; height: 0px; top: 0px; left: -4px" onmousedown="right_down('+n+',event);return false"><img src="/images/right-st.png" alt="" id="right_st_'+n+'" style="position: absolute; width: 9px; height: 6px; top: -6px; left: 0px" /><img src="/images/right-sb.png" alt="" id="right_sb_'+n+'" style="position: absolute; width: 9px; height: 6px; bottom: -6px; left: 0px" /><div id="right_sm_'+n+'" style="position: absolute; left: 0px; top: 0px; width: 9px; height: 100%; overflow: hidden; background: url(\'/images/right-sm.png\')"></div></div>';
    par.appendChild(el);
    right_sliders[n]=document.getElementById('tright_slider_'+n);
    right_els[n]=document.getElementById('tright_'+n+'_');
    right_pos[n]=0;
    cright(n);
    if(n==0)addEvent('resize',cright_all,window);
}

function addEvent(en,f,el)
{
	el=el||document;
	if(el.addEventListener)el.addEventListener(en,f,false);
	else el.attachEvent('on'+en,f);
}

function removeEvent(en,f,el)
{
	el=el||document;
	if(el.removeEventListener)el.removeEventListener(en,f,false);
	else el.detachEvent('on'+en,f);
}

function addOnLoad(f)
{
	if(typeof window.addEventListener!='undefined')
	    window.addEventListener('load',f,false);
	else if(typeof document.addEventListener!='undefined')
	    document.addEventListener('load',f,false);
	else if(typeof window.attachEvent!='undefined')
	    window.attachEvent('onload',f);
	return true;
}

function right_hl(n)
{
	document.getElementById('right_sm_'+n).style.background='url("/images/right-sam.png")';
	document.getElementById('right_st_'+n).src='/images/right-sat.png';
	document.getElementById('right_sb_'+n).src='/images/right-sab.png';
}

function right_dehl(n)
{
	document.getElementById('right_sm_'+n).style.background='url("/images/right-sm.png")';
	document.getElementById('right_st_'+n).src='/images/right-st.png';
	document.getElementById('right_sb_'+n).src='/images/right-sb.png';
}

function right_event(event){var n=right_n;if(!event)var event=window.event;event.cancelBubble=true;if(event.stopPropagation)event.stopPropagation();right_move(n,event);}

function right_down(n,event)
{
	right_n=n;
	if(!event)var event=window.event;
	if(document.onselectstart===null)document.onselectstart=function(){return false;};
	right_hl(n);
	renew_canvas();
	right_t=event.clientY+canvas.scrollTop;
	right_ip=right_sliders[n].offsetTop;
	addEvent('mousemove',right_event);
	addEvent('mouseup',function(){right_up(n);});
}

function right_up(n)
{
	removeEvent('mousemove',right_event);
	if(document.onselectstart)document.onselectstart=null;
	right_dehl(n);
}

function right_over(n)
{
	right_n=n;
	if(window.addEventListener)window.addEventListener('DOMMouseScroll',right_wheel,false);
	window.onmousewheel=document.onmousewheel=right_wheel;
}

function getLeft(el)
{
	var res=0;
	while(el!=null)
	{
		res+=el.offsetLeft;
		el=el.offsetParent;
	}
	return res;
}

function getTop(el)
{
	var res=0;
	while(el!=null)
	{
		res+=el.offsetTop;
		el=el.offsetParent;
	}
	return res;
}

function right_out(n)
{
	if(window.removeEventListener)window.removeEventListener('DOMMouseScroll',right_wheel,false);
	if(window.event)
	{
		renew_canvas();
		var x=(window.event.clientX+canvas.scrollLeft),y=(window.event.clientY+canvas.scrollTop);
		var el=document.getElementById('tright_'+n);
		var x0=getLeft(el),y0=getTop(el);
		var x1=x0+el.offsetWidth,y1=y0+el.offsetHeight;
		if(x<=x0+5||x>=x1-5||y<=y0+5||y>=y1-5)window.onmousewheel=document.onmousewheel=null;
	}else window.onmousewheel=document.onmousewheel=null;
}

function right_move(n,event)
{
	renew_canvas();
	var cur_t=event.clientY+canvas.scrollTop;
	var dy=cur_t-right_t;
	right_goto(n,right_ip+dy);
}

function right_goto(n,pos)
{
	if(pos<0)pos=0;
	if(pos>parseInt(right_sliders[n].parentNode.style.height)-right_sliders[n].offsetHeight)pos=parseInt(right_sliders[n].parentNode.style.height)-right_sliders[n].offsetHeight;
	right_sliders[n].style.top=pos+'px';
	var el=right_els[n];
	right_pos[n]=right_sliders[n].offsetTop/(parseInt(right_sliders[n].parentNode.style.height)-right_sliders[n].offsetHeight);
	el.scrollTop=Math.round((el.scrollHeight-el.offsetHeight)*right_pos[n]);
}

function right_wheel(event)
{
	var delta=0;
	if(!event)var event=window.event;
	if(event.wheelDelta)delta=event.wheelDelta/120;
	else if(event.detail)delta=-event.detail/3;
	if(delta!=0)
	{
		var n=right_n;
		if(delta>0)right_goto(n,right_sliders[n].offsetTop-4);
		else right_goto(n,right_sliders[n].offsetTop+4);
		if(right_sliders[n].parentNode.style.display!='none')
		{
			if(event.preventDefault)event.preventDefault();
			event.returnValue = false;
		}
	}
}

var tanim_step=8,tanim_time=10,topics=new Array();
if(isIE7)tanim_step=100;

function talks_anim(i,j,h)
{
	var el=topics[i][j],newh;
	if(h==0)
	{
		newh=el.offsetHeight-tanim_step-Math.round((el.offsetHeight-h)/10);
 		if(newh<h)newh=h;
 	}else
 	{
		newh=el.offsetHeight+tanim_step+Math.round((h-el.offsetHeight)/10);
 		if(newh>h)newh=h;
 	}
 	el.style.height=newh+'px';
 	if(newh!=h)setTimeout("talks_anim("+i+","+j+","+h+")",tanim_time);else
 	{
 		var el2=document.getElementById('topic_grad_'+i+'_'+j);
 		el2.parentNode.removeChild(el2);
 		if(h!=0)el.style.height='auto';
 		if(isIE6)setProperSizesIE(true);
 	}
}

function talks_show(i,j,s,tel,mode)
{
	if(document.getElementById('topic_grad_'+i+'_'+j))return false;
	var el=document.getElementById('topic_'+i+'_'+j);
	var el2=el.getElementsByTagName('div')[0];
	var grad=document.createElement('div');
	grad.id='topic_grad_'+i+'_'+j;
	grad.className='ietrans';
	grad.style.position='absolute';
	grad.style.left='0px';
	grad.style.bottom='0px';
	grad.style.width='100%';
	grad.style.height='15px';
	if(!isIE6)grad.style.background="url('/images/right-b.png')";
	grad.style.overflow='hidden';
	el.appendChild(grad);
	var s2=tel.innerHTML;
	tel.onclick=function(){talks_show(i,j,s2,this,1-mode); return false;};
	tel.innerHTML=s;
	if(!topics[i])topics[i]=new Array();
	topics[i][j]=el;
	talks_anim(i,j,(mode==1)?el2.offsetHeight:0);
}

function tlkview_hl(n,el){el.getElementsByTagName('img')[0].src='/images/tv_'+n+'1.png';}
function tlkview_dehl(n,el){el.getElementsByTagName('img')[0].src='/images/tv_'+n+'0.png';}

function talks_hl(el)
{
	if(talks_click_clicked)return false;
	el.style.background="url('/images/topic-bg-a.png')";
 	el.getElementsByTagName('i')[0].style.background="url('/images/topic-l-a.png')";
 	el.getElementsByTagName('b')[0].style.background="url('/images/topic-r-a.png')";
}

function talks_dehl(el)
{
	if(talks_click_clicked)return false;
	el.style.background="url('/images/topic-bg.png')";
 	el.getElementsByTagName('i')[0].style.background="url('/images/topic-l.png')";
 	el.getElementsByTagName('b')[0].style.background="url('/images/topic-r.png')";
}

function talks_red(el)
{
	el.style.background="#d56161";
	el.style.color='white';
 	el.getElementsByTagName('i')[0].style.background="url('/images/topic-l-s.png')";
 	el.getElementsByTagName('b')[0].style.background="url('/images/topic-r-s.png')";
}

function talks_unred(el)
{
	el.style.color='';
	talks_dehl(el);
}

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function talks_correct()
{
	var tw_bg=document.getElementById('tw_bg');
	tw_bg.style.height=tw_bg.parentNode.offsetHeight+'px';
 	document.getElementById('tw_bg_').style.height=(tw_bg.offsetHeight-200)+'px';
 	if(isIE6)document.getElementById('tw_b_stie').style.top=(tw_bg.offsetHeight-100)+'px';
 	var img=tw_bg.getElementsByTagName('img')[0];
 	img.style.height=(tw_bg.offsetHeight-48)+'px';
 	img.style.display='block';
 	if(isIE6)
 	{
 		var twindow=document.getElementById('topic_window');
 		h=twindow.offsetTop+twindow.offsetHeight;
 		if(getDocHeight()<h)document.body.style.height=h+'px';
 	}
 	var c=document.getElementById('cover_'),h=getDocHeight();
 	if(c.offsetHeight<h)c.style.height=h+'px';
}

var talks_click_el,talks_click_clicked=false;
function talks_click(num,cap,el,styles_ver,scode)
{
	if(talks_click_clicked)return false;
	talks_click_el=el;
 	var el=document.createElement('div'),el2=document.createElement('div');
 	el.id='cover';
 	el2.id='cover_';
 	el.style.height=el2.style.height=getDocHeight()+'px';
 	var s='<div align="center"><div id="topic_window"><div id="tw_bg"><div class="c0"></div><div class="c1" id="tw_b_stie"></div><div class="c2" id="tw_bg_"></div><img src="/images/tw.png" alt="" /></div><p class="c0"><a class="x" href="#" onclick="talks_close(); return false">&times;</a></p><div id="tw_"><p class="c1">'+cap+'</p><form action="" method="post" enctype="multipart/form-data" onsubmit="return talks_submit()"><input type="hidden" name="a_'+scode+'" value="1" />';
 	if(num!=0)s+='<input type="hidden" name="tpart" value="'+num+'" />';
 	s+='<dl><dt><label for="tcaption">'+str_cap+'</label></dt><dd><input type="text" maxlength="200" name="tcaption" id="tcaption" value="" class="c0" onkeyup="talks_key(this)" onkeydown="talks_caption_key(event)" /></dd>';
 	s+='<dt><label for="ttext">'+str_text+'</label></dt><dd><textarea name="ttext" id="ttext" rows="20" cols="5"></textarea></dd>';
 	s+='<dt><label for="tfile0">'+str_files+'</label></dt><dd><i class="c0" id="tfiles"><input type="hidden" name="max_file_size" value="5242880" /><input type="file" class="tfile" id="tfile0" size="71" name="tfile0" onchange="tfile_changed(0,this)" /><span id="tfhint">'+str_filemax+'</span></i></dd>';
 	s+='<dt></dt><dd><input type="submit" value="'+str_create+'" class="c1" id="tsbm" disabled="disabled" /></dd>';
 	s+='</dl><div class="clear"></div></form></div></div></div>';
    el.innerHTML=s;
 	el.appendChild(el2);
 	document.getElementById('super').appendChild(el);
	var fck=new FCKeditor('ttext');
	fck.Config["DefaultLanguage"]=str_lang;
	fck.Config["EditorAreaCSS"]='/styles/'+styles_ver+'/fck.css';
	fck.BasePath='/fckeditor/';
	fck.ReplaceTextarea();
	talks_correct();
	talks_click_clicked=true;
	talks_red(talks_click_el);
 	window.scrollTo(0,120);
 	document.getElementById('tcaption').focus();
 	addEvent('keydown',talks_close_key);
}

String.prototype.stripHTML = function()
{
        var matchTag = /<(?:.|\s)*?>/g;
        return this.replace(matchTag, "");
};

function talks_submit()
{
	if(!FCKeditorAPI)return false;
	var fck=FCKeditorAPI.GetInstance('ttext');
	if(trim(fck.GetHTML().stripHTML().replace(/&nbsp;/g,''))=='')
	{
		fck.Focus();
		return false;
	}
    if(window.location.hash=='create_topic'||window.location.hash=='#create_topic')
        window.location.hash='published';
	return true;
}

function talks_close_key(e)
{
	if(!e)var e=window.event;
    if(e.keyCode=="27"&&talks_click_clicked)talks_close();
}

function talks_close()
{
	removeEvent('keydown',talks_close_key);
	talks_click_clicked=false;
	talks_unred(talks_click_el);
	var el=document.getElementById('cover');
	el.parentNode.removeChild(el);
}

function FCKeditor_OnComplete(fck)
{
	fck.SetHTML('<p></p>');
}

function getFileName(fn)
{
	var l1=fn.lastIndexOf('/'),l2=fn.lastIndexOf('\\');
	return fn.substr(Math.max(l1,l2)+1);
}

function talks_check()
{
	if(trim(document.getElementById('tcaption').value)=='')
	{
		document.getElementById('tsbm').disabled=true;
		return false;
	}
	var el,i=0;
	while(el=document.getElementById('tfilec'+i))
	{
		if(el.style.color==''||trim(el.value)=='')
		{
			document.getElementById('tsbm').disabled=true;
			return false;
		}
		i++;
	}
	document.getElementById('tsbm').disabled=false;
}

function tf_focus(el)
{
	if(el.style.color=='')
	{
		el.value='';
		el.style.color='black';
		el.style.fontStyle='normal';
	}
}

function tf_blur(el)
{
	if(trim(el.value)==''||el.style.color=='')
	{
		el.value='';
		el.style.color='';
		el.style.fontStyle='';
		el.value=str_filecap+' '+getFileName(document.getElementById('tfile'+el.id.substr(6)).value);
	}
}

function talks_key(el)
{
	if(trim(el.value)=='')
	{
		el.style.borderColor='';
		document.getElementById('tsbm').disabled=true;
	}else
	{
		el.style.borderColor='#7a97b4';
		talks_check();
	}
}

function talks_caption_key(e)
{
	if(!e)var e=window.event;
	if(e.keyCode==9)
	{
		e.returnValue='';
		if(e.preventDefault)e.preventDefault();
		if(FCKeditorAPI)FCKeditorAPI.GetInstance('ttext').Focus();
	}
}

function tfile_cancel(n)
{
	if(n==0)
	{
	    document.getElementById('tfiles').innerHTML='<input type="hidden" name="max_file_size" value="5242880" /><input type="file" class="tfile" id="tfile0" size="71" name="tfile0" onchange="tfile_changed(0,this)" /><span id="tfhint">'+str_filemax+'</span>';
		talks_correct();
		talks_check();
		return true;
	}
	if(el=document.getElementById('tfclose'))el.parentNode.removeChild(el);
	var el=document.getElementById('tfilei'+n);
	if(el)el.parentNode.removeChild(el);
	var el=document.getElementById('tfilek'+n);
	el.parentNode.removeChild(el);
	tfile_changed(n-1,document.getElementById('tfile'+(n-1)),false);
	talks_correct();
}

function tfile_changed(n,f)
{
	if(f.value=='')return false;
	eval("f.onchange=function(){tf_blur(document.getElementById('tfilec"+n+"'));}");
	var el;
	if(el=document.getElementById('tfhint'))
		el.parentNode.removeChild(el);
	if(el=document.getElementById('tfclose'))
		el.parentNode.removeChild(el);
	el=document.createElement('b');
	el.id='tfclose';
	el.style.top=(f.offsetTop-1)+'px';
	el.innerHTML='<a href="#" onclick="tfile_cancel('+n+'); return false">&times;</a>';
	f.parentNode.appendChild(el);
	if(arguments.length<3)
	{
		document.getElementById('tsbm').disabled=true;
		el=document.createElement('i');
		el.id='tfilei'+n;
		n++;
		if(n==5)el.innerHTML='<input type="text" maxlength="200" class="ctf" value="'+str_filecap+' '+getFileName(f.value)+'" style="margin-bottom: 0px" id="tfilec'+(n-1)+'" name="tfilec'+(n-1)+'" onfocus="tf_focus(this)" onblur="tf_blur(this)" onkeyup="talks_key(this)" />';
		else el.innerHTML='<input type="text" maxlength="200" class="ctf" value="'+str_filecap+' '+getFileName(f.value)+'" id="tfilec'+(n-1)+'" name="tfilec'+(n-1)+'" onfocus="tf_focus(this)" onblur="tf_blur(this)" onkeyup="talks_key(this)" /><i id="tfilek'+n+'"><input type="hidden" name="max_file_size" value="5242880" /><input type="file" class="tfile" id="tfile'+n+'" size="71" name="tfile'+n+'" onchange="tfile_changed('+n+',this)" /></i>';
		f.parentNode.appendChild(el);
	}else
	{
		el=document.getElementById('tfilei'+n);
		n++;
		var el2=document.createElement('i');
		el2.id='tfilek'+n;
		el2.innerHTML='<input type="hidden" name="max_file_size" value="5242880" /><input type="file" class="tfile" id="tfile'+n+'" size="71" name="tfile'+n+'" onchange="tfile_changed('+n+',this)" />';
		el.appendChild(el2);
		talks_check();
	}
	talks_correct();
}

var slider_ta,slider_ta_cover,slider_sl,slider_x,slider_y,slider_minw,slider_minh,slider_maxw,slider_maxh;

function slider(ta,ta_cover,sl,minw,minh,maxw,maxh,e)
{
	document.body.style.cursor='nw-resize';
	slider_ta=document.getElementById(ta);
	if(ta_cover)
	{
		slider_ta_cover=document.getElementById(ta_cover);
		slider_ta_cover.style.display='block';
	}else slider_ta_cover=false;
	slider_sl=sl;
	slider_minw=minw;
	slider_minh=minh;
	slider_maxw=maxw;
	slider_maxh=maxh;
	if(!e)var e=window.event;
	if(e.preventDefault)e.preventDefault();
	e.returnValue=false;
	renew_canvas();
	slider_x=e.clientX+canvas.scrollLeft;
	slider_y=e.clientY+canvas.scrollTop;
    addEvent('mousemove',slider_move_);
    addEvent('mouseup',slider_up);
}

function slider_up()
{
	removeEvent('mouseup',slider_up);
	removeEvent('mousemove',slider_move_);
	document.body.style.cursor='';
	if(slider_ta_cover)slider_ta_cover.style.display='none';
	if(/msie|MSIE 6/.test(navigator.userAgent))setProperSizesIE(true);
}

function slider_move_(e)
{
	if(!e)var e=window.event;
	if(e.preventDefault)e.preventDefault();
	e.returnValue=false;
	slider_move(e.clientX,e.clientY);
	if(isIE6)
	{
		slider_ie(slider_ta);
		setProperSizesIE(true);
	}
}

function slider_move(x,y)
{
	renew_canvas();
	x+=canvas.scrollLeft;
	y+=canvas.scrollTop;
	var neww=(slider_ta.offsetWidth)+x-slider_x,newh=(slider_ta.offsetHeight)+y-slider_y;
	if(neww<slider_minw)
	{
		neww=slider_minw;
		x=neww-(slider_ta.offsetWidth)+slider_x;
	}else if(neww>slider_maxw)
	{
		neww=slider_maxw;
		x=neww-(slider_ta.offsetWidth)+slider_x;
	}
	slider_ta.style.width=neww+'px';
	slider_sl.style.left=(slider_sl.offsetLeft+x-slider_x)+'px';
	slider_x=x;
	if(newh<slider_minh)
	{
		newh=slider_minh;
		y=newh-(slider_ta.offsetHeight)+slider_y;
	}else if(newh>slider_maxh)
	{
		newh=slider_maxh;
		y=newh-(slider_ta.offsetHeight)+slider_y;
	}
	slider_ta.style.height=newh+'px';
	slider_sl.style.top=(slider_sl.offsetTop+y-slider_y)+'px';
	slider_y=y;
}

function slider_dbl(ta,sl,minw,minh,maxw,maxh)
{
	ta=document.getElementById(ta);
	if(ta.offsetWidth==maxw&&ta.offsetHeight==maxh)
	{
		sl.style.left=(sl.offsetLeft+minw-(ta.offsetWidth))+'px';
		ta.style.width=minw+'px';
		sl.style.top=(sl.offsetTop+minh-(ta.offsetHeight))+'px';
		ta.style.height=minh+'px';
	}else
	{
		sl.style.left=(sl.offsetLeft+maxw-(ta.offsetWidth))+'px';
		ta.style.width=maxw+'px';
		sl.style.top=(sl.offsetTop+maxh-(ta.offsetHeight))+'px';
		ta.style.height=maxh+'px';
	}
	if(isIE6)
	{
		slider_ie(ta);
		setProperSizesIE(true);
	}
}

function slider_ie(div)
{
	var iframe=div.getElementsByTagName('iframe')[0];
	iframe.style.height=iframe.parentNode.style.height=document.getElementById('comtext_cover').style.height=div.offsetHeight+'px';
}

function donation_check()
{
	var b=(trim(document.donation_frm.amount.value).match(/^\d+([\.,]\d{1,2})?$/));
	document.getElementById('d_amount').style.borderColor=(b?'':'#D56161');
	var btn=$('#donation_sbm');
	if(b)
	{
		btn.css({'opacity':1,'cursor':'pointer'}).get(0).disabled=false;
	}else
	{
		btn.css({'opacity':0.5,'cursor':'default'}).get(0).disabled=true;
	}
}

function donation_send()
{
	var sb=document.getElementById('donation_sbm');
	if(sb.disabled||sb.style.display=='none')return;
/*	var iframe=document.createElement('iframe');
	iframe.style.display='none';
	iframe.name='donation_iframe';
	iframe.id='donation_iframe';
	document.body.appendChild(iframe);
*/
	iframe=document.getElementById('donation_iframe');
	addEvent('load',function(){
		var content=iframe.contentWindow.document.body.innerHTML;
		if(content=='')return;
		content=content.split('|||||');
		document.donation_paypal_form.amount.value=content[0];
		document.donation_paypal_form.currency_code.value=content[1];
		document.donation_paypal_form.submit();
	},iframe);

	document.donation_frm.target='donation_iframe';
	var gif=document.getElementById('donation_gif');
	gif.style.left=Math.round((sb.offsetWidth-16)/2)+(isIE6||isIE7?40:0)+'px';
	gif.style.top=Math.round((sb.offsetHeight-16)/2)+'px';
	sb.parentNode.style.height=sb.parentNode.offsetHeight+'px';
	sb.style.display='none';
	gif.style.display='block';
	document.getElementById('stupid_paypal_return_field').value=(trim(document.donation_frm.name.value)!='')?'http://matholymp.org.ua/about/donation/?thank_you':'http://matholymp.org.ua/about/donation/?thank_you&amp;no_name';
	document.donation_frm.submit();
}

function donation_currencyChanged(s)
{
	$(s).parent().find('p.c_cur').attr('innerHTML',s.value=='USD'?'$':'ˆ');
}

function show_hide(elid,a,showstr,hidestr,tagToUse)
{                     
    if(tagToUse==undefined)
        tagToUse = 'div';
	var el=$('#'+elid),state=el.data('mathol_state')||'first';
	if(state=='first')
	{                 
		var firstChild=el.find('>:first-child'),lastChild=el.find('>:last-child'),prev=el.prev(),next=el.next();
		if(!prev.attr('tagName'))prev=false;
		if(!next.attr('tagName'))next=false;
		var prevMargin=prev?parseInt(el.prev().css('margin-bottom')):0;
		var nextMargin=next?parseInt(el.next().css('margin-top')):0;

		var height=$(document).height();
		el.css({'display':'block','overflow':'hidden','height':'0px'});
		el.data('mathol_margin',$(document).height()-height);
		el.css('margin-bottom','-'+el.data('mathol_margin')+'px');

		firstChild.css('margin-top',Math.max(0,parseInt(firstChild.css('margin-top'))-prevMargin)+'px');
		lastChild.css('margin-bottom',Math.max(0,parseInt(lastChild.css('margin-bottom'))-nextMargin)+'px');
		el.wrapInner('<'+tagToUse+' id="'+elid+'_in" style="overflow:hidden"></'+tagToUse+'>');
        el.append('<'+tagToUse+' class="show_hide_grad"></'+tagToUse+'>');
		state='hidden';
	}   
	el_in=$('#'+elid+'_in');
	switch(state)
	{
		case 'hidden':                          
			el.data('mathol_state','busy');
			if(hidestr!==false)
				$(a).attr('innerHTML',hidestr);  
            else
                $(a).addClass('c_opened');  
			el.animate({'height':el_in.height()+15+'px','margin-bottom':'-15px'},{'duration':450,'complete':function(){                
				el.find(tagToUse+'.show_hide_grad').css('display','none');
				el.css({'height':'auto','margin-bottom':'0px'});
				if(isIE6)setProperSizesIE(true);
				el.data('mathol_state','visible');
			}});
			break;
		case 'visible':
			el.data('mathol_state','busy');
			el.css({'height':el_in.height()+15+'px','margin-bottom':'-15px'});
			el.find(tagToUse+'.show_hide_grad').css('display','block');
			if(showstr!==false)
				$(a).attr('innerHTML',showstr);
            else
                $(a).removeClass('c_opened');  
			el.animate({'height':'0px','margin-bottom':'-'+el.data('mathol_margin')+'px'},{'duration':300,'complete':function(){
				if(isIE6)setProperSizesIE(true);
				el.data('mathol_state','hidden');
			}});
			break;
	}
}

function tablePrinterBeautify(id,sheader)
{                                  
	var table=$('#'+id),img=table.find('img.c_print_img');
	if(sheader)
	{                               
		img.css('opacity',0.2);
		if(isIE6)$(document).ready(function(){
			img.animate({'opacity':0.2},250); // Semi-transparent PNG JS makes img’s opacity 1
		});
		table.mouseenter(function(){         
			img.stop();
			img.animate({'opacity':0.75},100);
		});
		table.mouseleave(function(){
			img.stop();
			img.animate({'opacity':0.2},100);
		});
		img.mouseenter(function(){
			img.stop();
			img.css('opacity',1);
		});
		img.mouseleave(function(){
			img.stop();
			img.css('opacity',0.75);
		});
	}else
	{                               
		table.mouseenter(function(){     
			img.stop();
			img.css({'visibility':'visible','opacity':0}).animate({'opacity':1},100);
		});
		table.mouseleave(function(){
			img.stop();
			img.animate({'opacity':0},100);
		});
		img.mouseenter(function(){
			img.stop();
			img.css('opacity',1).attr('src','/images/printer-a.png');
		});
		img.mouseleave(function(){
			img.stop();
			img.attr('src','/images/printer.png');
		});
		if(isIE6)
		{
			img.mousemove(function(){
				img.stop();
				img.css('opacity',1).attr('src','/images/printer-a.png');
			});
		}
	}
}

function insts_getMarkerColor(type)
{
    return (type == 0 ? 'red' : 'blue');
}

function insts_initMap()
{
    window.insts_map_types = [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE];
    preloadImages(['/images/institutions/markers/red-a.png', '/images/institutions/markers/blue-a.png']);
    
    var infoWindowImages = ['arrow.png', 'shadow-bottom.png', 'shadow-bottom-left.png', 'shadow-bottom-right.png', 'shadow-left.png', 'shadow-right.png', 'shadow-top.png', 'shadow-top-left.png', 'shadow-top-right.png'];
    for (var i = 0; i < infoWindowImages.length; i++)
        infoWindowImages[i] = '/images/institutions/infowindow/' + infoWindowImages[i];
    preloadImages(infoWindowImages);
    
    window.insts_map = new google.maps.Map(document.getElementById('map'), {
        zoom: 11,
        center: new google.maps.LatLng(50.45, 30.5),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        }
    });
    $('div.insts_mapTop').css('display', 'block');
    google.maps.event.addListener(insts_map, 'maptypeid_changed', function() {
        var index = insts_map_types.indexOf(insts_map.getMapTypeId());
        if (index == -1)
            $('p.insts_mapControl span').removeClass('c1');
        else if (! $('#insts_mapType' + index).hasClass('c1'))
        {
            $('p.insts_mapControl span').removeClass('c1');
            $('#insts_mapType' + index).addClass('c1');
        }
    });        
    for (var i = 0; i < insts_markers.length; i++)
    {
        var color = insts_getMarkerColor(insts_markers[i][2]);
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(insts_markers[i][0], insts_markers[i][1]), 
          map: insts_map,
          icon: '/images/institutions/markers/' + color + '.png',
          shadow: new google.maps.MarkerImage('/images/institutions/markers/shadow.png', null, null, new google.maps.Point(1, 15))
        });
        google.maps.event.addListener(marker, 'mouseover', (function(marker, color){
            return function() {
                marker.setIcon('/images/institutions/markers/' + color + '-a.png');
            }
        })(marker, color));
        google.maps.event.addListener(marker, 'mouseout', (function(marker, color){
            return function() {
                marker.setIcon('/images/institutions/markers/' + color + '.png');
            }
        })(marker, color));        
        google.maps.event.addListener(marker, 'click', (function(marker, type, id){
            return function() {
                if (window.insts_infoWindow && ! window.insts_infoWindow.wasClosed)
                {
                    insts_infoWindow.close();
                    insts_infoWindow = null;
                    if (insts_infoWindowId == id)
                        return;
                }
                var contentInfo = insts_getInfoWindowContent(id);
                window.insts_infoWindow = new BFInfoWindow({content: contentInfo['content']}, contentInfo['width'], contentInfo['height'], contentInfo['arrowPosition']);
                window.insts_infoWindowType = type;
                window.insts_infoWindowId = id;
                insts_infoWindow.open(insts_map, marker);
            }
        })(marker, insts_markers[i][2], insts_markers[i][3]));
        insts_markers[i] = [marker, insts_markers[i][2], insts_markers[i][3]];
    }
}

function insts_setMapType(type)
{
    insts_map.setMapTypeId(insts_map_types[type]);
}

function insts_setInstType(type)
{
    if (window.insts_currentType == undefined)
        window.insts_currentType = -1;
    if (insts_currentType != type)
    {
        insts_currentType = type;
        if (type == -1)        
        {
            $('div.insts_institution').css('display', 'block');
            for (var i = 0; i < insts_markers.length; i++)
                insts_markers[i][0].setMap(insts_map);
        }
        else
        {
            $('div.insts_institution').css('display', 'none');
            $('div.insts_instType' + type).css('display', 'block');

            if (window.insts_infoWindow && ! window.insts_infoWindow.wasClosed && insts_infoWindowType != type)
            {
                insts_infoWindow.close();
                insts_infoWindow = null;
            }
            
            for (var i = 0; i < insts_markers.length; i++)
                insts_markers[i][0].setMap(insts_markers[i][1] == type ? insts_map : null);            
        }
        
        $('p.insts_types span').removeClass('c1');
        $('#insts_instType' + (type == -1 ? 'All' : type)).addClass('c1');
    }
}

function insts_getInfoWindowContent(id)
{
    var div = $('#insts_inst' + id);
    var name = div.find('.c_name').attr('innerHTML');
    var link = div.find('.c_link').attr('href');
    var address = div.find('.c_address').attr('innerHTML');
    var img = div.find('.c_img img');
    if (img.length == 0)
        img = false;
    var result = {};
    div = $('<div></div>');
    div.attr('innerHTML', '<div class="map_infoWindow_content"></div>');
    var contentDiv = div.find('.map_infoWindow_content');
    div.css('left', '-1000px').css('top', '-1000px').css('position', 'absolute').css('visibility', 'hidden');
    div.appendTo(document.body);
    if (img)
    {
        var imgWidth = img.attr('width');
        var imgHeight = img.attr('height');
        div.width(322 + imgWidth);
        contentDiv.attr('innerHTML', '<p class="insts_infoWindow_caption" style="margin-left:' + (22 + imgWidth) + 'px"><a href="' + link + '">' + name + '</a></p><p class="insts_infoWindow_address" style="margin-left: ' + (22 + imgWidth) + 'px">' + address + '</p>');
        if (div.height() < imgHeight + 32)
            div.height(imgHeight + 32);
        contentDiv.find('.insts_infoWindow_caption a').append('<img src="' + img.attr('src') + '" alt="" class="insts_infoWindow_img" style="top:' + Math.floor((div.height() - imgHeight - 12) / 2) + 'px" />');
        result['arrowPosition'] = 16 + Math.floor(imgWidth / 2);        
    } else
    {
        div.width(300);
        contentDiv.attr('innerHTML', '<p class="insts_infoWindow_caption"><a href="' + link + '">' + name + '</a></p><p class="insts_infoWindow_address">' + address + '</p>');
        result['arrowPosition'] = 80;
    }
    result['content'] = contentDiv.attr('innerHTML');
    result['width'] = div.width();
    result['height'] = div.height();
    div.remove();
    return result;
}

function inst_initMap(lat, lng, type)
{
    window.inst_map_types = [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE];
    
    window.inst_map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        }        
    });
    google.maps.event.addListener(inst_map, 'maptypeid_changed', function() {
        var index = inst_map_types.indexOf(inst_map.getMapTypeId());
        if (index == -1)
            $('p.inst_mapControl span').removeClass('c1');
        else if (! $('#inst_mapType' + index).hasClass('c1'))
        {
            $('p.inst_mapControl span').removeClass('c1');
            $('#inst_mapType' + index).addClass('c1');
        }
    });        
    var color = insts_getMarkerColor(type);
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, lng), 
      map: inst_map,
      icon: '/images/institutions/markers/' + color + '.png',
      shadow: new google.maps.MarkerImage('/images/institutions/markers/shadow.png', null, null, new google.maps.Point(1, 15))
    });    
}

function inst_setMapType(type)
{
    inst_map.setMapTypeId(inst_map_types[type]);
}

function inst_participatedToggle(id, link)
{
    if (link.sq_busy)
        return;
    link.sq_busy = true;
    var unbusy = function() {
        link.sq_busy = false;
    };
    var div = $('#inst_participated_list' + id);
    if (link.sq_opened)
    {
        link.sq_opened = false;
        link.innerHTML = inst_toggle_showLabel;
        div.slideUp(200, unbusy);
    } else
    {
        link.sq_opened = true;
        link.innerHTML = inst_toggle_hideLabel;
        div.slideDown(200, unbusy);
    }   
}

function main_messages_showAllTags(link)
{
    if (link.sq_opened)
        return;
    link.sq_opened = true;    
    var div = $('#main_messagesTagContainer');
    div.animate({height: 0}, {duration: 150, complete: function(){   
        div.find('p.c0').css('display', 'none');
        div.find('p.c1').css('display', 'block');
        div.animate({height: div.find('p.c1').height()}, {duration: 200, complete: function(){
            div.css('height', 'auto');
        }});        
    }});
}

function addCreateTopicOnLoadListener()
{
    addOnLoad(function() {
        if (window.location.hash == 'create_topic' || window.location.hash == '#create_topic')
            $('#create_topic_link').click();
    });
}

function survey_radioClicked(nm, id, code)
{
    var survey = $('#' + nm);
    survey.find('button.c_submit').attr('disabled', $('#' + nm + '_' + id + '_tr').hasClass('c_selected'));
    if (window.survey_data == undefined)
        window.survey_data = {};
    survey_data[nm] = [id, code];
}

function survey_send(sid, nm, user, domain)
{
    if (! window.survey_data || ! survey_data[nm])
        return;
    var survey = $('#' + nm);
    var radios = survey.find('table.survey td.c0 input');
    radios.attr('disabled', true);
    var button = survey.find('button.c_submit');
    var sending = survey.find('img.c_sending');
    var bwidth = survey.find('span.c_submitWidthTest').position().left;
    if (bwidth == 0)    // IE
        bwidth = button.width();
    var bheight = survey.find('div.c_submitContainer').height();
    sending.css('left', Math.floor((bwidth - sending.width())/2) + 'px');
    sending.css('top', Math.floor((bheight - sending.height())/2) + 'px');
    button.css('visibility', 'hidden');
    button.attr('disabled', true);
    sending.css('display', 'block');
    var item = survey_data[nm][0];
    var code = survey_data[nm][1];
    var url = domain + '?global_survey=' + sid + '&global_survey_item=' + item + '&global_survey_code=' + code + '&global_survey_user=' + user + '&rnd=' + Math.random();
    $.ajax({
        url: url,
        success: function(data){   
            if (data != 'ok')
                return;
            sending.css('display', 'none');       
            button.css('visibility', 'visible');        
            radios.attr('disabled', false);
            survey.find('table.survey tr').removeClass('c_selected');
            $('#' + nm  + '_' + item + '_tr').addClass('c_selected');
        }
    });
}

function about_section(section)
{
    var toY = (section == '' ? 0 : $('#section_' + section).offset().top);
    toY = Math.max(0, Math.min(toY, $(document).height() - $(window).height()));
    $('html, body').animate({'scrollTop': toY}, {'duration': 600});
}

function about_participants_switch(to)
{
    var all = ['administrators', 'students'];
    for (var i = 0; i < all.length; i++)
    {
        var span = $('#about_participants_switch_' + all[i]).closest('span');
        var div = $('#about_participants_' + all[i]);
        if (all[i] == to)
        {
            span.addClass('c1');
            div.css('display', 'block');
        }
        else
        {
            span.removeClass('c1');
            div.css('display', 'none');
        }
    }
}
