window.addEvent('load',function(){
	if ($$('.tabs').length) enableTabs();
	if ($$('.winningswitch').length) enableWinnings();
	enablePopUps();
	if ($$('.usersearch').length) enableSearch();
	if ($('user_search')) enableUserSearch();
	if ($('profile_winnings')) enableWinSort();
	if ($$('.remote')) enableRemote();
	
	if ($('loginForm')) {
		$('loginForm').addEvent('keydown', function(e){
			if (e.key == 'enter') {
				$('loginForm').submit();
			}
		});
	}
	
	if ($('blog_post')) {
		enableBlockquotes();
	}

});


function enableWinSort() {
  new SortingTable( 'profile_winnings', {
    zebra: true,                        // Stripe the table, also on initialize
    details: false,                     // Has details every other row
    paginator: false,                   // Pass a paginator object
    dont_sort_class: 'nosort',          // Class name on th's that don't sort
    forward_sort_class: 'forward_sort', // Class applied to forward sort th's
    reverse_sort_class: 'reverse_sort'  // Class applied to reverse sort th's
  });
}

function lockTopic(topic_id){
	
	new Request.HTML({'method': 'get','url': root+'rpc.php','onComplete': function(a,b,c,d){

		if (c.substring(0,4)=='true') {

            /*if (c.substring(5)=='1') {
        		$(document).getElement('.user_avatar').adopt(
                    new Element('div', {'class' : 'locked'})
                );
            }else {
                $(document).getElement('.user_avatar .locked').dispose();
            }*/
		}
	}}).send('action=lock_topic&topic_id='+topic_id);
}

function deleteTopic(topic_id){
	
	new Request.HTML({'method': 'get','url': root+'rpc.php','onComplete': function(a,b,c,d){
		if (c=='true') {
			$('topic-'+topic_id).get('tween', {property: 'opacity', onComplete: function(){
				$('topic-'+topic_id).dispose();
			}}).start(0);

		}
	}}).send('action=delete_topic&topic_id='+topic_id);
}

function deleteTopicInside(topic_id){
	if (!confirm('Действительно ли вы хотите удалить запись?')) {
		return false;
	}
	new Request.HTML({'method': 'get','url': root+'rpc.php','onComplete': function(a,b,c,d){
		if (c=='true') {
			location.href = '/';
		}
	}}).send('action=delete_topic&topic_id='+topic_id);
}

function deleteComm(comm_id, comm_type){
	
	jQuery.get( root + 'rpc.php?action=delete_comment&comm_id='+comm_id+'&comm_type='+comm_type,
	function(data) {
		if (data == 'true') {
			jQuery('#comm-'+comm_id).fadeOut(function(){
				jQuery(this).remove();
			});
		}
	});
	/*
	new Request.HTML({'method': 'get','url': root+'rpc.php','onComplete': function(a,b,c,d){
		if (c=='true') {
			$('comm-'+comm_id).get('tween', {property: 'opacity', onComplete: function(){
				$('comm-'+comm_id).getNext('img').dispose();
				$('comm-'+comm_id).dispose();
			}}).start(0);

		}
	}}).send('action=delete_comment&comm_id='+comm_id+'&comm_type='+comm_type);
	*/
}

function editComm(comm_id, comm_type){
	$$('.comments_input').set('value','Loading...');
	$('cmform').getElement('input[name=comm_edit]').set('value',comm_id);
	pos = $('cmform').getElement('textarea').getPosition();
	window.scrollTo(pos.x,pos.y-100);
	new Request.HTML({'method': 'get','url': root+'rpc.php', 'onComplete': function(a,b,c,d){
		$('cmform').getElement('textarea').set('value',c);
	}}).send('action=edit_comment&comm_id='+comm_id+'&comm_type='+comm_type);
}

