function popup(url, rd, res, maxsize, scrollbars) {
    if (typeof (ipopup) != 'undefined') {
        var id = ipopup(url, '', window._popupwidth, window._popupheight);
        /*
        var o = $1('iframe' + id);
        o.contentWindow.closeme = function() { windowClose(id); };
        */
        if (typeof (window.popups) == 'undefined')
            window.popups = [];
        window.popups.push(id);
        window.myclosepopup = function() { windowClose(window.popups.pop()); };
        //window.onscroll = function(e) { if (typeof (e) == 'undefined') e = event; e.preventDefault(); return false; };
        //Event.observe(window, 'scroll', function(e) { window.scrollTo(0, 0); });
    }
    else
        popup_real(url, rd, res, maxsize, scrollbars);
}

function popup_real(url, rd, res, maxsize, scrollbars)
{
	var width = _popupwidth;
	var height = _popupheight;
	//var width = (maxsize ? screen.width - 20 : _popupwidth);
	//var height = (maxsize ? screen.height - 100 : _popupheight);
	//var width = (maxsize ? 790 : 700); //(maxsize ? screen.width - 20 : 700);
	//var height = 550; //(maxsize ? screen.height - 100 : 550);
	var off = 0;
	try {
        if (window.opener) {
	        off += 30;
	        if (window.opener.opener)
		        off += 30;
        }
	} catch (e) { }
	
	//window.child = window.open(url, '', "width="+width+",height="+height+",scrollbars=no,dependent=yes,resizable=no,status=no,top="+((window.screen.height-height)/2+off).toString()+",left="+((window.screen.width-width)/2+off).toString()+"");

	if (typeof(res) == 'undefined' || !res)
		res = "no";
	else
		res = "yes";
	res = "yes"; // !!
    if (typeof(scrollbars) == 'undefined')
        scrollbars = 'no';
    if (scrollbars != '')
        scrollbars = 'scrollbars=' + scrollbars + ',';

//alert("width="+width+",height="+height+"," + scrollbars+"dependent=yes,resizable="+res+",status=no,top="+((window.screen.height-height)/2+off).toString()+",left="+((window.screen.width-width)/2+off).toString()+"");

	window.child = window.open(url, '', "width="+width+",height="+height+"," + scrollbars+"dependent=yes,resizable="+res+",status=no,top="+((window.screen.height-height)/2+off).toString()+",left="+((window.screen.width-width)/2+off).toString()+"");
	window.child.focus();
	//window.child.cspopup = true;
	window.child.rd = rd;
}

function freepopup(url)
{
    url = 'frame.aspx?page=' + escape(url);
    popup_real(url, false, true);
}
function chatpopup(params)
{
    var width = _popupwidth;
	var height = _popupheight;
	var off = 0;
	/* callee...
	if (window.opener) {
		off += 30;
		if (window.opener.opener)
			off += 30;
	}
	*/
	window.chatwin = window.open('chat.ashx/Default.html?' + params, 'dexchattrickywin', "width="+width+",height="+height+",scrollbars=no,dependent=yes,resizable=yes,status=no,top="+((window.screen.height-height)/2+off).toString()+",left="+((window.screen.width-width)/2+off).toString()+"");
}

var on_closewindow;
function exitpopup(ask, parenturl)
{
	if (ask && formdata != '' && formdata != getformdata())
		if (!confirm(_('formdata_changed')))
			return;
	try {
		if (window.opener)
			window.opener.focus();
	} catch (e)
	{
	}
	if (typeof (on_closewindow) != 'undefined')
	    on_closewindow();
	else if (window.opener) {
	    // popup
	    window.close();
	}
	else {
	    // iframe
	    try {
	        if (window.parent && parenturl) {
	            window.parent.location.href = parenturl;
	        }
	        else if (window.parent && window.parent.refreshParentOnClose && window.parent.refresher) {
	            window.parent.refreshParentOnClose = false;
	            window.parent.refresher();
	        }
	        else
	            window.parent.myclosepopup();
	    } catch (e) {
	    }
	}
}

function returnpopup(retval)
{
	var wo = window.opener;
	if (wo && wo.popupcallback) {
		var ret = retval.replace("\"", "\\\"").replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r") 
		wo.setTimeout('window.popupcallback("' + ret + '");', 10);
		wo.focus();
	}
	window.close();	
}

/*
var percent = 0;
function anim()
{
	if (percent > 200)
		percent = 200;
	var o = document.getElementById("done");
	o.style.width = (percent <= 100 ? percent : 200-percent) * 3 + "px";
	o.style.marginLeft = (percent <= 100 ? 0 : percent - 100) * 3 + "px";
	o.style.marginRight = (percent <= 100 ? 100-percent : 0) * 3 + "px";
	if (percent < 200) {
		window.setTimeout("anim()", 20);
	}
	percent += 4;
}
*/
function anim()
{
	var o = document.getElementById('doneanim');
	if (o)
	{
	    var t = window.theme;
	    if (typeof(t) == 'undefined')
	        t = '';
		o.style.backgroundImage = 'url(res/theme' + t + '/bkg_popuphead_done.gif)';
		o.style.backgroundPosition = 'left bottom';
	}
}

var formdata = '';
function getformdata()
{
	var fi, ii;
	var s = '';
	for (fi = 0; fi < document.forms.length; fi++) {
		var f = document.forms[fi];
		try {
		if (f.name.substring(0,2) == '__')
			continue;
		} catch (e) { }
		for (ii = 0; ii < f.elements.length; ii++) {
			var e = f.elements[ii];
			if (e.name == '')
				continue;
			if (e.type == "checkbox" || e.type=="radio")
				if (e.checked)
					s += '&' + escape(e.name) + '=' + escape(e.value);
				else
					s += '&' + escape(e.name) + '=';
			else
				s += '&' + escape(e.name) + '=' + escape(e.value);
		}
	}
	return s;
}
function saveformdata()
{
	formdata = getformdata();
}
function go(url)
{
	if (formdata != '' && formdata != getformdata())
		if (!confirm(_('formdata_changed')))
			return;
	location.href = url;
}
function safesubmit(f)
{
	if (formdata != '' && formdata != getformdata())
		if (!confirm(_('formdata_changed')))
			return;
	f.submit();	
}

