$(function () {
	
	$('#game_filter').change(function(){
		
		$.getJSON($("#opponentSearch-refresh").attr('href'), {'filter': $(this).attr('value')}, function(payload) {
			// refresh all snippets
			for(var id in payload.snippets) {
				$('#' + id).html(payload.snippets[id]);
			}
		});
		
	});
	
	$("#opponentSearch-refresh").click(function(){
		$.getJSON($("#opponentSearch-refresh").attr('href'), {'filter': $("#game_filter").attr('value')}, function(payload) {
			// refresh all snippets
			for(var id in payload.snippets) {
				$('#' + id).html(payload.snippets[id]);
			}
		});
		return false;
	});
	
	
	$('input:radio[name="type"]').click(function(){
		if($(this).attr('value') != 'player'){
			$('.opponentFormName').show();
		}else{
			$('.opponentFormName').hide();
		}	
	})	;

	$('a.ajax').live('click', function (event) {
		event.preventDefault();
		$.get(this.href);
	});
	
	$('#messageForm').attr('autocomplete', 'off');

	$("#messageForm").submit(function (e) {
		$(this).ajaxSubmit(e);
		resetCountdownEvent();
		//$('input.text').val('');
		$('input#frmchatForm-message').focus();
		return false;
	});

	$('#messageForm :submit').click(function (e) {
		$(this).ajaxSubmit(e);
		resetCountdownEvent();
		//$('input.text').val('');
		$('input#frmchatForm-message').focus();
		return false;
	});
		
	$('div#reload > a#target').live('click', function (event) {
		event.preventDefault();
		$.get(this.href);
		resetCountdownEvent();
	});
	
	$('.message > .body a').live('click', function (event) {
		event.preventDefault();
		window.open(this.href);
		return false;
	});
	
	$('input#frmchatForm-message').focus();
	
	$('span.nick').live('click', function (event) {
		var el = $('input#frmchatForm-message');
		el.val(!el.val() ? $(this).text() + ': ' : el.val() + $(this).text() + ', ');
		el.focus();
	});
	
	runCountdownEvent();
		
});

function reloadChat()
{
	$.get($('div#reload > a#target').attr('href'));
	runCountdownEvent();
}

function runCountdownEvent()
{
	$('div#reload > span.countdown').countdown({seconds: 5, callback: 'reloadChat()'});
}

function resetCountdownEvent()
{
	$('div#reload > span.countdown').countdown.stop();
	runCountdownEvent();
}

jQuery.extend({
    nette: {
        updateSnippet: function (id, html) {
                $("#" + id).html(html);
                $.nette.registerAfterUpdate();
        },

        registerAfterUpdate: function() { }
    }
});
