$(document).ready(function(){
	
/*
	$(".grow").hide();
	$(".grow").slideDown("slow");
*/
	
	$(".fade-in").hide();
	$(".fade-in-slow").fadeIn(2000);
	$(".fade-in-med").fadeIn(1500);
	$(".fade-in-fast").fadeIn(1000);

        $('.swappy').bind('focus', swappyTitleIn);
        $('.swappy').bind('blur', swappyTitleOut);

        $('.survey input').live('click', respond);
	
/*
	$(".more").hide();
	$(".showmore").click(function(){
			$(".more").slideToggle("slow");
			$(".showmore .choices").toggle();
	});
*/
	
});

function swappyTitleIn() {
        var el = $(this);
        if(el.val() == el.attr('title')) {
                el.val('');
        }
}
function swappyTitleOut() {
        var el = $(this);
        if(el.val() == '') {
                el.val( el.attr('title') );
        }
}

function respond() {
	var which = $(this);
	var question = which.closest('.survey');
	var form = which.closest('form');

	$(':button', question).attr('disabled','disabled');
	$.post(
		'/survey/',
		{
			which: which.attr('name'),
			response: which.val()
		},
		function(json) {
			if(json['saved']) {
				question.addClass('submitted');
				loadMore(form);
			}

			//$('.survey input').click(respond);
		},
		'json'
	);
}

function loadMore(form) {
	var questions = $('.survey', form);
	var submitted = questions.filter('.submitted');
/*
	questions.each(function() {
		if($(this).hasClass('submitted'))
			submitted++;
	});
*/

	if(questions.length == submitted.length) {
		if(form.attr('queue')) {
			//questions.fadeOut('slow', loadMore2);

			$.post(
				'/survey/more',
				{
					queue: form.attr('queue')
				},
				function(html) {
					if(html) {
						var a = $(html);
						a.hide();
						form.prepend(a);
						questions.fadeOut('slow', loadMore2);
					}
				}
			);
		}
	}
}
function loadMore2() {
	$(this).addClass('faded');

	var form = $(this).closest('form');
	var questions = form.find('.submitted');
	var hidden = form.find('.faded');

	if(questions.length == hidden.length) {
		form.find('.faded').remove();
		form.find('.survey').fadeIn('slow');
	}
}

function doRemove() {
	$(this).remove();
}

function removeQuestion() {
	$(this).remove();
	if($('.survey').length == 0) {
		$('.pod').html('<h2>Thank You</h2><p>I probably have more survey questions, but I will spare you for now.</p>');
	}
}



function newsletter(f) {
        var data = {
                e: $('#nl').val()
        }
        $.post(
                '/newsletter/',
                data,
                function(html) {
                        if(html == 'thanks') {
                                alert('Thanks. You have been signed up.');
                        } else {
                                alert('Please double-check your email address and try again.');
                        }
                }
        );
}