function entersubmit(f, ev)
{
	if (typeof(ev) == 'undefined')
		ev = window.event;
	if (ev && ev.keyCode == 13) {
		submitform(f);
	}
}

function submitform(i, doit, param, param2) {
    return submitform_real(false, i, doit, param, param2);
}

function submitform_req(i, doit, param, param2) {
    return submitform_real(true, i, doit, param, param2);
}

function submitform_real(req, i, doit, param, param2) {
    var f = (typeof (i) == 'object' ? i : document.forms[i]);

    for (var i = 0; i < f.elements.length; i++) {
        if (f.elements[i].className && f.elements[i].className.match(/\brequired\b/i)) {
            if (f.elements[i].value == '') {
                if (req) {
                    alert(_('missingrequiredfields'));
                    return;
                }
                else {
                    if (confirm(_('withoutrequiredfield'))) {
                        break;
                    }
                    else {
                        try { f.elements[i].focus(); } catch (e) { }
                        return;
                    }
                }
            }
        }
    }

    if (doit) {
        var d = f.elements['doit'];
        if (d) {
            d.value = doit;
        }
        var d = f.elements['doitparam'];
        if (param && d) {
            d.value = param;
        }
        var d = f.elements['doitparam2'];
        if (param2 && d) {
            d.value = param2;
        }
    }
    var res = true;
    if (typeof (f.onsubmit) != 'undefined' && f.onsubmit) {
        res = f.onsubmit();
    }
    if (typeof (res) == 'undefined' || res)
        f.submit();
    return;
}

function submitform2(sbn, i, doit, param, param2)
{
    var o = document.getElementById(sbn);
    if (o)
    {
        o.innerHTML = '...';
        o.disabled = true;
    }
    return submitform(i, doit, param, param2);
}

function submitform3(confirmtxt, sbn, i, doit, param, param2) {
    if (!confirm(confirmtxt)) {
        return;
    }
    var o = document.getElementById(sbn);
    if (o) {
        o.innerHTML = '...';
        o.disabled = true;
    }
    return submitform(i, doit, param, param2);
}

// used by quiz
function quizmultinoanswer(o)
{
	var nam = o.name.replace(/^([^_]+_).*/, '$1');
	var b = (nam != o.name);
	if (!o.checked)
		return true;
	var ns = nam.length;
	var i, cbs = document.getElementsByTagName('INPUT');
	for (i = 0; i < cbs.length; i++) {
		var c = cbs.item(i);
		if (!c || !c.type || c.type!='checkbox' || !c.name || c.name.substr(0, ns) != nam)
			continue;
		if (c.name == nam && b) {
			c.checked = false;
		} else if (c.name != nam && !b) {
			c.checked = false;
		}
	}
	return true;
}

function inputnumber(i, ev, min, max)
{
	if (i.value == '')
		return true;
	var n = new Number(i.value);
	if (isNaN(n)) {
		alert(_('badnumber'));
		i.focus();
		return false;
	}
	n = n + 0;
	if ((typeof(min) != 'undefined' && n < min) || (typeof(max) != 'undefined' && n > max))
	{
	    alert(_('numoutofrange'));
		i.focus();
		return false;
	}
	i.value = n.toString();
	return true;
}

function showhide(id, imgid, newstate)
{
    showhide_real(id, imgid, newstate);
}
function showhide_real(id, imgid, newstate)
{
	var o = document.getElementById(id);
	if (o)
	{
	    if (typeof newstate == 'undefined')
		    o.style.display = (o.style.display == 'none' ? '' : 'none');
		else
		    o.style.display = newstate ? '' : 'none';
		
		if (imgid == true)
			imgid = 'icon_' + id;
		if (imgid)
		{
			var io = document.getElementById(imgid)
			if (io)
			{
				var s = new String(io.src);
				io.src = s.replace(/_[01](f?)\./, '_' + (o.style.display == 'none' ? '0' : '1') + '.');
			}
		}
		
		return o.style.display == 'none' ? -1 : 1;
	}
	else
	{
	    return 0;
	}
}

function getTop2(o, includeself)
{
	var v = 0;
	if (o && includeself)
	    v += o.offsetHeight;
	while (o) {
		v += o.offsetTop;
		o = o.offsetParent;
	}
	return v;
}
function getLeft2(o, includeself)
{
	var v = 0;
	if (o && includeself)
	    v += o.offsetWidth;
	while (o) {
		v += o.offsetLeft;
		o = o.offsetParent;
	}
	return v;
}

function showhide2(id, parent, action)
{
	var o = document.getElementById(id);
	if (o) {
	    var doshow = (typeof(action) == 'undefined' ? o.style.display == 'none' : (action == 'show'));
		o.style.display = (doshow ? '' : 'none');
		if (doshow && parent)
		{
		    o.style.left = getLeft2(parent, false);
		    o.style.top = getTop2(parent, true);
		}
	}
}

		var menutrack = { id: '', state: 0, timer: '' };

		function menushow(id, parent)
		{
			if (menutrack.state != 0)
				menuhide(menutrack.id);
			menutrack.id = id;
			menutrack.state = 1;

            showhide2(id, parent, 'show');
		}

		function menuhide(id)
		{
			menutrack.id = '';
			menutrack.state = 0;

            showhide2(id, parent, 'hide');
		}

		function menuover(id)
		{
			menutrack.state = 3;
			//window.status = menutrack.state;
		}

		function menuout(id)
		{
			menutrack.state = 2;
			//window.status = menutrack.state;
			if (menutrack.timer == '')
				menutrack.timer = window.setTimeout('menutimer();', 500);
		}

		function menutimer()
		{
			if (menutrack.state == 2)
				menuhide(menutrack.id);
			menutrack.timer = '';
		}