function citeComm(comm_id, comm_type){
	//$$('.comments_input').set('value','Loading...');
	//$('cmform').getElement('input[name=comm_edit]').set('value',comm_id);
	pos = $('cmform').getPosition();
	window.scrollTo(pos.x,pos.y-100);
	new Request.HTML({'method': 'get','url': root+'rpc.php', 'onComplete': function(a,b,c,d){
		$('comment_quote').setStyle('display', 'block').set('html', c);
		$$('.css_cancel').setStyle('display', 'block');
	}}).send('action=cite_comment&comm_id='+comm_id+'&comm_type='+comm_type);
}

function enableSearch() {
	$$('.usersearch').addEvent('submit',function(e){
		
		e.preventDefault();
		input = this.getElement('input').get('value');
		
		
		if (input.length==0) {
			$$('#content .user').setStyle('display','block');
			$$('#content .userrpc').set('html','');
		}else {
			new Request.HTML({onSuccess:function(a,b,c,d){
				$$('#content .user').setStyle('display','none');
				$$('#content .userrpc').set('html',c).getElement('.list').setStyle('display','block');
			}}).get(this.get('action')+'?s='+input);
		}
	});
}

var sRequest;
var sinput;
function enableUserSearch(){
	sinput = $$('.search_input input[name=search]');
	new Element('div',{'id':'userSearch'}).inject('profile_content','bottom');
	sRequest = new Request.HTML({
		method: 'post',
		url: root+'usearch.php',
		
		onSuccess: function(a,b,c,d){
			$('userSearch').set('html',c);
		}
	}
	);
	sinput.addEvent('keyup', function(e){
		if (this.value.length>0) {
			$('profile_content').getChildren().setStyle('display','none');
			$('userSearch').setStyle('display','block');
			sRequest.cancel();
			sRequest.send('s='+this.value);
		}else {
			$('profile_content').getChildren().setStyle('display','');
			$('userSearch').setStyle('display','none');
		}
	});
}
function userSearchPager(limit){
	sRequest.send('s='+sinput.get('value')+'&l='+limit);
}

function enableTabs() {
	$$('.mainbar .tabs a').each(function(el,i){
		el.addEvent('click',function(e){
			e.preventDefault();
			prev = this.getAllPrevious().length;
			$$('.mainbar .tabs a.active').removeClass('active');
			$$('.mainbar .list').setStyle('display','none');
			this.addClass('active');
			$$('.mainbar .list')[prev].setStyle('display','block');
		});
	});
}

function enableWinnings() {
	$$('.winningswitch select[name=sum]').addEvents({
		'click' : filterSum,
		'keyup' : filterSum,
		'change' : filterSum
	});
	$$('.winningswitch select[name=sum]').store('default',0);
}

function filterSum(el,minValue) {
	document.getElement('a[rel=dropmenu1]').set('text',$(el).get('text'));
	document.getElement('input[name=minValue]').set('value',minValue);
	filterWinnings();
}

function filterRoom(el,room) {
	document.getElement('a[rel=dropmenu2]').set('text',$(el).get('text'));
	document.getElement('input[name=room]').set('value',room);
	filterWinnings();
	
}

function filterFriends(el,elclass) {
	$$('a[rel=dropmenu2]').set('text',el.get('text'));
	if (!elclass) {
		$$($('friends_table').getElements('li')).setStyle('display','');
		return;
	}
	$('friends_table').getElements('li').each(function(z){
		if (z.getElement('.'+elclass)!=null) {
			z.setStyle('display','');
		}else {
			z.setStyle('display','none');
		}
	});
	
}

function filterWinnings(){
	var room = $$('input[name=room]')[0].get('value');
	var minValue = $$('input[name=minValue]')[0].get('value');
	
	$$('.last_winnings tr').each(function(el,i){
		if (el.getChildren('td').length==0) return;
		money = parseInt(el.getChildren()[2].get('html').slice(1));
		el.setStyle('display',(money>minValue && (el.hasClass(room) || room.length==0))?'':'none');
	});
}

function expandRooms(){
	$$('#rooms div').setStyle('display','block');
	$$("#rooms .expand").setStyle('display','none');
	return false;
}

function enablePopUps(){
	$$('a[rel=popup]').addEvent('click', openPopUp);
}

function openPopUp(e){
	e.preventDefault();
	popitup(this.href);
}

