/**
 * Common JavaScript library.
 *
 * @package      TenisPortal
 * @subpackage   JavaScript
 * @author       Livesport, s.r.o.
 * @copyright    (c) 2007 Livesport, s.r.o.; {@link http://www.livesport.cz/}
 * @since        2007/09/22
 */

var ajaxObject = new Array();
var cJsLib     = new cJsLib();
var ie         = false;
var cookie     = new Cookie();
var eMsg       = new ExpressMessage();
var toolTip    = null; 
var closingPermInfo = false;

addLoadEvent(setInputEvents);
addLoadEvent(setHoverButtons);
addLoadEvent(setTabIndexes);
addLoadEvent(checkLastMatchSize);
addLoadEvent(setToolTip);

/**
 * Set default input events.
 */
function setInputEvents()
{/*
	var ipt = cJsLib.$('mutualName1');
	if (! cJsLib.isNull(ipt)) {
		ipt.setAttribute('autocomplete', 'off');
		
		ipt.onkeydown = function(evt)
		{
			var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
			if ((keyCode == 13 || keyCode == 9) && this.value.length >= 3) {
				return checkPlayerName(this.value, 1);
				
				return (keyCode == 13 ? false : true);
			}
		};
	}
	
	var ipt = cJsLib.$('mutualName2');
	if (! cJsLib.isNull(ipt)) {
		ipt.setAttribute('autocomplete', 'off');
	
		ipt.onkeydown = function(evt)
		{
			var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
			if ((keyCode == 13 || keyCode == 9) && this.value.length >= 3) {
				checkPlayerName(this.value, 2);
	            
	            return (keyCode == 13 ? false : true);
	        }
		};
	}
*/	
	var ipt = cJsLib.$('profilePlayerName');
	if (! cJsLib.isNull(ipt)) {
		ipt.setAttribute('autocomplete', 'off');
	
		ipt.onkeydown = function(evt)
		{
			var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
			if (keyCode == 13) {
				pl_profile(cJsLib.$('profilePlayerName').value);
	            
	            return (keyCode == 13 ? false : true);
			}
		};
	}

	var ipt = cJsLib.$('tournamentSearchName');
	if (! cJsLib.isNull(ipt)) {
		ipt.setAttribute('autocomplete', 'off');
	
		ipt.onkeydown = function(evt)
		{
			var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
			if (keyCode == 13) {
				tournament_search(cJsLib.$('tournamentSearchName').value);
	            
	            return (keyCode == 13 ? false : true);
			}
		};
	}
};

/**
 * Set HOVER efekt on backgrounded inputs.
 */
function setHoverButtons()
{
    var obj = cJsLib.$$('input.btn');
    
    if (! cJsLib.isNull(obj) && obj.length > 0) {
        for (var i = 0; i < obj.length; ++i) {
            obj[i].onmouseover = function()
            {
                var pElem   = this.parentNode;
                var pCss    = cJsLib.getCls(pElem);
                var pattBtn = new RegExp('(lGray|lOrange|lGreen)', 'g');
                
                if (! cJsLib.empty(pCss) && pattBtn.test(pCss)) {
                    cJsLib.addCls(this, 'hover');
                }
            };
            
            obj[i].onmouseout = function()
            {
                var pElem   = this.parentNode;
                var pCss    = cJsLib.getCls(pElem);
                var pattBtn = new RegExp('(lGray|lOrange|lGreen)', 'g');
                
                if (! cJsLib.empty(pCss) && pattBtn.test(pCss)) {
                    cJsLib.rmCls(this, 'hover');
                }
            };
        }
    }
};

/**
 * Set tabindex attribute on selected elements.
 */
function setTabIndexes()
{
    if (! cJsLib.isNull(tabIdx) && tabIdx.length > 0) {
        for (var i = 0; i < tabIdx.length; ++i) {
            cJsLib.$(tabIdx[i]).setAttribute('tabIndex', i+1);
        }
    }
};

/**
 * Check size table with last matches on home page and resize if needed.
 */
function checkLastMatchSize()
{
    var tbl = cJsLib.$(cookie.get('idx_last_game_tab') + '-data');

    if (! cJsLib.isNull(tbl)) {
        if (tbl.offsetHeight < 219) {
            var lstContainer = cJsLib.$('lastMatch');
            var cls          = null;
        
            if (! cJsLib.isNull(lstContainer)) {
                cJsLib.setStyle(lstContainer, 'height:' + tbl.offsetHeight + 'px;overflow-y:hidden;');
            }
        }
        
        if (cJsLib.isIE()) {
            cJsLib.setStyle(cJsLib.$('lstGame-' + cookie.get('idx_last_game_tab').replace('lstGame-', '') + '-data'), '#width:471px;_width:477px;');
        }
    }
};

function setToolTip()
{
    toolTip = new tooltip('web-all');
};

/**
 * Append a new onload function.
 * 
 * @param {String} func   The name of function.
 */
function addLoadEvent(func)
{
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') { 
        window.onload = func; 
    } else { 
        window.onload = function() { 
            if (oldonload) { 
                oldonload(); 
            }
            func(); 
        } 
    } 
};

/**
 * Detect M$ IE browser.
 * 
 * @return void
 */
function detect_browser()
{
	if (navigator.userAgent.match(/MSIE/))
		ie = true;
};

detect_browser();

/**
 * Remove the CSS class.
 * 
 * @param object
 *            element The DOM element of target element.
 */
function delCls(element)
{
	if (ie)
		element.removeAttribute('className');
	else
		element.removeAttribute('class');
};

/**
 * Set the CSS class name.
 * 
 * @param object
 *            $element Target element object.
 * @param string
 *            $clsName Name of the CSS class.
 * @return void
 */
function setCls(element, clsName)
{
	return (ie ? element.setAttribute('className', clsName) : element.setAttribute('class', clsName));
};

/**
 * Get the CSS style.
 * 
 * @param object
 *            element Target element object.
 */
function getCls(element)
{
	return (ie ? element.getAttribute('className') : element.getAttribute('class'));
};

/**
 * Set the CSS style on parent element.
 * 
 * @param object
 *            $element DOM object of parent element.
 * @param string
 *            $styleCSS The CSS style;
 */
function setStyle(element, styleCSS)
{
	if (ie)
		element.style.cssText = styleCSS;
	else
		element.setAttribute('style', styleCSS);
};

/**
 * Set the onclick function.
 * 
 * @param object
 *            $element DOM object of parent element.
 * @param string
 *            $onAction Action for onclick event.
 * @return void
 */
function setOnClick(element, onAction)
{
	if (ie)
		element.onclick = new Function("env", onAction);
	else
		element.setAttribute('onclick', onAction);
};