function hasclass(o, cn)
{
		s = new String(o.className);
		if (!s.match(new RegExp('\\b' + cn + '\\b')))
		{
			return false;
		}
		else
		{
		    return true;
		}
}

function addclass(o, cn)
{
		if (!hasclass(o, cn))
		{
			o.className = s + ' ' + cn;
    		//window.status = ('[ADD] old: ' + s + ' new: ' + o.className);
			return true;
		}
		else
		{
		    return false;
		}
}

function remclass(o, cn)
{
		s = new String(o.className);
		o.className = s.replace(new RegExp('\\s*\\b' + cn + '\\b|' + '\\b' + cn + '\\b\\s*', 'g'), '');
		//window.status = ('[REMOVE] old: ' + s + ' new: ' + o.className);
}

function htmlencode(s)
{
	s = new String(s);
	s = s.replace(/&/g, '&amp;');
	s = s.replace(/</g, '&lt;');
	s = s.replace(/>/g, '&gt;');
	return s;
}

function helppopup(url,ctx)
{
	var width = 820;
	var height = 650;
	var off = 0;
	/*
	    if (window.opener) {
		    off += 30;
		    if (window.opener.opener)
			    off += 30;
	    }
	*/
	if (typeof ctx != 'undefined')
		url += '&ctx=' + ctx;
	else if (typeof helpcontext != 'undefined')
		url += '&ctx=' + helpcontext;
	else
	    url += '&ctx=0';

	var res = "yes";
	window.helpchild = window.open(url, '', "width="+width+",height="+height+",scrollbars=yes,dependent=yes,resizable="+res+",status=no,top="+((window.screen.height-height)/2+off).toString()+",left="+((window.screen.width-width)/2+off).toString()+"");
	window.helpchild.focus();
}

function refreshparent() {
    try {
        if (window.parent && window.parent != window) {
            window.parent.refreshParentOnClose = true;
            return true;
        }
    } catch (e) { }
    try {
		if (window.opener) {
			if (window.opener.refresher) {
				window.opener.refresher();
				if (window.opener.opener) {
					if (window.opener.opener.refresher) {
						window.opener.opener.refresher();
						return true;
					}
				}
			}
		}
	} catch (e) { }
	return false;
}

function lptree_chgrp(lp)
{
    var o = document.getElementById('lp_' + lp);
    var box = document.getElementById('lp_chgrp');
    var ogrp = document.getElementById('LPGRP_' + lp);
    var f = document.getElementById('flpchgrp');
    if (!o || !box || !ogrp || !f)
        return;
    if (addclass(o, 'selected'))
    {
        if (box.style.display != 'none')
        {
            remclass(o, 'selected');
        }
        else
        {
            f.elements['newname'].value = ogrp.value;
            f.elements['lp'].value = lp;
            box.style.display = '';
        }
    }
    else
    {
        remclass(o, 'selected');
        box.style.display = 'none';
        f.elements['newname'].value = '';
        f.elements['lp'].value = '';
    }
}

function lptree_chgrp_cancel()
{
    var f = document.getElementById('flpchgrp');
    var lp = f.elements['lp'].value;
    var o = document.getElementById('lp_' + lp);
    var box = document.getElementById('lp_chgrp');

    remclass(o, 'selected');
    box.style.display = 'none';
    f.elements['newname'].value = '';
    f.elements['lp'].value = '';
}

/*** upload progress bar ***/

function randomstr(len)
{
    var charmap = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var m = charmap.length;
    var s = '';
    var i;
    for (i = 0; i < len; i++)
    {
        var j = Math.floor(Math.random() * m);
        s += charmap.charAt(j);
    }
    return s;
}

function preinit_progressbar(f)
{

    var s = new String(f.action);
    var uid = randomstr(12);

    if (s.match(/\?/))
    {
        s += '&';
    }
    else
    {
        s += '?';
    }
    s += '__pid=' + uid;
    f.action = s;
    
    var frname = 'ifr_progressbar_' + uid;
    var stname = 'st_progressbar_' + uid;
    // IExplorer only: var fr = f.ownerDocument.createElement('<IFRAME name="' + frname + '"></IFRAME>');
    // Firefox only: var fr = f.ownerDocument.createElement('IFRAME'); fr.name = frname;
    // any browser:
    var o = f.ownerDocument.createElement('SPAN');
    o.innerHTML =
        '<iframe frameborder="0" width="0" height="0" name="' + frname + '"></iframe>' +
        '<iframe frameborder="0" width="400" height="150" class="progresspanel" src="progressbar.aspx?pid=' + uid + '" id="' + stname + '"></iframe>'
//'';
    
    f.parentNode.appendChild(o);
    f.target = frname;
    f.style.display = 'none';
    
    return uid;
}

function submitform_progress(i, doit, param, param2)
{
	var f = (typeof(i) == 'object' ? i : document.forms[i]);
	
    var uid = preinit_progressbar(f);
    //window.setTimeout((function(){ submitform(f); }), 100);
    submitform(f);
}

/*** ***/

function confirmurl(txt, url)
{
    if (confirm(txt))
    {
      location.href = url;
    }
}