function popitup(url) {
	newwindow=window.open(url,'name','height=590,width=644,scrollbars=1,resizable=0,location=0');
	if (window.focus) {newwindow.focus()}
	return false;
}

function safeSubmit(forma){
	if ($('theme').selectedIndex == 0) {
		alert('Выберите категорию!');
		return false;
	}
	if (forma.retrieve('sending',false)==false) {
		forma.store('sending',true);
		forma.submit();
	}else {
		return false;
	}
}

function forgetPassword(){
	var inpt = $('login').getElement('input');
	val = inpt.get('value');
	if (val.length==0) {
		inpt.highlight('#f00').focus();
		return;
	}
	new Request.HTML({'method': 'get','url': root+'rpc.php','evalScripts':true,'onComplete': function(a,b,c,d){
	}}).send('action=request_pw&login='+val);
	
}

function getMyPos() {
    race_id = $('race_id').value;
    if (!race_id) {
        $('race_row').setStyle('display', 'none');
        return false;
    }

    $('race_row').setStyle('display','');
    $('race_pos').set('html', '...');

    new Request.HTML({'method': 'get', 'url': root+'rpc.php', onComplete: function(a,b,c,d){
        $('race_pos').set('html', c);
    }}).send('action=get_racepos&race_id='+race_id);
}

function switchMainTabs(item, nid) {
	//$('newspic').tween('opacity', 0.7);
	active_el = $('news_box').getElement('.tab_active');

	active_el.removeClass('tab_active').addClass('tab').getElement('span').setStyle('display', 'none').getParent().getElement('a').setStyle('display', 'inline');
	$(item).getParent('.tab').removeClass('tab').addClass('tab_active').getElement('a').setStyle('display', 'none').getParent().getElement('span').setStyle('display', 'inline');
	new Request.HTML({'method': 'get', 'url': root+'rpc.php', onComplete: function(a,b,c,d){
		//$('newspic').tween('opacity', [0.7, 1]);
		$('newsBlock').set('html', c);
    }}).send('action=get_main_news&id='+nid);
	return false;
}

function switchForumTabs2(item, nid) {
	$('pokah_filter').getElements('a').removeClass('button_active');
	$(item).addClass('button_active');
	
	new Request.JSON({'method': 'get', 'url': root+'rpc.php', onComplete: function(html){
		$('postBlock').set('html', html);
    }}).send('action=get_main_pokah&id='+nid);
	return false;
}

function switchForumTabs(item, nid) {
	$('menu').getElements('div div').setStyle('display', 'none');
	$('menu').getElements('a').setStyle('display', '');
	$(item).getParent().getElements('div').setStyle('display', '').getParent().getElement('a').setStyle('display', 'none');
	new Request.JSON({'method': 'get', 'url': root+'rpc.php', onComplete: function(html){
		$('postBlock').set('html', html);
    }}).send('action=get_main_pokah&id='+nid);
	return false;
}

function switchNaviTabs(item) {
	$('menu').getElements('div div').setStyle('display', 'none');
	$('menu').getElements('a').setStyle('display', '');
	$(item).getParent().getElements('div').setStyle('display', '').getParent().getElement('a').setStyle('display', 'none');
	doRemote(item);
	return false;
}

function enableRemote() {
	$$('.remote').addEvent('click', function(e){
		e.preventDefault();
		doRemote(this);
	});
}

function doRemote(item) {
	new Request.HTML({'method': 'get', 'url': item.href, onComplete: function(a,b,html,d){
		$('middle').set('html', html);
		enableRemote();
		if (debug) {
			eval(d);
		}
    }}).send('remote=1');
}

function scrollWinBlock(up, el) {
	step = el.getElement('.winBlock').retrieve('step', 0);
	if (!step) step = 0;
	if (!up) {
		step = step +1;
	}else {
		step = step -1;
	}
	step = Math.min( Math.max(step, 0), Math.ceil( el.getElements(".winer").length / 4) - 1 );
	offsetTop = -260 * step;
	el.getElement('.winBlock').store('step', step);
	
	el.getElement('.wuArr').className = step == 0 ? 'up1_empty wuArr' : 'up1 wuArr';
	el.getElement('.wdArr').className = step == Math.ceil( el.getElements(".winer").length / 4) - 1 ? 'down_empty wdArr' : 'down wdArr';
	
	el.getElement('.winBlock').set('tween', {duration: 1000, transition: 'cubic:out'}).tween('top', offsetTop );
}

