/*	contactform.js | De Geluksdruif
**	Lodewijk Schutte | Low
**	v1.0 | 20091106
**	---------------------------------------------------------------------- */

$(function(){
	
	// Get links with class 'contact'
	var popups = $('#primary a.contact').get();
	
	// If there aren't any, do nothing
	if (!popups.length) return;
	
	// Define a function to close the modal window
	var closePopup = function() {
		$('#overlay').hide();
		$('#popup').hide();
	};

	// define a function to prepare the fetched contact form
	var prepForm = function() {
		
		// add closePopup to the Cancel button of the form
		$('#closepopup').click(closePopup);
		
		// add submit handler to form
		$('#contact_form').submit(function(e){

			// cancel the actual submission of the form
			e.preventDefault();
		
			// clean up errors
			$('#contact_form .error').removeClass('error');
		
			// initiate error array and fields to check
			var errors = [];

			// Check required fields
			$('.required', this).each(function(){
				
				// get value from field
				var val = $(this).val();
				var ok	= true;
				
				// validate field
				if (!val) {
					ok = false;
				} else if ($(this).hasClass('email') && !val.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/gim)) {
					ok = false;
				} 
				
				// if validation failed, add it to the errors array
				if (!ok) {
					errors.push($(this));
				}

			});
		
			// if we have errors, add 'error' class to element and bail...
			if (errors.length) {
				$(errors).each(function(){
					$(this).addClass('error');
				});
				return false;
			}
		
			// define function as callback function
			var finished = function(ret) {
				$('#contactform').html('<p>Formulier is verstuurd!</p>');
				setTimeout(closePopup, 2000);
			};
		
			// Execute Ajax call
			$.post(
				$(this).attr('action'),	// Url = action from form itself
				$(this).serialize(),	// Serialized form data
				finished,				// Callback function we just created
				'html'					// Returns data in text format
			);
		
		});
	};

	// create overlay and popup divs
	var overlay = $('<div/>').attr('id','overlay').hide().click(closePopup);
	var popup = $('<div/>').attr('id','popup').hide();
	
	// append divs to body
	$(document.body).append(overlay);
	$(document.body).append(popup);

	// add event to popup links
	$(popups).click(function(e){
		
		// cancel link default
		e.preventDefault();
	
		// show overlay and popup divs
		$('#overlay').show();
		$('#popup').show();
		
		// Show loading message
		$('#popup').html('<p class="loading">Momentje&hellip;</p>');
	
		// load content form into popup div, prepForm afterwards
		$('#popup').load($(this).attr('href')+' #contactform', prepForm);
	
	});
		
});