/**
 * Get value of the node from XML DOM.
 * 
 * @param string
 *            $element The DOM object.
 * @return string
 */
function getNodeValue(element)
{
	return (ie ? element.text : element.textContent);
};

/**
 * Get object of element by ID.
 * 
 * @param string
 *            $element ID name of requested element.
 * @return object Returns element's object.
 */
function getElement(element)
{
	return document.getElementById(element);
};

/**
 * Get element position.
 * 
 * @param  {Object} obj   DOM object of parent element.
 * @param {Object}   Returns array with element position.
 */
function getElementPosition(obj)
{
	var curleft = 0;
	var curtop  = 0;

	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop  = obj.offsetTop;

		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop  += obj.offsetTop;
		}
	}

	return {curleft:curleft, curtop:curtop};
};

var nodiac =
{
	'á':'a', 'Á':'a',
	'č':'c', 'Č':'c',
	'ď':'d', 'Ď':'d',
	'é':'e', 'É':'e',
	'ě':'e', 'Ě':'e',
	'í':'i', 'Í':'i',
	'ň':'n', 'Ň':'n',
	'ó':'o', 'Ó':'o',
	'ř':'r', 'Ř':'r',
	'š':'s', 'Š':'s',
	'ť':'t', 'Ť':'t',
	'ú':'u', 'Ú':'u',
	'ů':'u', 'Ů':'u',
	'ý':'y', 'Ý':'y',
	'ž':'z', 'Ž':'z',
	'ü':'ue','Ü':'ue',
	'ä':'a', 'Ä':'a',
	'ë':'e', 'Ë':'e',
	'ö':'o', 'Ö':'o',
	'ï':'i', 'Ï':'i',
	'ÿ':'y', 'Ÿ':'y',
	'ł':'l', 'Ł':'l',
	'ĺ':'l', 'Ĺ':'l',
	'ć':'c', 'Ć':'c'
};

/**
 * Make friendly URL.
 * 
 * @param string
 *            $str Source string to convert.
 * @return string Returns converted string.
 * @copyright Jakub Vrána, http://php.vrana.cz; Jiří Švec - LiveSport,
 *            http://www.livesport.cz/
 */
function make_url(str)
{
	str		= str.toLowerCase();
	var s2	= '';

	for (var i = 0; i < str.length; i++)
		s2 += (typeof nodiac[str.charAt(i)] != 'undefined' ? nodiac[str.charAt(i)] : str.charAt(i));

	return s2.replace(/[^a-z0-9_]+/g, '-').replace(/^-|-$/g, '');
};

/**
 * URL encode / decode.
 * 
 * http://www.webtoolkit.info/
 */
