
var MESSAGES = {
	SUBSCRIBE_SUCCESS: 'Thank you! You have been subscribed.'
	,SUBSCRIBE_EMAIL_INVALID: 'Please enter a valid e-mail address.'
	,SUBSCRIBE_EMAIL_SERVER_ERROR: 'An error has occurred. Please try again.'
}

/* SUBSCRIPTIONS */
$(function() {

	//populate subscription form field with label text
	$('.subscribe-form input.text').each(function() {
		//find label
		var $input = $(this);
		var $label = $('label[for='+ $(this).attr('id') +']');
		var labeltext = $label.text();
		
		if($input.val() === '') {
			$input.val(labeltext);	
		}
		$input.focus(function() {
			if($input.val() == labeltext) {
				//clear out the value
				$input.val('').addClass('focused');	
			} else {
				$input.addClass('focused');	
			}
		});
		$input.blur(function() {
			if($input.val() === '') {
				$input.val(labeltext).removeClass('focused');	
			}
		});
	});
	
	//validate email subscriptions
	$('form.subscribe-form').submit(function() {
		var $form = $(this);
		//message
		var $msg = $form.find('p.message').length === 0 ? $('<p class="message" />') : $form.find('p.message');

		//do validation and show message
		if (!checkEmail($form.find('input.email')[0])) {
			//if does not pass client side validation
			$msg.addClass('error');
			$msg.html(MESSAGES.SUBSCRIBE_EMAIL_INVALID);
			$form.append($msg);
		} else {
			if($form.attr('action')) {
				var feedBurnerUrl = $form.attr('action') + '&email=' + $form.find('input.email')[0].value;
				var win = window.open(feedBurnerUrl, 'popupwindow', 'scrollbars=yes,width=560,height=460');
				$msg.html('');
				//tracking
				PGUtil.trackEvent('email', 'subscribe', $form.attr('action'))
			}
			else {
				$msg.addClass('error').html(MESSAGES.SUBSCRIBE_EMAIL_SERVER_ERROR);
			}
		}
		return false;
	});
	
	//track rss subscriptions
	$('a.rss').click(function() {
		window.open(this.href);
		//tracking
		PGUtil.trackEvent('rss', 'subscribe', $(this).attr('href'))
		return false;
	});
	
	
});


function checkEmail(el) {
	return '' || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(el.value);
}
