// FUNCTIONS

/**
 * Injects a simple overlay into the DOM. Checks if the background and wrapper are already visible and make use of them
 * if possible.
 *
 * @param {Object} e - jQuery event object
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 17 jan 2011
 */
function showOverlay(e) {
	var self = $(e.currentTarget),
		html = '<div id="overlayBg"></div><div id="overlay"></div>';

	$('body').append(html);

	var bg = $('#overlayBg'),
		overlay = $('#overlay');

	if (e) {
		e.preventDefault();
	}

	$.getScript('/library/jquery.chkFrm-2.1.js', function () {
		$('#mailLinkFrm').live('submit', function (e) {
			$(this).chkFrm(e, {
				onSuccess: function () {
					submitMailAddress(overlay, $(this).serialize());
				}
			});
		});
	});

	overlay.html('<img src="/images/misc/loader.gif" id="loader">');

	if ($.browser.msie) {
		bg.show();
		setTimeout(function () {
			overlay.fadeIn('fast');
		}, 200);
	} else {
		bg.fadeIn('medium', function () {
			overlay.fadeIn('fast');
		});
	}

	$.ajax({
		type: 'GET',
		url: '/inc/ajax/getNewsletterOverlay.php',
		success: function (r) {
			overlay.html(r);
		}
	});
}

/**
 * Removes injected overlay from the DOM.
 *
 * @param none
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 17 jan 2011
 */
function hideOverlay(e) {
	var bg = $('#overlayBg'),
		overlay = $('#overlay');

	if (e) {
		e.preventDefault();
	}

	overlay.fadeOut('fast', function () {
		bg.fadeOut('medium', function () {
			bg.remove();
			overlay.remove();
		});
	});
}

/**
 * Submits given form data to e-sender
 *
 * @param {}
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 8 mrt 2011
 */
function submitMailAddress(overlay, frmData) {
	overlay.html('<img src="/images/misc/loader.gif" id="loader">');

	$.ajax({
		type: 'POST',
		url: '/inc/ajax/submitMailAddress.php',
		data: frmData,
		success: function (r) {
			if ($.trim(r) !== '') {
				overlay.html(r);
			}
		}
	});
}

// EVENTS
$(function () {

	$('.showOverlay').bind('click', showOverlay);

	$('#close').live('click', hideOverlay);
	$(document).bind('keydown', function(e){
		if (e.keyCode == 27) {
			hideOverlay(e);
		}
	});

});

