function _$(id){ return document.getElementById(id);}

function initTopMenu(){
	var str = location.href;
	str = str.replace(/(http:\/\/[^\/]+\/[^\/]+).*/,'$1/');
	var hEls = _$("nav").getElementsByTagName("LI");
	for (var i=0, len=hEls.length; i<len; i++) {
		hEls[i].onmouseover=function() { this.className+=" hover"; }
		hEls[i].onmouseout=function() { this.className=this.className.replace(/(.*)hover/, "$1"); }
		try{ 
			As = hEls[i].getElementsByTagName('A');
			tmp = As[0].href.split('/');
			if(tmp.length>2){
				if(As[0].href==str){
					As[0].className+=' active';
				}
			}
		}catch(e){}
	}
}
function initLangSel(){
	if(!_$('langsel')) return;
	LIs = document.getElementById("langsel").getElementsByTagName('LI');
	for (i in LIs) {
		LIs[i].onmouseover=function(){this.className+=" hover";this.className=this.className.replace(/^\s+/,'');}
		LIs[i].onmouseout=function(){this.className=this.className.replace(/(.*)hover/,'$1').replace(/^\s+/,'');}
		try{ 
			As = LIs[i].getElementsByTagName('A');
			tmp = As[0].href.split('/');
			if(tmp.length>2){
				if(As[0].href==str){
					As[0].className+=' active';
				}
			}
		}catch(e){}
    }
}
function initPaginator(){
	if(!_$('paginator')) return;
	if(_$('paginator').getAttribute('worked') == 'no') return;

	if(location.href.match(/(.*)page([0-9]+)(.*)/i)){
		currentPage = (location.href.replace(/(.*)page([0-9]+)(.*)/i,'$2'));
	}else{
		currentPage = 1;
	}
	As = _$('paginator').getElementsByTagName('A');
	for(i in As){
			
		try{	if(i==0 && currentPage!=1) As[i].href = location.href.replace(/page[0-9]+/,'page'+(parseInt(currentPage)-1));
			if(parseInt(i))m = i;
			if(As[i].innerHTML==currentPage){
				As[i].className+=' active';
			}
		}catch(e){}
	} 
	if(m!=(parseInt(currentPage)+1)) As[m].href = location.href.replace(/page[0-9]+/,'page'+(parseInt(currentPage)+1));
	document.onkeyup = function(e){
		if(currentPage>1 && isCtrlLeftPressed(e)){
			newHref = location.href.replace(/page[0-9]+/,'page'+(parseInt(currentPage)-1));
			location.href= newHref;
		}else if(isCtrlRightPressed(e)){
			newHref = location.href.replace(/page[0-9]+/,'page'+(parseInt(currentPage)+1));
			location.href= newHref;
		}
	}
}
function initTabs(){
	LIs = document.getElementsByTagName('LI');
	for(i in LIs){
		try {
			As = LIs[i].getElementsByTagName('A');
			tabName = '#'+As[0].href.replace(/^.+#/,'');
			if(_$(tabName)){
				As[0].onclick = function(){switchTab(this);this.blur();return false;};
			}
		}catch(e){}
	}
	tmp=location.href.split('#');
	if(tmp.length==2){
		clickA(tmp[1]);
	}
}
function clickA(aName){
	LIs = document.getElementsByTagName('LI');
	for(i in LIs){
		try {
			As = LIs[i].getElementsByTagName('A');
			tabName = '#'+As[0].href.replace(/^.+#/,'');
			
			if(('#'+aName)==tabName && _$(tabName)){
				switchTab(As[0]);
			}
		}catch(e){}
	}
}
function switchTab(a){
	tabName='#'+a.href.replace(/^.+#/,'');
	if(_$(tabName)){
		if(a.parentNode.parentNode.tagName=='UL'){
			LIs = a.parentNode.parentNode.getElementsByTagName('LI');
			for(i in LIs){
				try {
					As = LIs[i].getElementsByTagName('A');
					if(As[0].className=='active'){
						As[0].className='';
						oldTabName = '#'+As[0].href.replace(/^.+#/,'');
						if(_$(oldTabName)){
							_$(oldTabName).style.display='none';
							break;
						}
					}
				}catch(e){}
			}
		}
		a.className = 'active';
		_$(tabName).style.display="block";
	}
}
function showNote(formName,inpName,msg){
	if(!msg) return;
	if(!_$(formName)) return;
	_$(formName)[inpName].style.border='dashed 1px #f88';
	cont = _$(formName)[inpName].parentNode;

	if(cont.lastChild.id == "note_"+cont.id){
		span = cont.lastChild;
		span.innerHTML = "";
	}else{
		span = document.createElement('SPAN');
		span.id = "note_"+cont.id;
	}
	span.innerHTML = msg;

	cont.appendChild(span);
	cont.style.paddingBottom='2px';
}

function showProcessIndicatorFor(forObj){
	var offset = $(forObj).offset();
	if(!$('#processIndicator').attr('id')){
		var pi = document.createElement('DIV');
		var pic = document.createElement('DIV');
		pic.appendChild(pi);
		pic.id='processIndicator';
		document.body.appendChild(pic);
	}
	$('#processIndicator').css('top',offset.top);
	$('#processIndicator').css('left',offset.left);
	$('#processIndicator').width($(forObj).width()-2);
	$('#processIndicator').height($(forObj).height()-2);
	$('#processIndicator').show();
}
function hideProcessIndicator(){
	$('#processIndicator').hide();
}                             

var userLinkMenuIsOpen = false;
var preventClose = false;
var gloTimeout = null;
var gloA = null;

function showUserLinkMenu(a,e){
	if(gloA && userLinkMenuIsOpen && gloA!=a) hideUserLinkMenu();
	var offset = $(a).offset();
	if(userLinkMenuIsOpen) return;

	if(e){
		$('#userLinkMenu').css('top',e.pageY);
		$('#userLinkMenu').css('left',e.pageX);
	}else{
		$('#userLinkMenu').css('top',offset.top+$(a).height());
		$('#userLinkMenu').css('left',offset.left);
	}
	$('#userLinkMenu').show();
	userLinkMenuIsOpen = true;
	gloA = a;
}
function hideUserLinkMenu(){
	if(!userLinkMenuIsOpen || preventClose) return;
	$('#userLinkMenu').hide();
	if(gloTimeout) clearTimeout(gloTimeout);
	gloTimeout = null;
	userLinkMenuIsOpen = false;
	gloA = null;
}
function cancelTimer(t){
	if(t) clearTimeout(t);
	t = null;
}
function hideUserLinkMenuDelayed(){
	if(!userLinkMenuIsOpen || preventClose){
		return;
	}
	gloTimeout=setTimeout(hideUserLinkMenu,100);
}
function showPrivateMessageForm(){
	createWindow({caption:'Private message',statusLeft:'<a href="javascript:closeWindow();">CANCEL</a>',statusRight:'<a href="javascript:trySubmitPrivateMessage()">SUBMIT</a>'});
	bindWindowContent('userMsgForm');
	$('#userMsgForm').show();
	setWindowSize(400,235);
	$(document).bind('keyup',function(e){ if(isEscPressed(e)) closeWindow()});
	showWindow();
	$('#pMsg').focus();
	centerWindow();
	tryLoadUserParams(gloA.href.replace(/.+\/(\d+)\/.*/,'$1'));
	$('#pMsg').unbind('keyup');
	$('#pMsg').keyup(function(e){if(isCtrlEnterPressed(e)) trySubmitPrivateMessage()});
	return false;
}
function bindWindowContent(id){
	if(window.bindedWindowContentId) unbindWindowContent();
	$('#windowContent').append($('#'+id));
	window.bindedWindowContentId = id;
}
function unbindWindowContent(){
	if(!window.bindedWindowContentId) return;
	$('#'+window.bindedWindowContentId).hide();
	$(document.body).append($(window.bindedWindowContentId));
	window.bindedWindowContentId = null;
}
function tryLoadUserParams(id){
	showProcessIndicatorFor('#userMsgForm');
	$.post('/user/messages/do/',{'action':'getUserParams','id':id},onLoadUserParams,'json');
}
function onLoadUserParams(data){
	hideProcessIndicator();
	if(!data.error){
		$('#pAvt').attr('src',data.src);
		$('#pName').html(data.nickname);
		$('#pInfo').html(data.info);
		$('#pLang').html(data.lang);
		$('#pTo').attr('value',data.id);
		$('#pMsg').attr('disabled',false);
	}else{
		alert(data.error);
	}
}
function trySubmitPrivateMessage(){
	$('#pMsg').attr('disabled',true);
	showProcessIndicatorFor('#pMsg');
	$.post('/user/messages/do/',{'action':'saveMessage','to':$('#pTo').val(),'message':$('#pMsg').val()},onSubmitingPrivateMessage,'json');
}
function onSubmitingPrivateMessage(data){
	hideProcessIndicator();
	$('#pMsg').attr('disabled',false);
	if(!data.error){
		$('#pMsg').val('');
		hideWindow();
		unbindWindowContent();
	}else{
		alert(data.error);
	}
}
function showFriendRequestForm(){
	createWindow({caption:'Send friend request',statusLeft:'<a href="javascript:closeWindow();">CANCEL</a>',statusRight:'<a href="javascript:trySubmitFriendRequest()">SUBMIT</a>'});
	bindWindowContent('userMsgForm');
	$('#userMsgForm').show();
	setWindowSize(400,235);
	$(document).bind('keyup',function(e){ if(isEscPressed(e)) closeWindow()});
	showWindow();
	$('#pMsg').focus();
	centerWindow();
	$('#pMsg').unbind('keyup');
	$('#pMsg').keyup(function(e){if(isCtrlEnterPressed(e)) trySubmitFriendRequest()});
	tryLoadUserParams(gloA.href.replace(/.+\/(\d+)\/.*/,'$1'));
	return false;
}
function trySubmitFriendRequest(){
	$('#pMsg').attr('disabled',true);
	showProcessIndicatorFor('#pMsg');
	$.post('/user/friends/do/',{'action':'saveRequest','to':$('#pTo').val(),'message':$('#pMsg').val()},onSubmitingPrivateMessage,'json');
}

var rus={
'113':'й',
'119':'ц',
'101':'у',
'114':'к',
'116':'е',
'121':'н',
'117':'г',
'105':'ш',
'111':'щ',
'112':'з',
'91':'х',
'93':'ъ',
'97':'ф',
'115':'ы',
'100':'в',
'102':'а',
'103':'п',
'104':'р',
'106':'о',
'107':'л',
'108':'д',
'59':'ж',
'39':'э',
'122':'я',
'120':'ч',
'99':'с',
'118':'м',
'98':'и',
'110':'т',
'109':'ь',
'44':'б',
'46':'ю',
'47':'.',

'81':'Й',
'87':'Ц',
'69':'У',
'82':'К',
'84':'Е',
'89':'Н',
'85':'Г',
'73':'Ш',
'79':'Щ',
'80':'З',
'123':'Х',
'125':'Ъ',
'65':'Ф',
'83':'Ы',
'68':'В',
'70':'А',
'71':'П',
'72':'Р',
'74':'О',
'75':'Л',
'76':'Д',
'58':'Ж',
'34':'Э',
'90':'Я',
'88':'Ч',
'67':'С',
'86':'М',
'66':'И',
'78':'Т',
'77':'Ь',
'60':'Б',
'62':'Ю',
'63':','
};

var eng={
'1081':'q',
'1094':'w',
'1091':'e',
'1082':'r',
'1077':'t',
'1085':'y',
'1075':'u',
'1096':'i',
'1097':'o',
'1079':'p',
'1093':'[',
'1098':']',
'1092':'a',
'1099':'s',
'1074':'d',
'1072':'f',
'1087':'g',
'1088':'h',
'1086':'j',
'1083':'k',
'1076':'l',
'1078':';',
'1101':'\'',
'1103':'z',
'1095':'x',
'1089':'c',
'1084':'v',
'1080':'b',
'1090':'n',
'1100':'m',
'1073':',',
'1102':'.',
'46':'/',

'1049':'Q',
'1062':'W',
'1059':'E',
'1050':'R',
'1045':'T',
'1053':'Y',
'1043':'U',
'1064':'I',
'1065':'O',
'1047':'P',
'1061':'{',
'1066':'}',
'1060':'A',
'1067':'S',
'1042':'D',
'1040':'F',
'1055':'G',
'1056':'H',
'1054':'J',
'1051':'K',
'1044':'L',
'1046':':',
'1069':'"',
'1071':'Z',
'1063':'X',
'1057':'C',
'1052':'V',
'1048':'B',
'1058':'N',
'1068':'M',
'1041':'<',
'1070':'>',
'44':'?'

};


function ToolTipShow(where,title,content){
var stip='';
stip="<div id='theToolTip'>"+
	"<div id='ToolTipTextWrap'>"+title+"</div>"+
		"<p>"+content+"</p>"+
	"</div>";
//	"<img src='/images/tooltip.gif' id='ToolTipPointer'>";

eld=document.createElement('DIV');
eld.id='ToolTip';
eld.name='ToolTip';
eld.innerHTML = stip;
eld.className='ToolTip';
c = _$(where).parentNode;
if(_$('ToolTip')) c.replaceChild(eld,_$('ToolTip')); else c.appendChild(eld);


}


function ToolTipHide(where){
	c = _$(where).parentNode;
	c.removeChild(_$('ToolTip'));
}


var why_drag=''; // x or y if param empty, then x and y
var outParamX=0;
var outParamY=0;
function drag(elementToDrag, why_drag, event, parentN, callBackf) {
	if(parentN) { var parentNx = _$(parentN).offsetLeft, parentNy = _$(parentN).offsetTop, parentNw = $('#'+parentN).width(), parentNh = $('#'+parentN).height(); }

    var startX = event.clientX, startY = event.clientY;
    var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;
    var deltaX = startX - origX, deltaY = startY - origY;
    if (document.addEventListener) {  // DOM Level 2 event model
        document.addEventListener("mousemove", moveHandler, true);
        document.addEventListener("mouseup", upHandler, true);
    }
    else if (document.attachEvent) {  // IE 5+ Event Model
        elementToDrag.setCapture( );
        elementToDrag.attachEvent("onmousemove", moveHandler);
        elementToDrag.attachEvent("onmouseup", upHandler);
        elementToDrag.attachEvent("onlosecapture", upHandler);
    }
    else {  // IE 4 Event Model
        var oldmovehandler = document.onmousemove; // used by upHandler( )
        var olduphandler = document.onmouseup;
        document.onmousemove = moveHandler;
        document.onmouseup = upHandler;
    }

    if (event.stopPropagation) event.stopPropagation( );  // DOM Level 2
    else event.cancelBubble = true;                      // IE


    if (event.preventDefault) event.preventDefault( );   // DOM Level 2
    else event.returnValue = false;                     // IE

    /**
     * This is the handler that captures mousemove events when an element
     * is being dragged. It is responsible for moving the element.
     **/
    function moveHandler(e) {
        if (!e) e = window.event;  // IE Event Model

        // Move the element to the current mouse position, adjusted as
        // necessary by the offset of the initial mouse-click.

//$('#translate').html(parentNw);
	fx=true; fy=true;
        if(why_drag!='y') if((e.clientX - deltaX)>=0 && (e.clientX - deltaX)<=parentNw-$('#'+elementToDrag.id).width()) elementToDrag.style.left = (e.clientX - deltaX) + "px"; else fx=false;
        if(why_drag!='x') if((e.clientY - deltaY)>=0 && (e.clientY - deltaY)<=parentNh-$('#'+elementToDrag.id).height()) elementToDrag.style.top = (e.clientY - deltaY) + "px"; else fy=false;
	outParamX = (e.clientX - deltaX);
	outParamY = (e.clientY - deltaY);

	if(typeof(window[callBackf]) == 'function' && fx && fy) 
		window[callBackf].call(window,{'x':outParamX,'y':outParamY});

        // And don't let anyone else see this event.
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
        else e.cancelBubble = true;                  // IE
    }

    /**
     * This is the handler that captures the final mouseup event that
     * occurs at the end of a drag.
     **/
    function upHandler(e) {
        if (!e) e = window.event;  // IE Event Model

        if (document.removeEventListener) {  // DOM event model
            document.removeEventListener("mouseup", upHandler, true);
            document.removeEventListener("mousemove", moveHandler, true);
        }
        else if (document.detachEvent) {  // IE 5+ Event Model
            elementToDrag.detachEvent("onlosecapture", upHandler);
            elementToDrag.detachEvent("onmouseup", upHandler);
            elementToDrag.detachEvent("onmousemove", moveHandler);
            elementToDrag.releaseCapture( );
        }
        else {  // IE 4 Event Model
            document.onmouseup = olduphandler;
            document.onmousemove = oldmovehandler;
        }

        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
        else e.cancelBubble = true;                  // IE
    }
}

function setCookies(name, value, age, path, domain, secure) {
        var curCookie = name + "=" + escape(value) +
                ((age) ? "; max-age=" + (age*24*60*60) : "") +
		"; path=/" +
//                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "");
        
                document.cookie = curCookie;
}
function getCookie(name) {
        var prefix = name + "=";
        var cookieStartIndex = document.cookie.indexOf(prefix);
        if (cookieStartIndex == -1)
                return null;
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length;
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}
function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" + 
		"; path=/" +
//                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; max-age=" + (-1*24*60*60);
        }
}

function readParam(block){
	if(getCookie(block) == 'on') return 'off'; else return 'on';
}
function setCookie(block,flag){
	setCookies(block,flag,30);
	readCookie(block);
}
function readCookie(block,p){

	if (!getCookie(block) || getCookie(block)=='undefined') {
	setCookies(block,'on',30);
	}

	if(getCookie(block) == 'off') {
		_$(block+'_img').src='/images/v.gif';
		_$(block+'_img').setAttribute('mode','on');
		if(p) _$(block).style.display = 'none';
//		cookie[block] = 'off';
	}
	if(getCookie(block) == 'on'){
		_$(block+'_img').src='/images/vo.gif';
		_$(block+'_img').setAttribute('mode','on');
		if(p) _$(block).style.display = 'block';
//		cookie[block] = 'on';
	}

}

function showCover(){
	$('#undercover').show();
	$('#undercover').width($(document).width());
	$('#undercover').height($(document).height());
	
	$('#cover').show();
	$('#cover').width($(document).width());
	$('#cover').height($(document).height());
}
function hideCover(){
	$('#undercover').hide();
	$('#cover').hide();
}
function createWhiteBlock(id,data){
	var html ='<div id="'+id+'" style="position:absolute;z-index:600;display:none;left:0px;top:0px;">';
		html+='<a href="" class="closecross" onclick="closeWhiteBlock($(this).parents(\'div\').attr(\'id\'));return false;"><img title="Закрыть" src="/images/cross.gif"></a>'
		html+='<table class="wir5"><tr><td class="lt"></td><td class="mt"></td><td class="rt"></td></tr><tr><td class="lm"></td><td class="mm" style="padding:10px;">'+data+'</td><td class="rm"></td></tr><tr><td class="lb"></td><td class="mb"></td><td class="rb"></td></tr></table>';
		html+='</div>';
	$(document.body).append(html);
}
function showWhiteBlock(id){
	if($('#'+id).length<1){
		createWhiteBlock(id);
	}
	$('#'+id).show();
}
function hideWhiteBlock(id){
	$('#'+id).hide();
}
function closeWhiteBlock(id){
	hideWhiteBlock(id);
	hideCover();
}
function centerWhiteBlock(id){
	$('#'+id).css('left',$(document.body).width()/2-$('#'+id).width()/2);
	$('#'+id).css('top',$(document.body).height()/2-$('#'+id).height()/2);
}                  
function removeWhiteBlock(id){
	$('#'+id).remove();
	hideCover();
}
function toggleBlock(ob, div_id, path){
	
	path1 = path.substr(0, (path.length-1));
	
	d = new Date();
	d = new Date(d.getTime()+90*24*60*60*1000);
	
	if(getCookie(div_id) == 1 || getCookie(div_id) === null){
		document.cookie = div_id+"=0; path="+path+";expires="+d+";";
		document.cookie = div_id+"=0; path="+path1+";expires="+d+";";
			
		ob.src = '/images/bottom_arr.gif';
	} else {
		document.cookie = div_id+"=1; path="+path+";expires="+d+";";
		document.cookie = div_id+"=1; path="+path1+";expires="+d+";";
	
		ob.src = '/images/top_arr.gif';
	}
	$("#"+div_id).slideToggle("slow");
}

function strip_tags(str, allowed_tags) {
    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
 
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
  
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
 
    return str;
}

function errAlert(el_id, mess){
	FormValidator.showFieldError('#'+el_id, mess);
	setTimeout(function(){FormValidator.hideFieldError('#'+el_id);}, 1000);
}

function drawClubTypeSelector(el_id){
	var arr = {'1':'Открытый', '0':'Закрытый'};
	$(document).ready(function(){
		RoundSelector.build(el_id, arr, parseInt($('#'+el_id).val()));
	});
	
}

