(function($){
	$.fn.sendFriend = function(){
		var jQueryMatchedObj = this;
		var id = $('#docId').attr('value');
		
		function _initialize(){
			_start(this);
			return false;
		}
		
		function _start(){
			// hide all bad elements, so they do not overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			loadForm();
		}
		
		function loadForm(){
			var form = $.ajax({
				type: "GET",
				url: "/ajax.php?send=1&act=getForm&id=" + id,
				async: false
			}).responseText;
			$('body').append(form);
			
			$('.close a').click(function(){
				_finish();
				return false;
			});
			
			$('.bttns .link a').click(function(){
				if($('#i-friend').val() == '' && $('#i-name').val() == '' && $('#i-email').val() == ''){
					_finish();
				}else{
					_finish();
					loadForm();
				}
				return false;
			});
			
			$('input[type="button"]').click(function(){
				_sendForm();
				return false;
			});
		}
		function _finish() {
			$('#popup').remove();
			$('#screen').fadeOut(function() { $('#screen').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		function _sendForm(){
			$.post('/ajax.php?send=1&act=submitForm&id=' + id,{
					'i-friend': $('#i-friend').val(),
					'i-name': $('#i-name').val(),
					'i-email': $('#i-email').val(),
					't-message': $('#t-message').val()
				}, _processResult);
			
			return false;
		}
		
		function _processError(error){
			var id = $('id', error).text();
			var msg = $('message', error).text();
			var listNode = $('#' + id).parent();
			listNode.addClass('err').append($('<p/>').addClass('error').text(msg));
		}
		
		function _processSuccess(success){
			$('.forma legend').after($('message', success).text());
			$('.bttns .link a').text('Notīrīt');
		}
		
		function _clearErrors(){
			$('p.error').remove();
			$('li.err').removeClass('err');
		}
		
		function _processResult(response){
			_clearErrors();
			if($('status', response).text() == '0'){
				_processSuccess($('success', response));
			}else if($('status', response).text() == '1'){
				$.each($('error', response), function(){
					_processError(this);
				});
			}else{
				alert('Notikusi kļūda!');
			}
		}
		this.unbind('click').click(_initialize);
	}
})(jQuery);