var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var pathName = getAbsolutePath();

var doLayout = function() {
	var winHeight = jQuery(window).height();
	var winWidth = jQuery(window).width();
	jQuery('body').css('height', winHeight);
	var formPosX = parseInt(((winWidth - 522) / 2), 10);
	var formPosY = parseInt((winHeight / 4), 10);
	jQuery('#subscribe-form-container').css('top', formPosY).css('left', formPosX);
	jQuery('#wrapper').css('minHeight', winHeight);
	var winWidth = jQuery(window).width();
	jQuery('#footer').css('top', (winHeight - 30)).css('left', (winWidth - 502) / 2).show();
};

function getAbsolutePath() {
	var loc = window.location;
	var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
	return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

var postSubmit = function(response) {
	var statusMsg = "";
	if ("undefined" !== typeof (response)) {
		var retCode = parseInt(response, 10);
		if (retCode == 1) {
			statusMsg = "Sorry! Unable to add you to the list at this time.";
		} else if (retCode == 0) {
			statusMsg = "You have been added to the Seazn mailing list.<br/><br/>";
			statusMsg += "You will receive a confirmation email.";
		}
	}

	jQuery('#message-popup p').html(statusMsg);
	jQuery('#message-popup #close-popup').show();
};

var doSubscribe = function() {
	var emailAddress = jQuery('#email-address').val();
	if (emailAddress.length == 0) {
		alert('Please enter your email address');
		return false;
	} else {
		if (!emailReg.test(emailAddress)) {
			alert('Please enter a valid email address');
		} else {
			jQuery('#message-popup #close-popup').hide();
			jQuery('#message-popup p').html('Please wait.<br/>Adding you to the Seazn mailing list.');
			jQuery('#message-popup').bPopup( {
				fadeSpeed : 1,
				followSpeed : 1,
				opacity : 0.8,
				modalClose : false
			});
			jQuery.post(pathName + 'notify_submit.php', {
				email : emailAddress
			}, postSubmit);
		}
	}
	return false;
};

jQuery(function() {

	jQuery.event.add(window, 'load', doLayout);
	jQuery.event.add(window, 'resize', doLayout);

	jQuery('#email-address').val("").focus();

	jQuery('#message-popup #close-popup').click(function() {
		jQuery('#message-popup').bPopup().close();
	});

	jQuery('#subscribe-do').click(doSubscribe);
	jQuery('#subscribe').submit(doSubscribe);
});

jQuery(window).load (function () {
	jQuery('#subscribe-form-container').show();
});

