var count = 0;
var page = 1;

function sh_delete(id) {
	if (!confirm('Czy na pewno usunąć ?'))
		return false;
	$.post('/shoutbox/usun/' + id, function() {
		refresh(page, false);
	});
	return false;
}
function success(response, status)  { 
	if(status == 'success') {
		$('#shoutbox-response').html('<img src="/img/accept.png" /> Dodano shout');
	//	$('#shoutbox .input input').css('background-color', 'none');
		$('#shoutContent').val('');
		insert(response);
	}
}
/* walidacja wysyłania shouta */
function validate(formData, jqForm, options) {
	for (var i=0; i < formData.length; i++) { 
		if (!formData[i].value) {
			alert('Uzupełnij wszystkie pola'); 
//			$('input[name='+formData[i].name+']').css('background-color', 'red');
			return false; 
		} 
	}
	$('#shoutbox-response').html('<img src="/img/loader.gif" /> Trwa wczytywanie');
//	clearTimeout(timeoutID);
	return true;
}
function refresh(iPage, slide) {
	if (iPage == null)
		iPage = page;
	else
		page = iPage;
	url = '/shoutbox/' + iPage;
	if (iPage == 1)
		url = '/shoutbox.html';
	$.get(url, {}, function(data) {
		div = $('<div>');
		div.html(data);
		if (is_shoutbox_admin) {
			div.find('.shoutbox-list').each(function() {
				id = $(this).find('.shoutbox_item-id').html();
				if (id)
					$(this).find('.shoutbox-list-message').prepend('<a href="#" onclick="return sh_delete(' + id + ')"><img src="/img/del.gif" alt="usun"></a> ');
			});
		}
		if (current_user_id) {
			current_time = new Date().getTime();
			div.find('.shoutbox_item-user_id.u' + current_user_id).each(function() {
				time = $(this).html();
				id = $(this).parent().find('.shoutbox_item-id').html();
				$(this).parent().find('a.nick').addClass('shoutbox-my-nick');
				if (id && current_time < time + 300 && !is_shoutbox_admin) {
					$(this).parent().find('.shoutbox-list-message').prepend('<a href="#" onclick="return sh_delete(' + id + ')"><img src="/img/del.gif" alt="usun"></a> ');
				}

			});
		}
	
		insert(div.html(), slide);
		$(".shoutbox-list a.nick").contextMenu({
			menu: 'userMenuUl',
			inSpeed: 300,
			outSpeed: 150
		});
	});
	return false;
}
function insert(data, slide) {
	$('#shoutbox-list').html(data);
//	timeoutID = setTimeout(function() {refresh(page, false);}, 20000);
}
function sh_page(page) {
	//$('#shoutbox-list').html('<div class="c">Ładowanie danych <br /><img src="/img/loader.gif" alt="" /></div>');
	refresh(page, true);
	return false;
}
$(document).ready(function() { 
	var options = { 
		dataType:       'post',
		beforeSubmit:   validate,
		success:        success
	}; 
	$('#shoutbox-form').ajaxForm(options);
//	timeoutID = setTimeout(function() {refresh();}, 20000);
});

