var click = false;
var url = '/index.php/default/chinwags/index/format/html';
var urlAdd = '/index.php/default/chinwags/add/format/html';
var urlCaptcha = '/index.php/default/chinwags/captcha/format/html';

$(document).ready(function(){
	chinwag(url, 'GET');

	$('#chinwag-form').submit(function(){
		var message = $.trim($('#message').val());
		if ($('#captcha-input').html() == null) {
			if (message.length == 0) {
				return false;
			} 
		} else {
			var input = $.trim($('#captcha-input').val());
			if (message.length == 0 || input.length != 3) {
				return false;
			}
		}

		chinwag(urlAdd, 'POST', $('#chinwag-form').serialize());

		return false;
	});

	$('#refresh').click(function(){
		$('#chinwag').scrollTop(0);
		chinwag(url, 'GET');
	});

	$('#captcha-box').hide();
	
	if ($('#captcha-box').html() != null) {
		$('#message').click(function() {
			if (click == false) {
				click = true;
				$('#captcha-box').show();
				captcha(urlCaptcha);
			}
		});
	}
});

function chinwag(url, type, data){
	$.ajax({
		global: false,
		type: type,
		url: url, 
		data : data,
		beforeSend: function() { $('#chinwag').prepend('<img style="margin:-62px 0 0 -62px; top:50%; left:50%; position:absolute;" src="/img/loading51.gif" alt="Ładuję..." />'); },
		success: function(data) { $('#chinwag').html(data); },	
		error: function(jqXHR, textStatus, errorThrown) {
			$('#chinwag').html(textStatus);
		}
	});
	return false;
}

function captcha(url){
	$.ajax({
		global: false,
		url: url, 
		beforeSend: function(){$('#captcha-wrapper').prepend('<img style="width:50px; height:50px; margin:-25px 0 0 -25px; top:50%; left:50%; position:absolute;" src="/img/loading51.gif" alt="Ładuję..." />');},
		success: function(data) { 
			$('#captcha-wrapper').html(data);
			$('#captcha-id').val($('#captcha').attr('title'));		
		   	$('#captcha').click(function(){
				captcha(url);
			});
		},
		error: function(jqXHR, textStatus, errorThrown) {
			$('#captcha-wrapper').html(textStatus);
		}
	});
}

function chinwag_success()
{
	$('#message').val('');
	$('#captcha-input').val('');
	$('#chinwag').scrollTop(0);

	if ($('#captcha-box').html() != null) {
		$('#captcha-box').hide();
		click = false;
	}	  
}