function togglehiddendocs()
{
    var o = $('tblBibitems');
    if (!o)
        return;

    o.select('.togglevis').each(function(o) {
        o.style.display = (o.style.display == 'none') ? '' : 'none';
    });
    
    /*
    var i;
    var c = o.getElementsByTagName('TR');
    for (i = 0; i < c.length; i++)
    {
        var b = c[i];
        if (b.id && b.id.match(/^Hbibitem_/))
        {
            b.style.display = (b.style.display == 'none' ? '' : 'none');
        }
    }
    */
}

function noop()
{
}

/* lp search */

function input_set(n, v)
{
    var o = document.getElementById(n);
    if (!o)
        return;
    //alert(n + ' ' + o.type + ' ' + o.checked + ' ' + o.value);
    if (o.type == 'checkbox' || o.type == 'radio')
        o.checked = v;
    else if (o.type == 'text' || o.type == 'hidden' || o.type == 'password')
        o.value = v;
}

function lps_preset(name)
{
    if (name == 'reset')
    {
        input_set('lps_innames', false);
        input_set('lps_search', '');
        input_set('lptype_P', true);
        input_set('lps_active', true);
        input_set('lps_inactive', false);
        input_set('lps_archive', false);
        input_set('lps_limit', '30');
    }
    else if (name == 'myarchives')
    {
        input_set('lps_innames', false);
        input_set('lps_search', '');
        input_set('lptype_P', true);
        input_set('lps_active', false);
        input_set('lps_inactive', false);
        input_set('lps_archive', true);
        input_set('lps_limit', '100');
        submitform('flpsearch');
    }
    else if (name == 'myinact')
    {
        input_set('lps_innames', false);
        input_set('lps_search', '');
        input_set('lptype_P', true);
        input_set('lps_active', false);
        input_set('lps_inactive', true);
        input_set('lps_archive', false);
        input_set('lps_limit', '100');
        submitform('flpsearch');
    }
}

function us_preset(name)
{
    if (name == 'reset')
    {
        input_set('us_search', '');
        input_set('us_currlp', false);
        input_set('us_online', false);
        input_set('us_pics', false);
        input_set('us_limit', '30');
    }
    else if (name == 'currentpics')
    {
        input_set('us_search', '');
        input_set('us_currlp', false);
        input_set('us_online', true);
        input_set('us_pics', true);
        input_set('us_limit', '100');
        submitform('fusersearch');
    }
}

/* */
function dexalert(s) {
    if (s.match(/^ERR_/) || s.match(/^TXT_/))
        s = _(s);
    alert(s);
}

