$(document).ready(function(){
	// $(document).ready() is executed after the page DOM id loaded
		
	// Binding an listener to the submit event on the form:
	$('.reportsubmit').click(function(e){
		
		var id = $(this).attr('id').split('_')[1];
		var guest = $('#guest'+id).val();
		
		// If a previous submit is in progress:
		if($('#submit_'+id).hasClass('active')) return false;
		
		// Adding the active class to the button. Will show the preloader gif:
		$('#submit_'+id).addClass('active');
		
		// Removing the current error tooltips
		$('.errorTip_'+id).remove();
		
		// Issuing a POST ajax request to submit.php (the action attribute of the form):
		$.post($('.reportform_'+id).attr('action'),$('.reportform_'+id).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 eid = elem.attr('id');
										
					if(response[eid])
						showTooltip(elem,response[eid],id);
				});
			}
			else
			{
			$('#reports'+id).html('Anmält!');		
			$('#reports'+id).css('color', '#ff0000');
			$('#report'+id).css('display', 'none');
			$('#newReportBox'+id).fadeIn(2000).css('display', 'block');
			$('#newReportBox'+id).html('Vi har tagit emot din anmälan.');		
			// location.replace(response.redirectURL);
			}
			
			$('#submit_'+id).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,id)
{
	// elem is the text box, txt is the error text
	$('<div class="errorTip_'+id+' red bold" style="margin-top: 5px;">').html(txt).appendTo(elem.closest('.formRow'+id));
}
