(function($) {
	
	$.fn.recommendForm = function( settings ) {
		
		var windowClass = '_sendRec';
		
		var recommendPluginNS = function(){
			
			return {
				
				validOptions: {
					
					submitHandler: function(f) {
						
						encjaNS.submitFormByAjax( f , function( obj ) {
				
		    				$("."+windowClass).html(obj.responseText);
		    				$("."+windowClass).parent().children(".ui-dialog-buttonpane").html('');
				
						});
						
					}
					
				}
				
			};
			
		}();
		
		var defConf = {
			'url'		: '',
			'title'		: 'Polecany artykuł'
		};
		
		if ( settings ) 
			var options = $.extend(defConf, settings);
		
		this.each(function() {
			
			var obj = this;
			
			$(this).click(function() {
				encjaNS.openWindow({
					ajax:{
						
						url 	:	mainLink + 'recommend.php?recommend_controller=1&ajax=1',
						data	: { link: options.url, title: options.title }
					},
					c: windowClass,
					title: "Poleć artykuł",
					dial: {
						modal: true,
						title: ''
					},
					dontClose: true,
					sData: "Wyślij",
					onSubmit: function () {
						
						$("."+windowClass).children("form").validate( recommendPluginNS.validOptions );
						
						$("."+windowClass).children("form").children("input").each(function() {
							
							$(this).rules("add", {
								required: true,
								messages: {
									required: "Pole wymagane"
								}
							});
							
						});
						
						$("#_recipientMail").rules("add", {
							email: true,
                                                        required: true,
							messages: {
								email: "Podaj poprawny adres"
							}
						});
						$("#senderMail").rules("add", {
							email: true,
                                                        required: true,
							messages: {
								email: "Podaj poprawny adres"
							}
						});
						$("#recipientName").rules("add", {
                                                        required: true
						});
						$("#senderName").rules("add", {
                                                        required: true
						});
						
						$("#check_code").rules("add", {
                            required: true
						});
												
						var data = {code: $("#check_code").val()};
						
						encjaNS.ajax({
							data: data,
							url: mainLink + 'recommend.php?recommend_controller=3&ajax=1',
							complete:function(o){
											
								if (jQuery.trim(o.responseText) == 'false' ) {
									
									encjaNS.reloadImageCode('imageCode');
									$("#check_code").after("<label id='captcha' for='check_code' generated='true' class='error_line'>Podaj poprawny kod</label><br/>"); 
									
								} else {
								
									$("#recommend_form").submit();
									
								};
								
							}
							
						});
						
						
						;
						
					}
				});
			})
			
		});
		
		return this;
		
	};
})(jQuery);