function antiidle(doit, params, p2)
{
    new Ajax.Request('Default.aspx?__antiidle=ajax', {
        method: 'post',
        parameters: typeof (doit) == 'undefined' ? {} : { doit: doit, params: params, p2: p2 },
        onSuccess: function(transport) {
            var ct = transport.getResponseHeader('Content-Type');
            var res = transport.responseText;
            if (ct.match(/text\/errormsg/)) {
                dexalert(res);
            }
            else {
                if (res && res.match(/<!--\[CooSpace\.LoginPage\]-->/)) {
                    location.href = 'Login.aspx?src=antiidle';
                }
                else {
                    res = eval(res);
                    for (var n in res) {
                        //alert(n + ' => ' + res[n]);
                        if (n.match(/^upd_/)) {
                            var o = $(n);
                            if (o)
                                o.update(res[n]);

                            if (n == 'upd_msgboard_items') // hack
                                o.scrollTop = 30000;

                        } else if (n.match(/^#upd_/)) {
                            var o = $(n.substr(1));
                            if (o) {
                                if (res[n])
                                    o.show();
                                else
                                    o.hide();
                            }
                        }
                    }
                }
            }
        },
        onFailure: function(transport) {
            //alert('AJAX error' + transport.responseText);
        }
    }); 
}

/* multilang js */
function _(s, p1, p2, p3)
{
    var o = window['txt_' + s];
    if (typeof(o) != 'undefined')
    {
        if (typeof(p1) != 'undefined')
            o = ('' + o).replace(/@P1@/g, p1);
        if (typeof(p2) != 'undefined')
            o = ('' + o).replace(/@P2@/g, p2);
        if (typeof(p3) != 'undefined')
            o = ('' + o).replace(/@P3@/g, p3);
        return o;
    }
    return '[TXT:' + s + ']';
}

function __(s, failval, p1, p2, p3)
{
    var o = window['txt_' + s];
    if (typeof(o) == 'undefined')
        o = failval;
    if (typeof(p1) != 'undefined')
        o = ('' + o).replace(/@P1@/g, p1);
    if (typeof(p2) != 'undefined')
        o = ('' + o).replace(/@P2@/g, p2);
    if (typeof(p3) != 'undefined')
        o = ('' + o).replace(/@P3@/g, p3);
    return o;
}

/* LPforum,LPfs,LPpg,LPblog, ... */
function setval(id, val)
{
    var o = document.getElementById(id);
    if (o)
        o.value = val;
}

function ajaxupdate_real(do_audit, id, url, params, method)
{
    new Ajax.Request(url, {
        method: typeof (method) == 'undefined' ? 'get' : method,
        parameters: params,
        onSuccess: function(transport) {
            var ct = transport.getResponseHeader('Content-Type');
            var res = transport.responseText;
            if (ct.match(/text\/errormsg/)) {
                dexalert(res);
            }
            else {
                if (res && res.match(/<!--\[CooSpace\.LoginPage\]-->/)) {
                    location.href = 'Login.aspx?src=ajax';
                    return;
                }
                else {
                    var o = $(id);
                    if (o)
                        o.update(res);

                    if (do_audit)
                        audit();
                }
            }
        },
        onFailure: function(transport) {
            alert('AJAX error' + transport.responseText);
        }
    });
}

function ajaxupdate_auto(id, url, params, method) {
    return ajaxupdate_real(false, id, url, params, method);
}
function ajaxupdate(id, url, params, method) {
    return ajaxupdate_real(true, id, url, params, method);
}
function ajaxupdate1(id, url, params) {
    var o = $(id);
    if (o) {
        //o.update('<img src="res/pics/ajax-loader.gif" border="0"/>');
        ajaxupdate(id, url, params);
    }
}

function ajaxupdate2(url, method, params, handler)
{
    var ico = $('ajaxbusy');
    if (ico)
        ico.show();

    new Ajax.Request(url, {
        method: (typeof (method) == 'undefined' ? 'get' : method),
        parameters: params,
        onSuccess: function(transport) {
            var ct = transport.getResponseHeader('Content-Type');
            var res = transport.responseText;
            var status;
            if (ct.match(/text\/errormsg/)) {
                status = 'error';
                dexalert(res);
            }
            else {
                if (res && res.match(/<!--\[CooSpace\.LoginPage\]-->/)) {
                    location.href = 'Login.aspx?src=ajax';
                    return;
                }
                else {
                    status = 'success';
                    var parts = res.split(/<separator[^>]*>\s*_____SEPARATOR____\s*<\/separator>/i);

                    for (var i = 1; i < parts.length - 1; i += 2) {
                        var id = parts[i];
                        var content = parts[i + 1];

                        //alert(id + ' <= ' + content);
                        var o = $(id);
                        if (o)
                            o.update(content);
                    }
                }
            }
            audit();
            if (ico)
                ico.hide();
            if (handler)
                handler(status, transport.responseText);
        },
        onFailure: function(transport) {
            if (ico)
                ico.hide();
            if (handler)
                handler('error', transport.responseText);
            else
                alert('AJAX error' + transport.responseText);
        }
    }); 
}

function ajaxdata(url, handler) {
    return ajaxdata2(url, null, handler);
}
function ajaxdata2(url, data, handler)
{
    var ico = $('ajaxbusy');
    if (ico)
        ico.show();

    new Ajax.Request(url, {
        method: 'post',
        parameters: data,
        onSuccess: function(transport) {
            var ct = transport.getResponseHeader('Content-Type');
            var res = transport.responseText;
            if (ct.match(/^application\/x-json/)) {
                eval('res = ' + res + ';');
                if (handler)
                    handler(res);
                else
                    alert('unhandled_json: ' + res.inspect());
            }
            else {
                alert('ajaxdata: invalid content-type: ' + ct);
            }
            if (ico)
                ico.hide();
        },
        onFailure: function(transport) {
            alert('AJAX error' + transport.responseText);
            if (ico)
                ico.hide();
        }
    }); 
}

function togglebox(id)
{
    var r = showhide_real(id, true);
    if (r == -1 || r == 1)
        antiidle('ajax_set', id + '=' + r);
}

function docsearch(form)
{
    form = $(form);
    var params = form.serialize(true);
    ajaxupdate2('Default.aspx?what=ajax_docsearch', 'post', params);
}
function docsearchp(s)
{
    $('ds_search').value = s;
    var params = $('fdocsearch').serialize(true);
    ajaxupdate2('Default.aspx?what=ajax_docsearch', 'post', params);
}

function autostuffs() {
/*
    $$('input,textarea').each(function(o)
    {
        o.observe('focus', function() { hilite(o, true); });
        o.observe('blur', function() { hilite(o, false); });
    });
*/
    $$('.magichover').each(function(o)
    {
        o.observe('mouseover', function() { hilite(o, true); });
        o.observe('mouseout', function() { hilite(o, false); });
    });
}

if (document.observe) {
    document.observe("dom:loaded", function() {
        autostuffs();
    });
}

function hilite(o, v)
{
    if (v)
        $(o).addClassName('hover');
    else
        $(o).removeClassName('hover');
}

function strlen(s)
{
    // \r és \n sorvégek konvertálása \r\n-re és úgy nézni a méretet
    s = (''+s).replace(/\r\n?/g, '\n').replace(/\n/g, '\r\n');
    return s.length;
}
function limitlength(ta, sp, maxlen)
{
    var l = strlen(ta.value);
    sp.update(l);
    if (l > maxlen)
    {
        sp.addClassName('maxlengthexceeded');
        //return false;
        return true;
    }
    else
    {
        sp.removeClassName('maxlengthexceeded');
        return true;
    }
}
function limitlength_submit(ta, maxlen)
{
    var l = strlen(ta.value);
    if (l > maxlen)
    {
        alert(_('maxlengthexceeded'));
        return false;
    }
    else
    {
        return true;
    }
}

function togglebibinfo(bib)
{
    var o = $('bibinfo_' + bib);
    if (o.childNodes.length == 0)
        ajaxupdate(o, 'Default.aspx?what=ajax_bibinfo&id=' + bib);
    else
        o.innerHTML = '';
}

/* forum-inc */
function fau2(r, u, n, newstate) {
    var id = 'U' + r + '_' + u;
    var oo = $(id);
    if ((oo && !newstate) || (!oo && newstate)) {
        fau(r, u, n);
    }
}

function fau(r, u, n)
{
    var old_n = n;
    var id = 'U' + r + '_' + u;
    var oo = $(id);
    var ooo = $(id + '_IMG');
    if (oo)
    {
        oo.parentNode.removeChild(oo);
        if (ooo)
            ooo.src = 'res/pics/fus_n.gif';
    }
    else
    {
        if (typeof(n.innerHTML) != 'undefined')
            n = '' + n.innerHTML;
        else
            n = ('' + n).escapeHTML();
        var c = $('ROLE' + r + '_USERS');
        
        var span = document.createElement('span');
        span.id = id;
        
        var inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = id;
        inp.value = 'Y';
        span.appendChild(inp);
        
        var a = document.createElement('a');
        a.href='javascript:;';
        a.onclick = function() { popup('Uinfo.aspx?u=' + encodeURIComponent(u)); };
        a.innerHTML = n;
        span.appendChild(a);

        var aimg = document.createElement('img');
        aimg.border = '0px';
        aimg.src = 'res/pics/x.gif';
        aimg.alt = 'X';
        aimg.style.marginLeft = '3px';
        aimg.onclick = function() { fau(r, u, old_n); };
        span.appendChild(aimg);
        
        var t = document.createTextNode('; ');
        span.appendChild(t);
        
        c.appendChild(span);
        
        if (ooo)
            ooo.src = 'res/pics/fus_e.gif';
    }
}
function fms_pager(offset)
{
  var pagesize = 25;
  ajaxdata('Default.aspx?what=ajax_roleusers&offset=' + offset + '&pagesize=' + pagesize, function(res) {

      var p = 1;
      var pc = $('PAGES');
      pc.innerHTML = '';
      for (var i = 0; i < res.cnt; i += pagesize) {
          var o = document.createElement('a');
          o.innerHTML = (p++);
          o.href = 'javascript:fms_pager(' + i + ')';
          if (offset >= i && offset < i + pagesize)
              o.className = 'current';
          pc.appendChild(o);
      }

      var data = res.list;
      var c = $('USERPAGER');
      for (var i = c.childNodes.length - 1; i >= 0; i--) {
          c.deleteRow(i);
      }

      for (var i = 0; i < data.length; i++) {
          var row = data[i];

          var tr = c.insertRow(c.rows.length);
          (function(o) {
              o.observe('mouseover', function() { hilite(o, true); });
              o.observe('mouseout', function() { hilite(o, false); });
          })($(tr));

          var td1 = tr.insertCell(0);
          td1.innerHTML = row[0].escapeHTML();
          td1.className = 'clickable';
          (function(u) {
              td1.onclick = function() { popup('Uinfo.aspx?u=' + encodeURIComponent(u)); };
          })(row[0]);

          var td2 = tr.insertCell(1);
          td2.innerHTML = row[1].escapeHTML();
          td2.className = 'clickable';
          (function(u) {
              td2.onclick = function() { popup('Uinfo.aspx?u=' + encodeURIComponent(u)); };
          })(row[0]);

          var td3 = tr.insertCell(2);
          td3.align = 'center';
          var img = document.createElement('img');
          td3.appendChild(img);
          img.src = $('U1_' + row[0]) ? 'res/pics/fus_e.gif' : 'res/pics/fus_n.gif';
          (function(uk, un) {
              img.onclick = function() { fau(1, uk, un); }
          })(row[0], row[1]);
          img.className = 'fus fus_1 fus_1_' + row[2];
          img.id = 'U1_' + row[0] + '_IMG';

          var td4 = tr.insertCell(3);
          td4.align = 'center';
          var img = document.createElement('img');
          td4.appendChild(img);
          img.src = $('U2_' + row[0]) ? 'res/pics/fus_e.gif' : 'res/pics/fus_n.gif';
          (function(uk, un) {
              img.onclick = function() { fau(2, uk, un); }
          })(row[0], row[1]);
          img.className = 'fus fus_2 fus_2_' + row[2];
          img.id = 'U2_' + row[0] + '_IMG';
      }

      selectrole(1);
      selectrole(2);
  });
}

function fms_selbylist(role, addremove) {
    var o = $('ta_selbylist')
    if (!o) return;
    var list = [];
    o.value.split(/\n/g).each(function(line) {
        line = line.strip();
        if (line != '') {
            line = line.replace(/\s.+$/, '');
            list.push(line);
        }
    });
    list = list.uniq();
    if (list.length < 1)
        return;
    ajaxdata2('Default.aspx?what=ajax_getunameslp', { ids: list.join(',') }, function(res) {
        res.each(function(o) {
            fau2(role, o[0], o[1], addremove);
        });
        if (res.length == list.length)
            alert(_('fms_selbylistres', res.length));
        else
            alert(_('fms_selbylistres2', res.length, list.length - res.length));
    });
}

function input_phonenumber(o, fmt) {
    var s = o.value;
    if (s == '')
        return;
    if (typeof (fmt) == 'undefined' || fmt == '')
        fmt = '+2-2-3-4';

    s = s.replace(/ /g, '');

    // +xxxxxx or 00xxxxxx
    var hasplus = s.charAt(0) == '+';
    if (!hasplus && s.match(/^00/)) {
        s = s.replace(/^00/, '');
        hasplus = true;
    }
    if (!hasplus && s.match(/^36[237]0/)) {
        hasplus = true;
    }

    s = s.replace(/[^0-9]/g, '');

    // convert hungarian internal prefix to international
    if (s.match(/^06/)) {
        s = s.replace(/^06/, '36');
        hasplus = true;
    }

    // add country prefix (default: 36)
    if (!hasplus)
        s = '36' + s;

    fmt = fmt.split('');
    var cmd, i, k
    var j = 0;
    var res = '';
    for (i = 0; i < fmt.length; i++) {
        cmd = fmt[i];
        if (cmd.match(/^[0-9]+$/)) {
            cmd = new Number(cmd);
            for (k = 0; k < cmd; k++)
                res += s.charAt(j++);
        }
        else
            res += cmd;
    }
    o.value = res;
}

function trim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+|[" + chars + "]+$", "g"), "");
}

