!function ($) {
	"use strict";

	function Feedback(elem, options){
		var $elem = $(elem);
		var b = new $.Bem2("feedback");

		var $show = $(options.show);
		var $close = $elem.find(b.e("close").s());
		var $block = $elem.find(b.s());
		var $fade = $elem.find(b.e("fade").s())
		var $form = $elem.find("form");
		var $submit = $elem.find(b.e("submit").s());
		var $success = $elem.find(b.e("message_status_ok").s());
		var $success_close = $success.find(b.e("message-close").s());
		var $error = $elem.find(b.e("message_status_error").s());
		var $error_close = $error.find(b.e("message-close").s());
		var $extra = $elem.find(b.e("extra").s());

		$elem.appendTo("body");

		$show.off("off").on("click", function(e){
			e.preventDefault();
			$elem.add($block).add($fade).show()
			$fade.css("opacity", 0).animate({ opacity: 1}, 500);
			$("html, body:not(:animated)").animate({ scrollTop: 0}, 1000);
		});

		$close.off("click").on("click", function(e){
			e.preventDefault();
			$elem.add($block).add($fade).hide();
		});

		$submit.off("click").on("click", function(e){
			e.preventDefault();
			$.ajax({
				type: "POST",
				url: $form.attr("action"),
				data: $form.serialize() + "&form_name=" + options.form_name,
				dataType: "json",
				success: function(data) {
					$("html, body:not(:animated)").animate({ scrollTop: 0}, 1000);
					if(data.status && data.status === "success") {
						$block.hide();
						$success.show();
					} else {
						$block.hide();
						$error.show();
					}
				}
			});			
		});

		$success_close.off("click").on("click", function(e){
			e.preventDefault();
			$elem.add($block).add($fade).add($success).hide();
		});

		$error_close.off("click").on("click", function(e){
			e.preventDefault();
			$error.hide();
			$block.show();
		});
		
		return {
			reset: function(){
				$form[0].reset();
			},

			extra: $extra
		};
	}

	$.fn.waFeedback = function (options) {
		return new Feedback(this, options);
	};
}(window.jQuery)


