
var showAccount;
var newAccount;

$(document).ready(function() {

	if ($('#alias').val()) {
		$('#alias-field span b').text($('#alias').val());
	}

	$('#alias').keyup(function() {
		if (this.value) {
			$('#alias-field span b').text(this.value);
		}
	});
	
	$('.template input.radio').each(function() {
		$(this)
			.click(templateSelect)
			.css({ position:'absolute', top:0, left:0, zIndex:9 });
	});
	
	var foundSelectedTemplate = false;
	
	$('.template input:radio').each(function() {
		if (this.checked) {
			$(this.parentNode).addClass('selected-template');
			foundSelectedTemplate = true;
		}
	});
	
	var selectedInMore = false;
	
	if (!foundSelectedTemplate) {
	
		$('.template:first').addClass('selected-template');
		$('.template input:radio').get(0).checked = true;
		
	}else{
	
		$('.template:gt(4) input:radio').each(function() {
			if (this.checked) selectedInMore = true;
		});
		
	}
	
	if (selectedInMore) {
	
		$('.template').show();
		$('#template-chooser a.more').css('display', 'none');
		
	}else{
	
		$('.template:gt(4)').css('display', 'none');
		
		$('#template-chooser a.more')
			.css('display', 'inline')
			.click(function() {
				$('.template').fadeIn();
				$(this).css('display', 'none');
				window.location.href = "#template-chooser";
			});
		
	}
	
	$('#almost-done').css('display', 'block');
	
	$('#existing-account h2').text('Sign In.');
	
	$('#account-outer')
		.addClass('dialog')
		.css('display', showAccount ? 'block' : 'none');
		
	$('#account #existing-account-mode')
		.click(existingAccountMode);
		
	$('#account #new-account-mode')
		.click(newAccountMode);
		
	if (newAccount) newAccountMode();
	else existingAccountMode();
	
	$('#account a.cancel')
		.css('display', 'inline')
		.click(function() {
			hideAccountDialog();
			clearAccount();
			return false;
		});
	
});



function templateSelect() {
	$('.template').each(function() {
		$(this).removeClass('selected-template');
	});
	$(this.parentNode).addClass('selected-template');
}



function showAccountDialog() {
	newAccountMode();
	$('#account-outer').css('display', 'block');
}

function hideAccountDialog() {
	$('#account-outer').css('display', 'none');
}

function clearAccount() {
	$('#account input:text, #account input:password').val('');
}



function existingAccountMode() {
	$('#existing-account').css('display', 'block');
	$('#new-account').css('display', 'none');
	$('#existing-account-mode').css('display', 'none');
	$('#new-account-mode').css('display', 'block');
	$('input[name=new_account]').val(0);
}

function newAccountMode() {
	$('#new-account').css('display', 'block');
	$('#existing-account').css('display', 'none');
	$('#new-account-mode').css('display', 'none');
	$('#existing-account-mode').css('display', 'block');
	$('input[name=new_account]').val(1);
}
