/**
 * Login form
 * (requires jQuery.js, PopupBlock.js)
 */

var LoginForm = function (options) {

	var that = new PopupBlock(options);

	var form = options.container.find("form");
	var errors = options.container.find(".errors");
	var progress = options.container.find(".progress");

	var form_data = {
		"is-ajax": "true"
	};
	
	/**
	 * Replaces current login with the new one
	 * @param {String} login New login
	 */
	function replaceLogin(login) {
		$("#user_info .user").text(login);
		$("#user_info .logout").removeClass("hidden");
		$("#user_info .logon").addClass("hidden");
	}

	var maySubmit = false;

	form.submit(function () {

		if (maySubmit) {
			return true;
		}

		errors.addClass("hidden");
		progress.removeClass("hidden");

		// Prepare form data for sending
		form.find("input").each(function () {
			form_data[this.name] = this.value;
		});

		// We are going to submit our form with AJAX
		$.ajax({

			// The URL to request
			"url": "/login_ajax/",

			// POST на локале работать отказался
			"type": "GET",

			// Force the requested page to not be cached by the browser
			"cache": "false",

			// We are expecting JSON back from the server
			"dataType": "json",
			//"traditional": "true",

			// Data to be sent to the server
			"data": form_data,

			success: function (data) {
				if (data.status == "success") {
					form.attr('action', location.href);
					maySubmit = true;
					replaceLogin(data.username);
					that.hide();
					//form.submit();
					//document.location.reload();
					if (data.url) {
						document.location.href = data.url;
					}
				} else {
					progress.addClass("hidden");
					errors.html(data.message).removeClass("hidden");
				}
			}
		});

		// Prevent the form from being submitted
		return false;

	});

	that.superior = function (name) {
		var that = this,
		    method = that[name];
		return function () {
			return method.apply(that, arguments);
		};
	};

	var super_show = that.superior("show");
	var super_hide = that.superior("hide");

	that.show = function (event) {
		super_show(event);
		form.find("input[name='auth.name']").focus();
	};

	that.hide = function (event) {
		super_hide(event);
	};

	return that;
};


$(function () {

	var Login = new LoginForm({
		container: $("#user-enter"),
		link: $("#user-info .logon a"),
		fader: $("#fader"),
		close: $("#user-enter .icon_close")
	});

});