/*** CSX ***/
function csx_setscore(c, type, id, s) {
    var params = {};
    params.SCORE = s;
    params[type] = id;
    new Ajax.Request('Default.aspx?what=ajax_csx_setscore', {
        method: 'post',
        parameters: params,
        onSuccess: function(transport) {
            var ct = transport.getResponseHeader('Content-Type');
            var res = transport.responseText;
            if (ct.match(/text\/errormsg/)) {
                dexalert(res);
            }
            else {
                var score = new Number(res);
                c.title = score;
                stars(c);
            }
        },
        onFailure: function(transport) {
            //alert('AJAX error' + transport.responseText);
        }
    });
}

function stars(cont, value) {
    if (!value) {
        value = new Number(cont.title);
    }
    var i;
    if (value > 4.5)
        i = 5;
    else if (value > 3.5)
        i = 4;
    else if (value > 2.5)
        i = 3;
    else if (value > 1.5)
        i = 2;
    else if (value > 0.5)
        i = 1;
    else
        i = 0;
    var imgs = cont.getElementsByTagName('img');
    for (var j = 0; j < imgs.length; j++) {
        imgs[j].src = imgs[j].src.replace(/\/star(gray)?\./, '/star' + (j  < i ? '' : 'gray') + '.');
    }
    return;
}

