// vim: sw=4 ts=4 noet encoding=utf-8

(function ($) {
	$.fn.createForm = function () {};
	$.fn.submitForm = function () {};

	$.fn.quickreg = function (opts) {

		var options = $.extend({
			partnerId:	null,
			serviceId:	null,
			serviceUrl:	"https://4game.ru/widget",
			data: 		{},
			onLoad:		null,
			onError:	null,
			onSuccess:	null,
			table:		0
		}, opts);

		if (!options.partnerId || !options.serviceId) {
			throw "partner_id or service_id is not set";
		}

		$(this).each(function () {

			var t = this;
			var e = $(this);

			var onSubmitForm = function (ev) {
				ev.preventDefault();
				ev.stopPropagation();
				var form = this;
				var p = (p = new RegExp('(?:^|; )' + encodeURIComponent("pid") + '=([^;]*)').exec(document.cookie)) ? decodeURIComponent(p[1]) : null;

				if (p)
				{
					$("input[name=partnerId]", $(form)).val(p);
				}

				ev.preventDefault();
				$.ajax({
					url: form.action,
					dataType: "jsonp",
					jsonp: "jsonp_callback",
					data: $(form).serialize(),
					success: function (response) {
						e.html(response.html);
						$("form.quickreg", e).submit(onSubmitForm);
						$("form.quickreg input[type=submit]", e).click(function(ev) {
							ev.preventDefault();
							ev.stopPropagation();
							onSubmitForm.apply($("form.quickreg", e)[0], [ev]);
						});
						if (response.errors && typeof options.onError == 'function') {
							options.onError.apply(form, [response.errors]);
						}
						if (typeof options.onSuccess == 'function') {
							options.onSuccess.apply(t, [response]);
						}
					},
					error: function (xhr) {
						// do something
					}
				});
			};

			$.ajax({
				dataType: "jsonp",
				jsonp: "jsonp_callback",
				data: $.extend({
					partnerId: options.partnerId,
					serviceId: options.serviceId,
					table: options.table
				}, options.data),
				url: options.serviceUrl,
				success: function (response) {
					e[0].innerHTML = response.html;
					$("form.quickreg", e).submit(onSubmitForm);
					$("form.quickreg input[type=submit]", e).click(function(ev) {
						ev.preventDefault();
						ev.stopPropagation();
						onSubmitForm.apply($("form.quickreg", e)[0], [ev]);
					});
					if (typeof options.onLoad == 'function') {
						options.onLoad.call(t);
					}
				},
				error: function (xhr) {
					// do something
				}
			});

		});

		return this;
	};

})(jQuery);