var url = {

	// public method for url encoding
	encode : function(string)
	{
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function(string)
	{
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function(string)
	{
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++)
		{
			var c = string.charCodeAt(n);

			if (c < 128)
				utftext += String.fromCharCode(c);
			else if((c > 127) && (c < 2048))
			{
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else
			{
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function(utftext)
	{
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while (i < utftext.length)
		{
			c = utftext.charCodeAt(i);

			if (c < 128)
			{
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224))
			{
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else
			{
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}

		return string;
	}
};

/**
 * Set the CSS class at mouseover event.
 * 
 * @param object
 *            $element Target element object.
 * @return void
 */
function m_over(element)
{
	// last_cls = ie ? element.getAttribute('className') :
	// element.getAttribute('class');
	setStyle(element, 'background: #f7f8dc');
};

/**
 * Set the CSS class in mouseout event.
 * 
 * @param object
 *            $element Target element object.
 * @return void
 */
function m_out(element)
{
	setStyle(element, '');
};

/**
 * Set the CSS class in mouseover event on double row.
 * 
 * @param object
 *            $element Target element object.
 * @param boolean
 *            $is_second Is second row.
 * @return void
 */
function md_over(element, is_second)
{
	// save last CSS class
// last_d_cls = ie ? element.getAttribute('className') :
// element.getAttribute('class');

	var one = element.getAttribute('id');
	var two = one.match(/b/) ? one.slice(0,-1) : one+'b';

	// setting hover
	setStyle(getElement(one), 'background: #f7f8dc');
	setStyle(getElement(two), 'background: #f7f8dc');
};

/**
 * Set the CSS class in mouseout event on double row.
 * 
 * @param object
 *            $element Target element object.
 * @param boolean
 *            $is_second Is second row.
 * @return void
 */
function md_out(element, is_second)
{
	var one = element.getAttribute('id');
	var two = one.match(/b/) ? one.slice(0, -1) : one+'b';

	// setting hover
	setStyle(getElement(one), '');
	setStyle(getElement(two), '');
};

function cTabMenu(prefix, id, maxId, showData, resizeOverflow, cookieName)
{
    if (cJsLib.empty(id)) {
        id = new Number(1);
    }
    
    idx            = cJsLib.$('last') == null ? false : true;
    resizeOverflow = ! cJsLib.isNull(resizeOverflow) && resizeOverflow ? true : false;
    showData       = ! cJsLib.isNull(showData) && showData ? true : false;
    
    for (i = 1; i <= maxId; ++i) {
        cJsLib.rmCls(cJsLib.$(prefix + i));
        
        if (showData) {
            cJsLib.setCls(cJsLib.$(prefix + i + '-data'), 'none');
        }
    }
    
    cJsLib.setCls(cJsLib.$(prefix + id), 'set');
    
	if (cJsLib.isObject(cJsLib.$(prefix + id + '-data'))) {
		if (showData) {
			cJsLib.sh(prefix + id + '-data');
		}

		if (resizeOverflow) {
			var div        = cJsLib.$('lastMatch');
			var dataHeight = cJsLib.$(prefix + id + '-data').offsetHeight;
	        var dHeight    = dataHeight > 250 ? 250 : (dataHeight < 50 ? 20 : dataHeight);
			cJsLib.setStyle(div, 'height:' + dHeight.toString() + 'px;');

            if (cJsLib.isIE()) {
                cJsLib.setStyle(cJsLib.$('lstGame-' + id + '-data'), '#width:471px;_width:477px;');
            }
            
			if (dHeight == 20) {
				cJsLib.setCls(div, 'noScroll');
			} else {
				cJsLib.rmCls(div);
			}
		}
	}
		
	// update cookie
	if (! cJsLib.empty(cookieName)) {
		cookie.add(cookieName, prefix + id, 365);
	}
    
    delete i,resizeOverflow,showData;
};

/**
 * Show / hide tab menu.
 * 
 * @param string
 *            $tab ID of next tab menu.
 * @param boolean
 *            $showData If need switch hidden data box enter <b>true</b>,
 *            otherwise <b>null</b> or <b>false</b>.
 * @param string
 *            $prefix Prefix for element ID. param boolean $show_data Show data
 *            data block, for example paired DIV block witch some data which
 *            depends on tab. Data block must a same ID as pared tab and
 *            finishes '-data', e.g. <b>lt1</b> for TAB and <b>lt1-data</b>
 *            for the data block <i>(optional)</i>.
 * @param boolean
 *            $resize_overflow Resize overflow div <i>(optional)</i>.
 * @return void
 */
function tmenu(prefix, id, max_id, show_data, resize_overflow)
{
	var idx = (getElement('last') == null) ? false : true;

	if (typeof id == 'undefined') {
		id = 1;
	}

	if (typeof resize_overflow == 'undefined') {
		resize_overflow = false;
	}

	if (typeof show_data == 'undefined') {
		show_data = false;
	}

	for (var i = 1; i <= max_id; i++) {
		setCls(getElement(prefix+i), 'n');

		if (idx) {
			setCls(getElement('tbl-last'+i), 'result');
		}

		if (show_data) {
			setCls(getElement(prefix+i+'-data'), 'hidden');
		}
	}

	setCls(getElement(prefix+id), 'a');

	if (show_data) {
		setCls(getElement(prefix+id+'-data'), 'shown');
    }

	if (idx && resize_overflow) {
		var div = getElement('last');
		var dataHeight	= getElement(prefix+id+'-data').offsetHeight;
		var dHeight		= dataHeight > 250 ? 250 : (dataHeight < 50 ? 35 : dataHeight);
		setStyle(div, 'height:'+dHeight+'px;');

		if (dHeight == 35) {
			setCls(div, 'no-scroll');
			var tbl = getElement('tbl-last'+id);
			setCls(tbl, 'result no-data');
		} else {
			delCls(div);
        }
	}
};

/**
 * Check if added comment is not empty.
 * 
 * @return boolean Returns <b>true</b> if comment is not empty, otherwise
 *         returns <b>false</b>.
 */
function checkComment()
{
	if (getElement('commContent').value == '')
	{
		alert(TXT_COMMENT_CAN_NOT_BE_EMPTY);
		return false;
	}

	return true;
};

/**
 * Fill the input and hidden input in mutual matches search box.
 * 
 * @param object
 *            $element DOM object of parent element.
 * @param string
 *            $playerName Name of player.
 * @param string
 *            $playerURL URL for player profile.
 * @return void
 */
function fillMutual(element, playerName, playerURL)
{
	element.value    = playerName;
	var hiddenElem   = getElement('h-'+element.getAttribute('id'));
	hiddenElem.value = playerURL;

	if (element.getAttribute('id') == 'mutualName1')
		mutualName[0] = playerName;
	else
		mutualName[1] = playerName;

	setCls(getElement('mutualSuggest'), 'suggest hidden');
};

/**
 * Create new suggest box.
 * 
 * @param string
 *            $elementID ID of suggest box.
 * @return object Returns the DOM object of box.
 */
function _createSuggestBox(elementID)
{
	// new suggest container
	var newSuggest = document.createElement('div');
	newSuggest.setAttribute('id', 'mutualSuggest');
	setCls(newSuggest, 'suggest');

	return newSuggest;
};

/**
 * Create suggest row.
 * 
 * @param string
 *            $rowValue Value of option in suggest.
 * @param string
 *            $rowHref Link for option.
 * @param string
 *            $onClickFunction Function which execute if click on element.
 * @return object Returns the DOM object.
 */
function _createSuggestRow(rowValue, rowHref, onClickFunction)
{

	var opt = document.createElement('a');
	setOnClick(opt, onClickFunction);
	opt.appendChild(document.createTextNode(rowValue));
	opt.setAttribute('href', rowHref);

	return opt;
};

/**
 * Move active row in suggest.
 * 
 * @param object
 *            $element DOM object of parent element.
 * @param string
 *            $direction Direction of motion. Possible values are:
 *            <ul>
 *            <li><b>up</b> - move up,</li>
 *            <li><b>down</b> - move down.</li>
 *            </ul>
 * @return void
 */
function moveActiveSuggestRow(element, direction)
{
	var newPosition = lastSuggestRow;

	// check if suggest has some childs
	if (element.hasChildNodes())
	{
		// remove hover
		delCls(element.childNodes[lastSuggestRow]);

		if (direction == 'down')
		{
			if (lastSuggestRow >= element.childNodes.length-1)
				newPosition = 0;
			else
				newPosition++;
		}
		else
		{
			if (lastSuggestRow <= 0)
				newPosition = element.childNodes.length-1;
			else
				newPosition--;
		}

		// set hover
		setCls(element.childNodes[newPosition], 'active');

		// save last position
		lastSuggestRow = newPosition;
	}
};

function checkSearchForm()
{
	val = getElement('searchText');

	if (val.value.length < 3) {
		alert(TXT_SHORT_SEARCHED_TEXT);
		return false;
	} else {
		sbt = getElement('searchSubmit');
		sbt.click();
	}

	return true;
}

/**
 * Check players if mutual form and redirect to theirs mutual matches.
 * 
 * @param {String} $elem1 ID of first input element with player name.
 * @param {String} $elem2 ID of second input element with player name.
 */
function checkMutual(elem1, elem2)
{
	var player1 = cJsLib.$(elem1).value;
	var player2 = cJsLib.$(elem2).value;

	if (getElement('h_player1').value == '' && player1 != '') {
		checkPlayerName(player1, 1);
	}

	if (getElement('h_player2').value == '' && player2 != '') {
		checkPlayerName(player2, 2);
	}

    if (cJsLib.$('h_player1').value == cJsLib.$('h_player2').value) {
        alert(TXT_CAN_NOT_COMPARE_THE_SAME_PLAYER);        
    } else if (getElement('h_player1').value.length > 0 && getElement('h_player2').value.length > 0) {
		var form = cJsLib.$('mutualForm');

		form.setAttribute('action', TXT_URL_MUTUAL_MATCHES + getElement('h_player1').value + '/' + getElement('h_player2').value + '/');
		form.submit();
	}
};

// AJAX {{{

var xhr;

/**
 * Create XMLHttpRequest (XHR) object.
 * 
 * @return void
 */
function create_xhr()
{
	try {
		// Firefox, Opera 8.0+, Safari
		xhr = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert(TXT_UNSUPPORTED_BROWSER);
				return false;
			}
		}
	}
};

/**
 * Display XHR error and error code, if creation failure.
 * 
 * @return void
 */
function show_xhr_error()
{
	alert(TXT_XHR_ERROR);
};

var plProfileInProgress = false;
/**
 * Search player name and show your profile.
 * 
 * @param {String} name      Player's name. Minimal length is 3 chars.
 * @param {String} pl_type   Game type.
 * Possible values are:
 * <ul>
 *      <li><b>men</b> - for ATP,</li>
 *      <li><b>women</b> - for WTA.</li>
 * </ul>
 * @return void
 */
function pl_profile(name)
{
	var pl_type; // means: kind of game (ATP | WTA)
    var playerType = 'woman';
    var cls        = null; // CSS class names of tab
    
	// check for player type
    if ((cls = cJsLib.getCls(cJsLib.$('plProfile-1'))) && cls.match(/set/)) {
        var playerType = 'man';
    }

	if (! cJsLib.empty(name) && name.length >= 2 && ! plProfileInProgress) {
        plProfileInProgress = true;

        var ajaxIndex = ajaxObject.length;

        // create new AJAX object
        ajaxObject[ajaxIndex] = new XHR();

        // store created AJAX as alias
        var ajax = ajaxObject[ajaxIndex];

        ajax.setMethod('GET')
            .setRequestFile('/res/ajax/player-profile.php')
            .setVar('player', url.encode(name))
            .setVar('type', playerType)
            .setBasicPreLoaderId('profileSearchBut', false);

        // redefine function which execute after AJAX
        ajax.onCompletion = function(response, txt)
        {
            var pRedirect = response.getElementsByTagName('redirect');

            if (! cJsLib.isNull(pRedirect) && pRedirect.length > 0 && pRedirect[0].firstChild.nodeValue != '') {
                window.location.href = pRedirect[0].firstChild.nodeValue;
                return true;
            }

            var noData     = response.getElementsByTagName('nodata').item(0);
            var muchResult = response.getElementsByTagName('much_results').item(0);
            
            if (! cJsLib.isNull(muchResult)) {
                alert(muchResult.firstChild.nodeValue);
            } else if (! cJsLib.isNull(noData)) {
                alert(noData.firstChild.nodeValue);
            } else {
                var newBox     = cJsLib.createElement('div', {'id': 'profile-search'});
                var parBoxElem = getElement('profile-search').parentNode; // parent DOM element for replacing DIV boxes
                var player     = response.getElementsByTagName('player');

                for (var i=0; i < player.length; i++) {
                    var pl_name = getNodeValue(player[i].firstChild);
                    var pl_url  = getNodeValue(player[i].lastChild);

                    var lCase = cJsLib.createElement('div', {});
                    var link  = cJsLib.createElement('a', {'href': pl_url});
                    link.appendChild(document.createTextNode(pl_name));
                    lCase.appendChild(link);
                    lCase.appendChild(document.createTextNode(' »'));

                    newBox.appendChild(lCase);
                }

                // replace DOM
                parBoxElem.replaceChild(newBox, cJsLib.$('profile-search'));
                
            }
            
            // remove preloader
            this.restoreBasicPreLoader();
        }

        // run the AJAX
        ajax.runAjax();

        plProfileInProgress = false;
	}
};


var tournamentSearchInProgress = false;
/**
 * Search tournaments
 * 
 * @param {String} name      Tournament name. Minimal length is 3 chars.
 * @return void
 */
function tournament_search(name)
{
    var cls        = null; // CSS class names of tab
    
	if (! cJsLib.empty(name) && name.length >= 2 && ! tournamentSearchInProgress) {
        tournamentSearchInProgress = true;

        var ajaxIndex = ajaxObject.length;

        // create new AJAX object
        ajaxObject[ajaxIndex] = new XHR();

        // store created AJAX as alias
        var ajax = ajaxObject[ajaxIndex];

        ajax.setMethod('GET')
            .setRequestFile('/res/ajax/tournament-search.php')
            .setVar('name', url.encode(name))
            .setBasicPreLoaderId('tournamentSearchBut', false);

        // redefine function which execute after AJAX
        ajax.onCompletion = function(response, txt)
        {
            var pRedirect = response.getElementsByTagName('redirect');

            if (! cJsLib.isNull(pRedirect) && pRedirect.length > 0 && pRedirect[0].firstChild.nodeValue != '') {
                window.location.href = pRedirect[0].firstChild.nodeValue;
                return true;
            }

            var noData     = response.getElementsByTagName('nodata').item(0);
            var muchResult = response.getElementsByTagName('much_results').item(0);
            
            if (! cJsLib.isNull(muchResult)) {
                alert(muchResult.firstChild.nodeValue);
            } else if (! cJsLib.isNull(noData)) {
                alert(noData.firstChild.nodeValue);
            } else {
                var newBox     = cJsLib.createElement('div', {'id': 'tournament-search'});
                var parBoxElem = getElement('tournament-search').parentNode; // parent DOM element for replacing DIV boxes
                var tournament = response.getElementsByTagName('tournament');

                for (var i=0; i < tournament.length; i++) {
                    var t_name = getNodeValue(tournament[i].firstChild);
                    var t_url  = getNodeValue(tournament[i].lastChild);

                    var lCase = cJsLib.createElement('div', {});
                    var link  = cJsLib.createElement('a', {'href': t_url});
                    link.appendChild(document.createTextNode(t_name));
                    lCase.appendChild(link);
                    lCase.appendChild(document.createTextNode(' »'));

                    newBox.appendChild(lCase);
                }

                // replace DOM
                parBoxElem.replaceChild(newBox, cJsLib.$('tournament-search'));
                
            }
            
            // remove preloader
            this.restoreBasicPreLoader();
        }

        // run the AJAX
        ajax.runAjax();

        tournamentSearchInProgress = false;
	}
};




var plCheckMutName = false; 

/**
 * Check player name in database.
 * 
 * @param  {String}  name   Searched player name.
 * @param  {Integer} id     ID of input element <i>(element for first player has number 1, second has number 2)</i>.
 * @return {Void}           Returns void.
 */
function checkPlayerName(name, id)
{
    // check for player type
    var playerType = 'woman';
    var cls        = null;
    
    if ((cls = cJsLib.getCls(cJsLib.$('mutPlayer-1'))) && cls.match(/set/)) {
        var playerType = 'man';
    }

    if (! cJsLib.empty(name) && name.length >= 2 && ! plCheckMutName) {
        plCheckMutName = true;

        var ajaxIndex = ajaxObject.length;

        // create new AJAX object
        ajaxObject[ajaxIndex] = new XHR();

        // store created AJAX as alias
        var ajax = ajaxObject[ajaxIndex];

        ajax.setMethod('GET')
            .setRequestFile('/res/ajax/check-player-name.php')
            .setVar('name', url.encode(name))
            .setVar('type', playerType)
            .setBasicPreLoaderId('mutualSearchBut', false);

        // redefine function which execute after AJAX
        ajax.onCompletion = function(response)
        {
            var noData     = response.getElementsByTagName('nodata').item(0);
            var muchResult = response.getElementsByTagName('much_results').item(0);
            var focusTo    = true;
            
            if (! cJsLib.isNull(muchResult)) {
                alert(muchResult.firstChild.nodeValue);
                focusTo = false;
            } else if (! cJsLib.isNull(noData)) {
                alert(noData.firstChild.nodeValue);
                focusTo = false;
            } else {
                var player = response.getElementsByTagName('player').item(0);
                var plName = player.getAttribute('name');
                var plUrl  = player.getAttribute('url');

                cJsLib.$('h_player' + id).value   = plUrl;
                cJsLib.$('mutualName' + id).value = plName;
            }
            
            if (cJsLib.$('h_player1').value != '' && cJsLib.$('h_player2').value != '') {
                fillMutual();
            }
            
            if (focusTo) {
                var elemFocus = null;
                
                if (id == 1) {
                    elemFocus = 'mutualName2';
                } else if (id == 2 && cJsLib.$('h_player1').value == '') {
                    elemFocus = 'mutualName1';
                } else if (id == 2 && cJsLib.$('h_player1').value != '') {
                    elemFocus = 'mutualBtn';
                }
                
                cJsLib.$(elemFocus).focus();
            }
            
            // restore search button
            this.restoreBasicPreLoader();
            
            return false;
        }

        // run the AJAX
        ajax.runAjax();

        plCheckMutName = false;
        return false;
    }
};

/**
 * Redirect to mutual page if set all players.
 * 
 * @return {Boolean}
 */
function fillMutual()
{
    if (cJsLib.$('h_player1').value == '' || cJsLib.$('h_player2').value == '') {
        return false;
    }
    
    document.location = cJsLib.$('mutualForm').action + cJsLib.$('h_player1').value + '/' +  cJsLib.$('h_player2').value + '/';
    return true;
};

var lastExpress;
var actGetExpress = false;

/**
 * Get a express message and show it.
 * 
 * @param {Integer} id   ID of express message.
 */
function getExpress(id)
{
    if (! cJsLib.empty(lastExpress) && lastExpress == id) {
        hideExpress(id);
	} else if (! actGetExpress) {
        // delete pointer to auto hide opened express message
        if (cJsLib.isActiveTimeOut()) {
            cJsLib.destroyTimeOut();
        }
        
        actGetExpress = true;
        var ajaxIndex         = ajaxObject.length;
        ajaxObject[ajaxIndex] = new XHR();
        var ajax              = ajaxObject[ajaxIndex];

        ajax.onCompletion = function(responseXML, response)
        {
            if (typeof lastExpress != "undefined" || lastExpress != null) {
                contElem = cJsLib.$('emsg-' + lastExpress);
                cJsLib.setCls(contElem, 'hidden');
                cJsLib.setCls(cJsLib.$('p-emsg-' + lastExpress), 'express');
            }
            
        	mContainer           = cJsLib.$('emsg-' + id);
        	mContainer.innerHTML = response;
        	lastExpress          = id;
        	cJsLib.rmCls(mContainer).setCls(cJsLib.$('p-emsg-' + id), 'express active');
            
            cJsLib.$('p-emsg-' + id).onmouseover = function()
            {
                cJsLib.destroyTimeOut();
            };
            
            cJsLib.$('p-emsg-' + id).onmouseout = function()
            {
                cJsLib.registerTimeOutSh('p-emsg-' + id, 5, 'hide');
            };
        };

        ajax.setMethod('GET').setVar('id', id).setRequestFile('/res/ajax/get-express-message.php');
        ajax.runAjax();
        
        actGetExpress = false;
	}
};

/**
 * Hide content of a express message.
 * 
 * @param {Integer} id   Id of express message.
 */
function hideExpress(id)
{
    cJsLib.setCls(cJsLib.$('emsg-' + id), 'hidden');
    cJsLib.setCls(cJsLib.$('p-emsg-' + lastExpress), 'express');
    cJsLib.$('p-emsg-' + lastExpress).onmouseout = function()
    {};
    
    lastExpress = null;
};

/* Forum functions {{{ */
function hide(element, useXhr)
{
	var e = getElement(element);
	var ufMin = getElement('uf-min');
	var hText = ufMin.firstChild;
	var stat = '0';
	var cl;

	useXhr = (typeof useXhr == 'undefined' || useXhr !== true) ? false : true;

	if ((cl = e.getAttribute('class')) == undefined) {
		cl = e.getAttribute('className');
	}

	if (cl == 'hide' || cl == 'hidden') {
		delCls(e);
		setCls(ufMin, 'up');
		hText.innerHTML = TXT_MINIMIZE;
		ufMin.title = TXT_CLICK_TO_MINIMIZE_FILTER;
		stat = '1';
	} else {
		setCls(e, 'hide');
		setCls(ufMin, 'down');
		hText.innerHTML = MAXIMIZE;
		ufMin.title = TXT_CLICK_TO_MAXIMIZE_FILTER;
	}

	if (useXhr) {
		create_xhr();
		xhr.open('GET', TXT_URL_DISCUSSION + 'ajax/change-filter-stat.php?stat=' + stat);
		xhr.send(null);
	}
};

/**
 * Show reload filter button.
 * 
 * @return void
 */
var last_search;
var last_only;

/**
 * Check value filter by user only button and if value is changed, reload
 * filter.
 * 
 * @return void
 */
function check_search()
{
	var value   = getElement('search-user').value;

	check_length(getElement('search-user'), 64);

	if (value.length >= 3 && value != last_search) {
		if (getElement('filter').value == TXT_ACTIVATE) {
			getElement('filter').disabled = false;
		} else {
			enable_reload();
		}
	} else {
		getElement('filter_reload').disabled = true;
	}

	if (last_search == undefined) {
		last_search = getElement('search-user').value;
	}
};

/**
 * Active / deaktive user filter.
 * 
 * @param integer
 *            $status New filter status.
 *            <ul>
 *            <li><strong>0</status> - disable filter,</li>
 *            <li><strong>1</strong> - enable filter.</li>
 *            </ul>
 * @return void
 */
function u_filter(statue)
{
	var filter_div = getElement('u-filter');
	var stat;
	var xml;
	var sel;

	if (statue == '0') {
		filter_div.setAttribute('class', 'uf-deact');
		filter_div.setAttribute('className', 'uf-deact');
		getElement('filter').value = TXT_ACTIVATE;
		getElement('filter-status').innerHTML = TXT_ACTIVE;
		stat = '0';
	} else {
		filter_div.setAttribute('class', 'uf-act');
		filter_div.setAttribute('className', 'uf-act');
		getElement('filter').value = TXT_DEACTIVATE;
		getElement('filter-status').innerHTML = TXT_DEACTIVE;
		stat = '1';
	}

	xml = '<root>';
	xml += '<status>'+stat+'</status>';
	xml += '<search'+((getElement('search-user').value == '') ? '/>' : ('>'+getElement('search-user').value+'</search>'))
	xml += '<only'+((getElement('user-only').value == '') ? '/>' : ('>'+getElement('user-only').value+'</only>'));

	sel  = getElement('sel-highlight').options;
	if (sel.length > 0) {
		xml += '<h_user>';

		for (var i = 0; i < sel.length; i++) {
			xml += '<user id="'+sel[i].id+'">'+sel[i].text+'</user>';
		}

		xml += '</h_user>';
	} else {
		xml += '<h_user/>';
	}

	sel  = getElement('sel-ignore').options;
	if (sel.length > 0) {
		xml += '<i_user>';

		for (var i = 0; i < sel.length; i++) {
			xml += '<user id="'+sel[i].id+'">'+sel[i].text+'</user>';
		}

		xml += '</i_user>';
	} else {
		xml += '<i_user/>';
	}

	xml += '</root>';

	create_xhr();
	xhr.onreadystatechange = function()
	{
		if (xhr.readyState == 0 || xhr.readyState == 4) {
			if (xhr.status == 200) {
				document.location = getElement('forum').action;
			} else {
				show_xhr_error();
			}
		}
	};
	xhr.open('POST', TXT_URL_DISCUSSION + 'ajax/uf-enable.php');
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send(xml);
};
// }}}

function host(ip, parentElement)
{
	pElem = getElement('id'+parentElement);
	create_xhr();
	xhr.onreadystatechange = function()
	{
		if (xhr.readyState == 0 || xhr.readyState == 4)
		{
			if (xhr.status == 200)
			{
				pElem.innerHTML = xhr.responseText;
				pElem.title = '';
				pElem.style.cursor = 'auto';
			}
			else
			{
				show_xhr_error();
			}
		}
	};
	xhr.open('GET', '/res/ajax/get-hostname.php?ip='+ip, true);
	xhr.send(null);
};

/**
 * Enable filter button.
 * 
 * @return void
 */
function enable_reload()
{
	if (getElement('filter').value == TXT_DEACTIVATE) {
		getElement('filter_reload').disabled = false;
	} else {
		getElement('filter_reload').disabled = false;
		getElement('filter_reload').style.display = '';
	}
};

function reload()
{
	u_filter('1');
};

function add_wrong()
{
	if (getElement('new_wrong').value.length > 3) {
		create_xhr();
		var url = 'word='+getElement('new_wrong').value;

		xhr.onreadystatechange = function()
		{
			if (xhr.readyState == 0 || xhr.readyState == 4) {
				if (xhr.status == 200) {
					getElement('add_result').innerHTML = xhr.responseText;
					getElement('new_wrong').value = '';
				} else {
					show_xhr_error();
				}
			}
		};

		xhr.open('POST', TXT_URL_DISCUSSION + 'ajax/add-expletive.php');
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
		xhr.send(url);
	} else {
		getElement('add_result').innerHTML = TXT_SHORT_WORD;
	}
};

/**
 * Add user to highlighted user combo box.
 * 
 * @param string
 *            $user_id ID user.
 * @param string
 *            $nick Nickname.
 * @return void
 */
function add_high(user_id, nick)
{
	var opt = document.createElement('option');

	if (check_in_combo('sel-highlight', nick) == true) {
		alert(TXT_USER_ALREADY_EXISTS_IN_SELECTION);

		return false;
	}

	if (check_in_combo('sel-ignore', nick) == true) {
		alert(TXT_USER_CANT_ADD_TO_HIGHLIGHTED + "\n" + TXT_USER_ALREADY_IN_IGNORED);

		return false;
	}

	remove_empty('sel-highlight');

	opt.value = user_id;
	opt.setAttribute('id', 'uh'+user_id);
	opt.appendChild(document.createTextNode(nick));
	getElement('sel-highlight').appendChild(opt);
	reload();
}

function check_in_combo(combo, value)
{
	var sel = getElement(combo).options;

	for (var i = 0; i < sel.length; i++) {
		if (sel[i].text == value) {
			return true;
		}
	}

	return false;
}

/**
 * Remove empty value in combo box.
 * 
 * @param string
 *            $element ID of combo box.
 * @return void
 */
function remove_empty(element)
{
	var e_name;

	if (element == 'sel-ignore') {
		e_name = 'ui0';
	} else {
		e_name = 'uh0';
	}

	if (getElement(e_name) != null) {
		sel = getElement(element);
		sel.removeChild(sel.options[getElement(e_name).index]);
	}
}

/**
 * Enable button.
 * 
 * @param string
 *            $element Button ID, which you can enable.
 * @return void
 */
function enable_clear(element)
{
	var e   = getElement('rem-'+element);
	var sel = getElement('sel-'+element);

	if (sel.options.length > 0) {
		e.setAttribute('disabled', '');
		e.disabled = false;
	}
}

/**
 * Remove selected user from multi combo box.
 * 
 * @param string
 *            $element Parent element, where need remove users from list.
 * @return void
 */
function rem_sel_user(element)
{
	var e = getElement(element);
	var e_rem;

	for (var i = e.options.length-1; i >= 0; i--) {
		if (e.options[i].selected == true) {
			e.removeChild(e.options[i]);
		}
	}

	if (e.id == 'sel-ignore') {
		e_rem = 'ignore';
	} else {
		e_rem = 'highlight';
	}

	if (e.options.length == 0) {
		var opt = document.createElement('option');
		opt.value = '';
		opt.setAttribute('id', 'u'+(e_rem == 'ignore' ? 'i' : 'h')+'0');
		opt.appendChild(document.createTextNode(''));
		getElement('sel-'+e_rem).appendChild(opt);
	}

	getElement('rem-'+e_rem).disabled = true;
	enable_reload();
}

/**
 * Enable / disable add user button.
 * 
 * @param object
 *            $element Object of element, which enable or disable.
 * @return void.
 */
function enable_add(element)
{
	var te = 'add-'+(element == 'h' ? 'highlight' : 'ignore');
	var e  = getElement(te);

	if (e.value.length > 0) {
		getElement('b'+te).disabled = false;
	} else {
		getElement('b'+te).disabled = true;
	}
}

function checkLoginFrm()
{
    if (cJsLib.empty(cJsLib.$('loginName').value)) {
        alert(TXT_BAD_USERNAME_LOGIN);
        return false;
    }
    
    if (cJsLib.empty(cJsLib.$('loginPass').value)) {
        alert(TXT_BAD_PASSWORD_LOGIN);
        return false;
    }
    
    return true;
}

// user search functions {{{
var user;
var sel;
function add_user(element)
{
	var id = element.name;

	if (id == 'add_highlight') {
		user = getElement('add-highlight');
		sel  = getElement('sel-highlight');

		if (check_in_combo('sel-ignore', user.value)) {
			alert(TXT_USER_CANT_ADD_TO_HIGHLIGHTED + "\n" + TXT_USER_ALREADY_IN_IGNORED);
			user.value = '';

			return false;
		}
	} else {
		user = getElement('add-ignore');
		sel  = getElement('sel-ignore');

		if (check_in_combo('sel-highlight', user.value)) {
			alert(TXT_USER_CANT_ADD_TO_IGNORED + "\n" + TXT_USER_ALREADY_IN_HIGHLIGHTED);
			user.value = '';

			return false;
		}
	}

	if (sel.options.length >= 50) {
		alert(TXT_EXCEED_MAXIMUM_USERS);

		return false;
	}

	if (check_in_combo(sel.id, user.value)) {
		alert(TXT_USER_ALREADY_EXISTS_IN_SELECTION);
		user.value = '';

		return false;
	}

	if (user.value != '') {
		create_xhr();
		xhr.onreadystatechange = function()
		{
			if (xhr.readyState == 0 || xhr.readyState == 4) {
				if (xhr.status == 200) {
					var opt = document.createElement('option');

					if (xhr.responseXML.getElementsByTagName('user')[0].hasChildNodes()) {
						var uid;
						if (xhr.responseXML.getElementsByTagName('id')[0].firstChild.textContent == undefined) { // M$ fix
							uid   = xhr.responseXML.getElementsByTagName('id')[0].firstChild.text;
							value = xhr.responseXML.getElementsByTagName('nick')[0].firstChild.text;
							nick  = xhr.responseXML.getElementsByTagName('nick')[0].firstChild.text;
						} else { // valid browsers
							uid   = xhr.responseXML.getElementsByTagName('id')[0].firstChild.textContent;
							value = xhr.responseXML.getElementsByTagName('nick')[0].firstChild.textContent;
							nick  = xhr.responseXML.getElementsByTagName('nick')[0].firstChild.textContent;
						}

						remove_empty(sel.id);

						opt.value = value
						opt.setAttribute('id', 'u'+(sel.id == 'sel-highlight' ? 'h' : 'i')+uid);
						opt.appendChild(document.createTextNode(nick));
						sel.appendChild(opt);
						user.value = '';

						if (getElement('filter').value == TXT_ACTIVATE) {
							getElement('filter').disabled = false;
						} else {
							enable_reload();
						}

					} else {
						alert(TXT_USER_DOES_NOT_EXISTS);
					}
				} else {
					show_xhr_error();
				}
			}
		};
        
		xhr.open('GET', TXT_URL_DISCUSSION + 'ajax/check_user.php?user=' + user.value, true);
		xhr.send(null);
	}
}
// }}}

/**
 * Reset all settings on filter and deactive it.
 * 
 * @return void
 */
function reset_filter()
{
	if (confirm(TXT_REALLY_DELETE_FILTER_SETTINGS)) {
		getElement('search-user').value = '';
		getElement('user-only').value = '';

		var e = getElement('sel-highlight');
		for (var i = e.options.length-1; i >= 0; i--) {
			e.removeChild(e.options[i]);
		}

		e = getElement('sel-ignore');
		for (var i = e.options.length-1; i >= 0; i--) {
			e.removeChild(e.options[i]);
		}

		u_filter('0');
	}
}

/**
 * Add user to only user filter.
 * 
 * @param string
 *            $nick Nickname.
 * @return void
 */
function add_only(nick)
{
	if (check_in_combo('sel-ignore', nick) == true) {
		alert(TXT_USER_CAN_NOT_ADD + "\n" + TXT_USER_IS_ALREADY_IGNORED);
			return false;
	}

	getElement('user-only').value = nick;
	reload();
}

/**
 * Add user to ignored combo box.
 * 
 * @param integer
 *            user_id User ID.
 * @param sring
 *            nick Nickname.
 * @return void
 */
function add_ignore(user_id, nick)
{
	var opt = document.createElement('option');
	var err = false;
	var mes = '';

	if (check_in_combo('sel-ignore', nick) == true) {
		mes = TXT_USER_ALREADY_EXISTS_IN_SELECTION;
		err = true;
	}

	if (err === false && getElement('user-only').value == nick) {
		mes = TXT_USER_CANT_ADD_TO_IGNORED + "\n" + TXT_USER_IS_ALREADY_IN_FIELD_SHOW_ONLY_USERS;
		err = true;
	}

	if (err === true) {
		alert(mes);

		return false;
	}

	if (confirm(TXT_REALLY_IGNORE_USER)) {
		remove_empty('sel-ignore');

		opt.value = user_id;
		opt.setAttribute('id', 'ui'+user_id);
		opt.appendChild(document.createTextNode(nick));
		getElement('sel-ignore').appendChild(opt);
		reload();

		if (getElement('filter').value == TXT_ACTIVATE) {
			getElement('filter').disabled = false;
		}
	}
}

/**
 * Mark all admins info as readed and remove it.
 * 
 * @return void
 */
function closePermInfo()
{
    if (! closingPermInfo) {
        closingPermInfo = true;

        var ajaxIndex = ajaxObject.length;

        // create new AJAX object
        ajaxObject[ajaxIndex] = new XHR();

        // store created AJAX as alias
        var ajax = ajaxObject[ajaxIndex];

        ajax.setMethod('GET')
            .setRequestFile(TXT_URL_DISCUSSION + 'ajax/close-perm-info.php');

        // redefine function which execute after AJAX
        ajax.onCompletion = function(response)
        {
            var actInfo = null;
            if ((actInfo = cJsLib.$('active-info')) && cJsLib.isObject(actInfo)) {
                actInfo.parentNode.removeChild(actInfo);
            }
        }

        // run the AJAX
        ajax.runAjax();

        closingPermInfo = false;
    }
};

/**
 * Check value filter by user only button and if value is changed, reload
 * filter.
 * 
 * @return void
 */
function check_only()
{
	var value = getElement('user-only').value;
	var sel = getElement('sel-ignore').options;
	last_only = getElement('user-only');

	check_length(getElement('user-only'), 64);

	if (value != last_only) {
		for (var i = 0; i < sel.length; i++) {
			if (sel[i].text == value && sel[i].text != '') {
				alert(TXT_USER_IS_IGNORED_CANNOT_SHOW_HIS_CONTRIBUTIONS_ONLY);
				getElement('user-only').value = '';

				return false;
			}
		}

		if (value != '') {
			create_xhr();
			xhr.onreadystatechange = function()
			{
				if (xhr.readyState == 0 || xhr.readyState == 4) {
					if (xhr.status == 200) {
						var opt = document.createElement('option');
						var xml = xhr.responseXML.getElementsByTagName('user')[0];

						if (xml.hasChildNodes()) {
							if (xhr.responseXML.getElementsByTagName('nick')[0].firstChild.textContent == undefined) { // M$ fix
								nick = xhr.responseXML.getElementsByTagName('nick')[0].firstChild.text;
								id   = xhr.responseXML.getElementsByTagName('id')[0].firstChild.text;
								next = xhr.responseXML.getElementsByTagName('next')[0].firstChild.text;
							} else {
								nick = xhr.responseXML.getElementsByTagName('nick')[0].firstChild.textContent;
								id   = xhr.responseXML.getElementsByTagName('id')[0].firstChild.textContent;
								next = xhr.responseXML.getElementsByTagName('next')[0].firstChild.textContent;
							}

							if (next == '1') {
								if (confirm(TXT_SPECIFIED_USER_DOES_NOT_EXISTS + "\n" + TXT_NEAREST_USER_IS + nick + ".\n" . TXT_DO_YOU_CAN_FILL_THIS_USER)) {
									sel = getElement('sel-ignore').options;
									for (var i = 0; i < sel.length; i++) {
										if (sel[i].text == nick) {
											alert(TXT_USER_IS_ALREADY_IN_INGNORED_CAN_NOT_FILTER_HIS_CONTRIBUTIONS_ONLY);
											getElement('user-only').value = '';

											return false;
										}
									}

									getElement('user-only').value = nick;
									last_only = nick;

									if (getElement('filter').value == TXT_DEACTIVATE) {
										enable_reload();
									} else {
										getElement('filter').disabled = false;
									}
								} else {
									getElement('user-only').value = '';
								}
							} else {
								getElement('user-only').value = nick;
								last_only = nick;

								if (getElement('filter').value == TXT_DEACTIVATE) {
									enable_reload();
								} else {
									getElement('filter').disabled = false;
								}
								// enable_reload();
							}
						} else if (getElement('user-only').value == '') {
							last_only = nick;

							if (getElement('filter').value == 'c') {
								enable_reload();
							} else {
								getElement('filter').disabled = false;
							}
							// enable_reload();
						} else {
							alert(TXT_USER_DOES_NOT_EXISTS);
						}
					}
				}
			};
            
			xhr.open('GET', TXT_URL_DISCUSSION + 'ajax/check_user.php?user='+value);
			xhr.send(null);
		} else {
			enable_reload();
		}
	}
}


var streamsTimeout = null;
var visible = null;
 
function showStreams(id)
{
	document.getElementById('streams'+id).style.display = 'block';
	if (streamsTimeout != null) clearTimeout(streamsTimeout);
	if (visible != null && visible != id) doHideStreams(visible);
	visible = id;
}

function hideStreams(id)
{
	streamsTimeout = setTimeout('doHideStreams('+id+')', 300);
}

function doHideStreams(id)
{
	getElement('streams'+id).style.display = 'none';
}


function poll_vote(pollID)
{
	var vote = 0;
	var r = document.forms['poll'+pollID].elements['vote'];
	for (var i = 0; i < r.length; i++) if(r[i].checked) vote = r[i].value;
	if (vote != 0) poll_submit(pollID, vote);
}

var pollVoting = false;

function poll_submit(pollID, voteID)
{
	if (!pollVoting)
	{
		pollVoting = true;
		
		var ajaxIndex = ajaxObject.length;

		// create new AJAX object
		ajaxObject[ajaxIndex] = new XHR();

		// store created AJAX as alias
		var ajax = ajaxObject[ajaxIndex];

		ajax.element = 'poll-' + pollID;

		// set requested script file
		ajax.method = 'GET';
		ajax.requestFile = '/res/ajax/poll-vote.php';

		// set up URL parameter
		ajax.setVar('pollID', pollID);
		ajax.setVar('voteID', voteID);

		// run the AJAX
		ajax.runAjax();
		
		pollVoting = false;
	}
}

function moreButtonClick(type, back, more)
{
	var el = document.getElementById(type + '-more');
	var show = (el.style.display == 'none');
	el.style.display = show ? 'block' : 'none';
	document.getElementById(type + '-more-b').innerHTML = '<span class="l">&nbsp;</span>' + (show ? back : more);
}

function playerInjuriesShow(type)
{
	document.getElementById('injuries-' + (type == 'full' ? 'short' : 'full')).style.display = 'none';
	document.getElementById('injuries-' + type).style.display = 'block';
}


var tzOpen = false;
var tzLoaded = false;
function tz(url)
{
	var e = document.getElementById('timezones');
	if (tzOpen)
	{
		e.style.display = 'none';
		tzOpen = false;
	}
	else
	{
		e.style.display = 'block';
		tzOpen = true;
		if (!tzLoaded)
		{
			var ajaxIndex = ajaxObject.length;

			// create new AJAX object
			ajaxObject[ajaxIndex] = new XHR();

			// store created AJAX as alias
			var ajax = ajaxObject[ajaxIndex];

			ajax.element = 'timezones';
			
			ajax.setVar('url', url);

			// set requested script file
			ajax.method = 'GET';
			ajax.requestFile = '/res/ajax/timezones.php';

			// run the AJAX
			ajax.runAjax();
			
			tzLoaded = true;
		}
	}
}

function tzover(e)
{
	e.className = 'over';
}
function tzout(e)
{
	e.className = '';
}

var tzHideTimeout = null;
function tzHide()
{
	tzHideTimeout = setTimeout('tzDoHide()', 1000);
}
function tzStopHiding()
{
	if (tzHideTimeout != null) clearTimeout(tzHideTimeout);
}
function tzDoHide()
{
	document.getElementById('timezones').style.display = 'none';
	tzOpen = false;
}