function validate_email(fData){
	var reg = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
	return reg.test(fData);
}

function toggle_subscribe_status(){
	if(validate_email($('#subscribe-email').val())){
		$('#subscribe-button').removeAttr('disabled');
		$('#subscribe-email').attr('class','in-range');
	}
	else{
		$('#subscribe-button').attr('disabled','disabled');
		$('#subscribe-email').attr('class','out-of-range');
	}
}

function setCookie(c_name, value, expiredays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = c_name + "=" + encodeURI(value) + ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}


$(function(){

	var
		s = $('#js-subscribe'),
		postTitle = $('h1 a').html(),
		email = $.cookie('mi5_comment_author_email'),
		post_id = $('#post_id').val();


	$('#popup-header').append(' ' + postTitle);
	$('#subscribe-email').val(email);


	s.click(function(){

		if(s.attr('class')=='subscribed'){
			$('#popup-header').html('Перестать следить за новыми комментариями к посту ' + postTitle);
			$('#js-hide-for-unsubscribe').css('display', 'none');
		}
		else{
			$('#popup-header').html('Подписка на новые комментарии к посту ' + postTitle);
			$('#js-hide-for-unsubscribe').css('display', 'block');
		}

		$('#popup').css('display','block');
		toggle_subscribe_status();

		$('#subscribe-email').keyup(function(){
			window.setTimeout(function(){
				toggle_subscribe_status();
			}, 300)
		});

	});


	$('#subscribe-button').click(function(){

		if(s.attr('class')=='subscribe'){ // подписаться
			$.get("/subscribe", { post_id: post_id, email: $('#subscribe-email').val(), subscribe: "1" }, function(data){
				if(data=='true') s.attr('class', 'subscribed').html('Отписаться');
				setCookie('mi5_comment_author_email', $('#subscribe-email').val(), 365);
			});
		}

		if(s.attr('class')=='subscribed'){ // удалить подписку
			$.get("/subscribe", { post_id: post_id, email: $('#subscribe-email').val(), unsubscribe: "1" }, function(data){
				if(data=='true') s.attr('class', 'subscribe').html('Подписаться');
			});
		}

		$('#popup').css('display','none');
		return false;
	});


	$('#popup-close').click(function(){ $('#popup').css('display','none'); });
});
