$(document).ready(function(){
	// $(document).ready() is executed after the page DOM id loaded
		
	// Binding an listener to the submit event on the form:
	$('.submit').click(function(e){
		
		var bid = $(this).attr('id').split('_')[1];
		var guest = $('#guest'+bid).val();
		
		// If a previous submit is in progress:
		if($('#submit_'+bid).hasClass('active')) return false;
		
		// Adding the active class to the button. Will show the preloader gif:
		$('#submit_'+bid).addClass('active');
		
		// Removing the current error tooltips
		$('.errorTip_'+bid).remove();
		
		// Issuing a POST ajax request to submit.php (the action attribute of the form):
		$.post($('.commentform_'+bid).attr('action'),$('.commentform_'+bid).serialize()+'&fromAjax=1',function(response){
			
			if(!response.status)
			{
				// Some kind of input error occured
				
				// Looping through all the input text boxes,
				// and checking whether they produced an error
				$('input[type!=submit]').each(function(){
					var elem = $(this);
					var id = elem.attr('id');
										
					if(response[id])
						showTooltip(elem,response[id],bid);
				});
			}
			else
			{
			$('#comments'+bid).html('Kommenterad');
			if (guest == 1){			
			$('#comments'+bid).css('color', '#ff0000');
			} else {
			$('#comments'+bid).css('color', '#006600');				
			}
			$('#blog'+bid).css('display', 'none');
			$('#newName'+bid).html(response.name);
			$('#newTime'+bid).html(response.date);
			document.getElementById('newComment'+bid).innerHTML = response.comment;
//			$('#newComment'+bid).html(response.comment);
			$('#newCommentBox'+bid).fadeIn(2000).css('display', 'block');
			if (guest == 1){
				$('#newCommentBox'+bid).css('background', '#ffcbcb');
				$('#guestPost'+bid).css('display', 'block');
			}
			if (response.sum != 1){
				$('#lastComment'+bid).css('margin-bottom', '10px');
				$.scrollTo('#lastComment'+bid, 500 );
			}

			// location.replace(response.redirectURL);
			}
			
			$('#submit_'+bid).removeClass('active');
		},'json');
		
		e.preventDefault();
	});
	
//	$(window).resize();
});

// Centering the form vertically on every window resize:
$(window).resize(function(){
	var cf = $('#carbonForm');
	
	$('#carbonForm').css('margin-top',($(window).height()-cf.outerHeight())/2)
});

// Helper function that creates an error tooltip:
function showTooltip(elem,txt,bid)
{
	// elem is the text box, txt is the error text
	$('<div class="errorTip_'+bid+' red bold">').html(txt).appendTo(elem.closest('.formRow'+bid));
}
