/* Send to friend...
----------------------------------------------*/

$('#fancy_wrap p.buttons a').click(function(){
	$.fn.fancybox.close();
	return false;
});

$('#fancy_wrap form#email-friend-form .button').click(function(){
	$(this).parent().submit();
	return false;
});

$('#fancy_wrap form#email-friend-form').submit(function(){
	
	var error_height = $('#fancy_wrap ul#errors').height();
	var window_height = $('#fancy_ajax').outerHeight() - error_height;
		
	$.post(
		$(this).attr('action'),
		$(this).serialize(),
		function(data){
			
			var errors = $('.error li', data);
			if( errors.length ){
				var text_to_insert = '';
				errors.each(function(i){ text_to_insert += '<li>'+$(errors[i]).html()+'</li>'; });
				if( $('ul#errors').length ){
					$('#fancy_wrap ul#errors').fadeOut(250, function(){
						$(this).empty().append(text_to_insert);
					});
				}else{
					$('#fancy_wrap form#email-friend-form').prepend('<ul id="errors" style="display: none;">'+text_to_insert+'</ul>');
				}
				
				var new_height = window_height + $('#fancy_wrap ul#errors').height();
				$('#fancy_outer').animate({'height':new_height+'px'}, 250, function(){
					$('#fancy_wrap ul#errors').fadeIn(250);
				});
				
			}else{
				
				// Create success message...
				var success_message = $('h1', data).html();
				success_message = '<div class="success" style="display: none;"><p>' + success_message + '</p><p class="buttons"><a href="#">close window</a></p></div>';
				$('#fancy_wrap #email-friend-wrapper').append(success_message);
				
				// Reattach events...
				$('#fancy_wrap p.buttons a').click(function(){ $.fn.fancybox.close(); return false; });
				
				// Fade out form, fade in success message...
				$('#fancy_wrap form#email-friend-form').fadeOut(250, function(){
					var new_height = $('#fancy_ajax div#email-friend-wrapper').outerHeight() + $('#fancy_wrap #email-friend-wrapper .success').outerHeight();
					$('#fancy_outer').animate({'height':new_height+'px'}, 250, function(){
						$('#fancy_wrap #email-friend-wrapper .success').fadeIn(250);
					});
				});
				
			}
			return false;
		}
	);
	return false;
});