function scrollRateBlock(up) {
	var el = $('user_rating');
	step = el.retrieve('step', 0);
	if (!step) step = 0;
	if (!up) {
		step = step +1;
	}else {
		step = step -1;
	}
	step = Math.min( Math.max(step, 0), Math.ceil( el.getElements(".user_reit_block").length / 15) - 1 );
	offsetTop = -405 * step;
	el.store('step', step);
	
	el.getElement('.user_button_top div').className = step == 0 ? 'up1_empty' : 'up1';
	el.getElement('.user_button_bottom div').className = step == Math.ceil( el.getElements(".user_reit_block").length / 15) - 1 ? 'down1_empty' : 'down1';
	
	el.getElement('.scroll').set('tween', {duration: 1000, transition: 'cubic:out'}).tween('top', offsetTop );
}

function doContestVote (pic_id, vote){
    new Request.HTML({'method': 'get', 'url': root+'rpc.php', onComplete: function(a,b,html,d){

		$('pic_'+pic_id).set('html', html);
    }}).send('action=contest_vote&id='+pic_id+'&vote='+vote);
}

function readMsgs() {
	var msg_table = document.getElement('.msg_table');
	var msgs = msg_table.getElements('input:checked');
	if (msgs.length == 0) {
		alert('Выберите хотя бы одно сообщение!');
		return;
	}
	var msg_ids = [];
	msgs.each(function(el, i){
		msg_ids.push(el.id.slice(1));
	});
	new Request.HTML({'method': 'post', 'url': root+'rpc.php?action=msgread', onComplete: function(a,b,html,d){
		msgs.each(function(el, i){
			el.set('checked', false);
			$$(el.getNext('img.new_msg_img')).dispose();
			el.getParent('tr').set('bgcolor', '');
		});
    }}).send('ids='+msg_ids.join(','));
}

function saveRating() {

	new Request.HTML({'method': 'post', 'url': root+'rpc.php?action=saverating'}).send($('userrating').toQueryString());
	getRating($('userrating').getElement('input[name=target]').value, 1);
}

function getRating(target,page) {
	//$('userratinglist').tween('opacity', 0);
	(function(){
		new Request.HTML({'method': 'post', 'url': root+'rpc.php?action=getratinglist', onComplete: function(a,b,html,d){
			$$(a).replaces($('userratinglist'));
			//$('userratinglist').setStyle('opacity', 0).tween('opacity', 1);
		}}).send('t='+target+'&p='+page);
	}).call();
	return false;
}

function enableBlockquotes() {
	$('blog_post').getElements('blockquote').each(function(el, i){
		var el = new Element('a').addClass('toggle toggle_open').setStyle('cursor', 'pointer').inject($(el), 'before');
		el.store('bq', el.getNext('blockquote'));
		el.addEvent('click', function(e){
			if ($(this).hasClass('toggle_open')) {
				$(this).set('html', 'Показать скрытый текст').retrieve('bq').slide('out');
			}else {
				$(this).set('html', 'Спрятать текст').retrieve('bq').slide('in');
			}
			
			$(this).toggleClass('toggle_open');
		}).fireEvent('click');
	});
}

/*****************************
* new calendar ;)
*****************************/

var Calendar = new Class(
{
	querystr : null,
	
	querydate: null,
	
	url: null,
	
	initialize: function(url) {
		this.url = url;
	},
	
	setString: function(str) {
		this.querystr = str;
	},
	
	setDate: function(newdate) {
		this.querydate = newdate;
	},
	
	query: function(){
		new Request.HTML({'method': 'get','url':this.url,'update': $('calendar')}).send('date='+this.querydate+'&s='+this.querystr);
	}
	
}
);
