$(document).ready(function() {
	
	$('.tell-friend a').click(function(e){		
		e.preventDefault();

		showSendToFriendForm();
	});
	
	
	// validate signup form on keyup and submit
	// Uses jquery validate, which must be loaded before this script

	$("#send-to-friend-form .btn-submit-small").live('click', function(e){
		
		e.preventDefault();
		
		$('#send-to-friend-form').validate({
			rules: {
				first_name_to: "required",
				last_name_to: "required",
				email_to: "required",
				first_name_from: "required",
				last_name_from: "required",
				email_from: "required"
			},		
			invalidHandler: function(form, validator) {
				// $("#send-to-friend-errors").html("Please complete all fields.");
			},
			submitHandler: function(form) {
				
				// Submit the form to the server for processing
			   	$(form).ajaxSubmit({
					url:'/send-to-friend/post',
					dataType: 'json',
					success: function(json_object) {
								if (json_object.status == "success") {
									showSendToFriendThankYou();
								} else if (json_object.status == "fail") {
									showSendToFriendError();
								}
							},
					error: function(jqXHR, textStatus, errorThrown){
						showSendToFriendError();
					}
				});
	
				return false;
			}
		});
		
		$('#send-to-friend-form').submit();
	});

});

function showSendToFriendForm()
{
	$('<div id="send-to-friend-container"></div>').appendTo('body');
	
	$("#send-to-friend-container").load('/send-to-friend',function(){			
		$('#send-to-friend-page').val(window.location.href);
		$('#inline-page').html(window.location.href);
	}).dialog({					
		height: 717,
		width: 500,
		modal: true,
		dialogClass: 'send-to-friend-dialog',
		close: function(event, ui) {
			$("#send-to-friend-container").remove();
		}			
	});
}

function showSendToFriendThankYou(data)
{
	$('#send-to-friend-form').slideUp(function(){
		$('#send-to-friend-thank-you').fadeIn();
	});
  
	pageTracker._trackPageview('/ajax-goals/send-to-friend');
}

function showSendToFriendError()
{
	$('#send-to-friend-form').slideUp(function(){
		$('#quick-signup-error-message').fadeIn();
	});

}