function CreateBookmarkLink() {
  title = "CSX.hu"; 
  url = "http://www.csx.hu/?from=fav";
  if (window.sidebar) { // Mozilla Firefox Bookmark
    window.sidebar.addPanel(title, url, "");
  } else if( window.external ) { // IE Favorite
    window.external.AddFavorite( url, title);
  } else if(window.opera && window.print) { // Opera Hotlist
    return true;
  }
}

function $1(n) {
    return document.getElementById(n);
}

function settab(buttons, contents, idx, idx2) {
    var i;
    if (typeof (idx2) == 'undefined')
        idx2 = idx;
    for (i = 0; i < buttons.length; i++) {
        if (i == idx)
            addclass(buttons[i], 'active');
        else
            remclass(buttons[i], 'active');
    }
    for (i = 0; i < contents.length; i++) {
        if (i == idx2)
            contents[i].style.display = '';
        else
            contents[i].style.display = 'none';
    }
}

function xtraajaxsearch(form, result, offset) {
    form = $(form);
    var data = form.serialize(true);
    if (data['pattern'] == '') {
        $(result).update('');
        return;
    }
    data['_name'] = form.id;
    data['_offset'] = typeof (offset) == 'undefined' ? 0 : offset;
    result = $(result);
    ajaxupdate1(result, 'xtra.aspx', data);
}

// hint support

function showhint(o, hintid) {
    var pos = Element.cumulativeOffset(o);
    var spos = Element.cumulativeScrollOffset(document.body);
    var spos2 = Element.cumulativeScrollOffset(o);
    pos.left -= spos2.left - spos.left;
    pos.top -= spos2.top - spos.top;
    
    var div = document.createElement('div');
    o.hintobj = div;
    //document.body.appendChild(div);
    o.parentNode.appendChild(div);
    div.className = 'hint';
    div.style.top = (pos.top) + 'px';
    div.style.left = (pos.left + 11) + 'px';
    var s = window.hintTexts[hintid];
    if (typeof (s) == 'undefined')
        s = hintid;
    div.innerHTML = s;
}

function hidehint(o) {
    if (o.hintobj) {
        o.hintobj.parentNode.removeChild(o.hintobj);
        o.hintobj = null;
    }
}

function addautohints() {
    var lastth;
    var page = location.href.replace(/\?.*/, '').split('/');
    page = page[page.length - 1].replace(/\..+/,'');
    $$('form table.fields').each(function(o) {
        o.getElementsBySelector('input,select').each(function(o) {
            var td = o.parentNode;
            var f = o.form;
            if (!f || !td || o.name == '')
                return;
            //alert(f + ' id=' + f.id + ' name=' + f.name);
            var formname = (f.id == '' ? f.name : f.id);
            if (formname == '')
                return;
            if (td.nodeName == 'TD' || td.nodeName == 'td') {
                var th = td.previousSibling;
                if (th && (th.nodeName == 'TH' || th.nodeName == 'th')) {

                    if (lastth == th)
                        return;
                    lastth = th;

                    var id = (page + '.' + formname + '.' + o.name.replace(/^[\.@!]/, '')).toLowerCase();

                    var img = document.createElement('img');
                    img.className = 'hint';
                    if (typeof (window.hintTexts[id]) == 'undefined') {
                        img.src = 'res/theme' + window.theme + '/nohint.gif';
                        img.ondblclick = function() { prompt('hint ID', id); };
                    }
                    else {
                        img.src = 'res/theme' + window.theme + '/hint.png';
                        img.onmouseover = function() { showhint(img, id); };
                        img.onmouseout = function() { hidehint(img, id); };
                    }
                    img.alt = '';
                    th.appendChild(img);
                }
            }
        });
    });
}

document.observe('dom:loaded', addautohints);

/* iefix */
try {
    if (window.name.toLowerCase() == '_blank')
        window.name = '';
} catch (e) { }

/* */

RegExp.escape = function(text) {
    if (!arguments.callee.sRE) {
        var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
        arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
    }
    return text.replace(arguments.callee.sRE, '\\$1');
}

/* csx pmsg */
function csx_sendmsg(form, list, listtype) {
    form = $(form);
    if (form['msg'].value == '' || form['to'].value == '') {
        return;
    }
    var params = form.serialize(true);
    form['msg'].value = '';
    params['ajax'] = 'sendmsg';
    params['listid'] = list;
    params['listtype'] = listtype;
    ajaxupdate(list, 'xtra.aspx', params, 'post');
    if (listtype == 'sent') {
        var o; 
        o = $('pmsg_folder_-1');
        if (o) o.addClassName('pmsg_folder_active');
        o = $('pmsg_folder_0');
        if (o) o.removeClassName('pmsg_folder_active');
    }
}

function csx_getmsg(id, container, msgrow) {
    var c = $1(container);
    if (c.getElementsByTagName('div').length > 0)
        c.innerHTML = '';
    else {
        var o = $(msgrow);
        if (o) o.removeClassName('pmsg_new');
        ajaxupdate(container, 'xtra.aspx', { ajax: 'getmsg', id: id }, 'post');
    }
}

