$(document).ready(function()
{
	// Overlay global configurations
	$.tools.overlay.conf.closeOnClick = false;
	$.tools.overlay.conf.closeOnEsc = false;
	
	/*	
	// this doesnt do anything but print to the console. 
	$.extend($.tools.overlay.conf, {
		onBeforeClose: function(e){ 
			var $target = $(this.getTrigger());
			console.log($target);
			console.log($(this.isOpened()));
		}
	});
	*/	
	
	$('.close').live('click', function()
	{
		window.location = "http://"+window.location.hostname;
	});
	
	
	var key = $("div#key").overlay({api: true, effect: 'default', expose: { color: '#000', loadSpeed: 200, opacity: 0.3 }});
	var age = $("div#age").overlay({api: true, effect: 'drop' });
	var details = $("div#details").overlay({api: true, effect: 'drop' });
	var friends = $("div.overlay#friends").overlay({api: true, effect: 'drop' });
	var error = $("div.overlay#error").overlay({api: true, effect: 'drop', expose: { color: '#000', loadSpeed: 200, opacity: 0.5 }});
	var age_error = $("div.overlay#age-error").overlay({api: true, effect: 'drop', expose: { color: '#000', loadSpeed: 200, opacity: 0.3 }});
	var login = $("div#login").overlay({api: true, effect: 'drop', expose: { color: '#000', loadSpeed: 200, opacity: 0.3 }});
	var limit = $("div#limit").overlay({api: true, effect: 'drop', expose: { color: '#000', loadSpeed: 200, opacity: 0.3 }});


// ========================
	jQuery.validator.setDefaults(
	{
		errorElement: "span",
		errorLabelContainer: ".errors"
	});

	$('a.login').click(function(e)
	{
		e.preventDefault();
		login.load();
	});

	$('input[type=text]').focus( function()
	{
		$(this).val('');
	});
	
	$('#key em.get-a-password a').click( function(e)
	{
		e.preventDefault();
		$.ajax({
			url: '/rsvp/error',
			dataType: "html",
			success: function(data)
			{
				$('.overlay#error').addClass('remove');
				$('.overlay#error .int').html(data);
				error.load();
			}
		});
	});


	$('button#skip').click( function()
	{	
		friends.close();
		friends.onClose(function()
		{
			$.ajax({
				type: "POST",
				url: "/rsvp/sendtofriend",
				success: function()
				{
					window.location.reload(true);			
				}
			});
		});
	});


	$('#sendtofriend-form').submit( function(e)
	{
		e.preventDefault();
		var settings = $('#sendtofriend-form').validate().settings;
	
		if($(this).valid())
		{
			friends.close();
			friends.onClose(function()
			{
				$.ajax({
					type: "POST",
					data: $('#sendtofriend-form').serialize(),
					url: "/rsvp/sendtofriend",
					success: function()
					{
						window.location.reload(true);
					}
				});
			});
		}
	});


	$('#login-form').submit( function(e)
	{
		e.preventDefault();
		var validator = $('#login-form').validate();
	
		if($(this).valid())
		{
			$.ajax({
				type: "POST",
				data: $('#login-form').serialize(),
				dataType: "json",
				url: "/rsvp/login",
				success: function(data)
				{
					if(data.result == 'error')
					{
						validator.showErrors({"login-password": data.message});
					}
					else
					{
						window.location.reload(true);
					}
				}
			});

		}
	});


	$('a.invites').click( function(e)
	{
		e.preventDefault();

		$.ajax({
			url: '/rsvp/sendtofriend',
			dataType: "json",
			success: function(data)
			{
				$('.overlay#friends .content #guest-name').html(data.guest);
				$('.overlay#friends .content #event-name').html(data.event);
								
				for(var i = 1; i <= data.invites; i++)
				{
					$('.overlay#friends .content #email-container'+i).show();
				}
				
				friends.load();
			}
		});
	});

// =========================

	// Load the KEY form
	setTimeout(function()
	{
		key.load();	
	//	$("div.overlay#key .content").load('/rsvp/key');

	}, 1000);

	// submit the passcode form
	$('#passcode-form').submit( function(e)
	{
		e.preventDefault();
				
		var validator = $(this).validate();
						
		$("input#input-key").rules("add", {
			required: true,
			minlength: 7,
			messages: {
				required: "A password is required to continue",
				minlength: jQuery.format("Please, a {0} character password is required")
			}
		});

		if($('#passcode-form').valid())
		{			
			$.ajax({
				url: '/rsvp/key', 
				data: {key: $("input#input-key").val()}, 
				type: "POST",
				dataType: "json",
				success: function(data)
				{
					if(data.result == "error" && data.type == "over 3 tries" || data.type == "already used")
					{
						// Spawn a overlay error box!
						$.ajax({
							url: '/rsvp/error',
							type: "POST",
							data: {error: data.message},
							dataType: "html",
							success: function(data)
							{
								$('.overlay#error .int').html(data);
								error.load();
							}
						});
					}
					else if(data.result == "error" && data.type == "limit")
					{
						// Spawn a overlay email capture box!
						// The passcode was a total success. Let's move on to the next screen!
						key.close();
						key.onClose(function()
						{
							$('.overlay').removeClass('key');
							key.unbind('.overlay');
							load_limit_form();
						});
					}
					else if(data.result == "error")
					{
						validator.showErrors({"key": data.message});
					}
					else
					{
						// The passcode was a total success. Let's move on to the next screen!
						key.close();
						key.onClose(function()
						{
							$('.overlay').removeClass('key');
							key.unbind('.overlay');
							load_age_form();
						});
					}
				},
				error: function(data)
				{
					alert(data);
				}
			});
		}
		
	})


	// submit the passcode form
	$('#limit-form').submit( function(e)
	{
		e.preventDefault();
		
		var validator = $('#limit-form').validate();

		$("#limit-form input#fname, #limit-form input#lname").rules("add", 
		{
			required: true, messages: 
			{
				required: "Your first and last name is required to continue"
			}
		});	

		if($(this).valid())
		{
			var updates;
			if($("#limit-form input#updates").is(':checked'))
			{
				updates = 'yes';
			}
			else
			{
				updates = 'no';
			}
		
			$.ajax({
				url: '/rsvp/limit',
				type: "POST",
				dataType: "json",
				data: {fname: $("#limit-form input#fname").val(), lname: $("#limit-form input#lname").val(), email: $("#limit-form input#email").val(), twitter: $("#limit-form input#twitter").val(), updates: updates },
				success: function(data)
				{
					// The age verification was a total success. Let's move on to the next screen!
					limit.close();
					limit.onClose(function()
					{
						window.location = "http://"+window.location.hostname+"/gallery";
					});
				},
				error: function(data)
				{
					alert('Error');
				}
			});
		}
	});


	function load_age_form()
	{			
		$.ajax({
			url: '/rsvp/age',
			dataType: "html",
			success: function(data)
			{
				$('.overlay#age .content p.copy').html(data);
				age.load();
			}
		});
	}


	function load_limit_form()
	{			
		$.ajax({
			url: '/rsvp/limit',
			dataType: "html",
			success: function(data)
			{
				$('.overlay#limit .content p.copy').html(data);
				limit.load();
			}
		});
	}


	function load_details_form()
	{
		$.ajax({
			url: '/rsvp/details',
			dataType: "html",
			success: function(data)
			{
				$('.overlay#details .content p.copy').html(data);
				details.load();
			}
		});
	}

	function load_friends_form()
	{
		$.ajax({
			url: '/rsvp/sendtofriend',
			dataType: "json",
			success: function(data)
			{
				$('.overlay#friends .content #guest-name').html(data.guest);
				$('.overlay#friends .content #event-name').html(data.event);
								
				for(var i = 1; i <= data.invites; i++)
				{
					$('.overlay#friends .content #email-container'+i).show();
				}
				
				friends.load();
			}
		});
	}

	// Process the age form
	$('#verification-form').submit( function(e)
	{
		e.preventDefault();

		// Check the Age form with some fancy Javascript
		$('#verification-form').validate();
				
		$("input#month").rules("add", 
		{
			required: true, minlength: 2, number: true, range: [1,12], messages:
			{
				required: "Your full birthday is required to continue",
				minlength: jQuery.format("Please, a {0} digit day is required to continue"),
				number: "Enter a month please",
				range: "Please enter a month between 01 and 12"
			}
		});
		
		
		$("input#day").rules("add", 
		{
			required: true, minlength: 2, number: true, range: [1,31], messages: 
			{
				required: "Your full birthday is required to continue",
				minlength: jQuery.format("Please, a {0} digit day is required to continue"),
				number: "Enter a day please",
				range: "Please enter a day between 01 and 31"
			}
		});		

		$("input#year").rules("add", 
		{
			required: true, minlength: 4, number: true, range: [1900,2009], messages: 
			{
				required: "Your full birthday is required to continue",
				minlength: jQuery.format("Please, a {0} digit year is required to continue"),
				number: "Enter a year please",
				range: "Please enter a year between 1900 and 2009"
			}
		});	

		if($(this).valid())
		{	
			$.ajax({
				url: '/rsvp/age',
				type: "POST",
				dataType: "json",
				data: {month: $("input#month").val(), day: $("input#day").val(), year: $("input#year").val() },
				success: function(data)
				{
					if(data.result == "error")
					{
						// Spawn a overlay error box!
						$.ajax({
							url: '/rsvp/age_error',
							type: "POST",
							data: {error: data.message},
							dataType: "html",
							success: function(data)
							{
								console.log(data);
								$('.overlay#age-error').html(data);
								age_error.load();
							}
						});
					}
					else
					{
						// The age verification was a total success. Let's move on to the next screen!
						age.close();
						age.onClose(function()
						{
							load_details_form();
							age.unbind();
						});
					}
				},
				error: function(data)
				{
					alert('System Error (age)');
				}
			});
		}		
	})

	$('#personal-form').submit( function(e)
	{
		e.preventDefault();
		
		var validator = $('#personal-form').validate();

		$("input#fname, input#lname").rules("add", 
		{
			required: true, messages: 
			{
				required: "Your first and last name is required to continue"
			}
		});	

		if($(this).valid())
		{
			var updates;
			if($("input#updates").is(':checked'))
			{
				updates = 'yes';
			}
			else
			{
				updates = 'no';
			}
		
			$.ajax({
				url: '/rsvp/details',
				type: "POST",
				dataType: "json",
				data: {fname: $("input#fname").val(), lname: $("input#lname").val(), email: $("input#email").val(), twitter: $("input#twitter").val(), updates: updates },
				success: function(data)
				{
					// The age verification was a total success. Let's move on to the next screen!
					details.close();
					details.onClose(function()
					{
						load_friends_form();
						details.unbind();
					});
				},
				error: function(data)
				{
					alert('Error');
				}
			});
		}		
	});
});