function csx_delmsg(msgid, o1, o2) {
    ajaxdata2('xtra.aspx', { ajax: 'delmsg', id: msgid }, function(res) {
        if (res == 1) {
            if (o1 && (o1 = $(o1)))
                o1.remove();
            if (o2 && (o2 = $(o2)))
                o2.remove();
        }
        else
            alert(_('ERR_UNKNOWN'));
    });
}

/* msgboard */
function msgboard_focus() {
    var o = $('s_msgboard_control');
    o.addClassName('msgboard_control_active');
    var i = $1('s_msgboard_input');
    if (i.value == _('msgboard_writehere'))
        i.value = '';
}

function msgboard_blur(now) {
    var f = function() {
        var o = $('s_msgboard_control');
        o.removeClassName('msgboard_control_active');
        var i = $1('s_msgboard_input');
        if (i.value == '')
            i.value = _('msgboard_writehere');
    };
    if (now)
        f();
    else
        window.setTimeout(f, 500);
}

function msgboard_send() {
    var i = $1('s_msgboard_input');

    if (i.value.replace(/^\s+|\s+$1/g) != '')
        antiidle('msgboard_send', i.value);

    i.value = '';
    msgboard_blur(true);

    var ooo = $('upd_msgboard_items');
    if (ooo)
        ooo.scrollTop = 30000;
}

if (document.observe) {
    document.observe("dom:loaded", function() {
        //$('upd_msgboard_items_bottom').scrollIntoView();
        var ooo = $('upd_msgboard_items');
        if (ooo)
            ooo.scrollTop = 30000;
    });
}

/* search */

function globalsearch(type) {
    var o = $('menu_search_input');
    if (!o)
        return;
    location.href = 'search.aspx?type=' + type + '&search=' + encodeURIComponent(o.value);
}
function onenterpress(i, ev, func) {
    if (typeof (ev) == 'undefined')
        ev = window.event;
    if (ev && ev.keyCode == 13) {
        func(i);
    }
}

/* multidownload */
/*
function multidl_add(div, url) {
    var m = /\/([^\/]+)\/([^\/]+)$/.exec(url);
    var token = RegExp.$1;
    var fn = decodeURI(RegExp.$2);
    if (typeof (token) != 'undefined' && token != '') {
        antiidle('dllist_add', token, fn);
        addclass(div, 'multidl_added');
    }
}
*/
function multidl_show(o, url) {
    var p = {};
    if (url) {
        var m = /\/([^\/]+)\/([^\/]+)$/.exec(url);
        var token = RegExp.$1;
        var fn = decodeURI(RegExp.$2);
        if (typeof (token) != 'undefined' && token != '') {
            p.token = token;
            p.fn = fn; 
            addclass(o, 'multidl_added');
        }
    }
    ajaxdata2('Default.aspx?what=ajax_dllist_show', p, function(res) {

        var div = o.dllist_obj;
        var newdiv = false;
        if (!div) {
            var pos = Element.cumulativeOffset(o);
            var spos = Element.cumulativeScrollOffset(document.body);
            var spos2 = Element.cumulativeScrollOffset(o);
            pos.left -= spos2.left - spos.left;
            pos.top -= spos2.top - spos.top;

            div = document.createElement('div');
            div.style.zIndex = 100;
            o.appendChild(div);
            div.className = 'dllist_box';
            div.style.top = (pos.top) + 'px';
            div.style.left = (pos.left + 11) + 'px';

            div = $(div);
            o.dllist_obj = div;
            var effect = new DFXTransp(div);
            effect.speed = 0.1;
            o.dllist_effect = effect;
            $(o).observe('mouseout', function(e) { effect.startHide(); });
            $(o).observe('mouseover', function(e) { effect.startShow(); });
            effect.timerStopped = function(val) { if (val == 0) { $(o).stopObserving('mouseout'); $(o).stopObserving('mouseover'); div.parentNode.removeChild(div); o.dllist_obj = null; o.dllist_effect = null; } };
        }

        if (o.dllist_effect)
            o.dllist_effect.startShow();

        $(div).update('');
        res.each(function(x) {
            var oo = document.createElement('div');
            oo.appendChild(document.createTextNode(x[1]));
            div.appendChild(oo);
        });

        var oo = document.createElement('div');
        oo.className = 'dllist_buttons';

        var a = document.createElement('a');
        a.href = 'getzip.aspx/dllist/pack.zip';
        a.target = '_blank';
        a.appendChild(document.createTextNode(_('dllist_download')));
        oo.appendChild(a);

        oo.appendChild(document.createTextNode(' | '));

        a = document.createElement('a');
        a.href = 'javascript:';
        $(a).observe('click', function() { ajaxdata('Default.aspx?what=ajax_dllist_clear', function(res) { }); $(o).stopObserving('mouseout'); $(o).stopObserving('mouseover'); effect.startHide(); });
        a.appendChild(document.createTextNode(_('dllist_clearall')));
        oo.appendChild(a);

        div.appendChild(oo);
    });
}

function realmouseover(evt,currentTarget) {
    var relatedTarget = $(evt.relatedTarget || evt.fromElement);
    if (!relatedTarget)
        return false;
    if (relatedTarget != currentTarget && relatedTarget.childOf(currentTarget)==false)
        return true;
    else
        return false;
}
function realmouseout(evt, currentTarget) {
    var relatedTarget = $(evt.relatedTarget || evt.toElement);
    if (!relatedTarget)
        return false;
    if (relatedTarget != currentTarget && relatedTarget.childOf(currentTarget) == false)
        return true;
    else
        return false;
}

function audit() {
    var s;
    s = window.audit_pagekind;
    if (!s)
        s = 'UNKNOWN';
    //alert('ajax - ' + s);
}
