/**
 * @requires js/modules/loading.js
 */

if (typeof(m) == "undefined" || !m) {
	var m = {};
}

(function($) {
	m.vkLogin = function(config)
	{
		this.config = {
			prepareUrl : '/user/auth/preparevk/',
			onSuccess : this.onSuccess,
			onError : this.onError
		};

		if (typeof(config) == 'object' && config) {
			this.config = $.extend(this.config, config);
		}
	}

	m.vkLogin.prototype.isLoggedIn = function(callback)
	{
		var that = this;
		m.loading.show();
		VK.Auth.login(function(data) {
			m.loading.hide();

			var session = null;
			var result = false;
			if (data.status == 'connected') {
				result = true;
				session = data.session;
			}

			callback.call(that, result, session);
		});
	}

	m.vkLogin.prototype.simpleLogin = function(callback)
	{
		var that = this;

		m.loading.show();
		VK.Auth.login(function(data) {
			m.loading.hide();

			if (data.session) {
				var res = true;
			} else {
				var res = false;
			}

			callback.call(that, res);
		});
	}

	m.vkLogin.prototype.login = function(callback)
	{
		var that = this;

		m.loading.show();
		VK.Auth.login(function(data) {
			if (data.session) {
				that.getProfile(data.session.user.id, function(profile) {
					profile.sid = data.session.sid;

					$.post(that.config.prepareUrl, profile, function(resData) {
						m.loading.hide();

						if (resData.result) {
							that.config.onSuccess.call(that, resData);
						} else {
							that.config.onError.call(that, resData);
						}
					}, 'json');
				}, true);
			} else {
				m.loading.hide();
				that.config.onError.call(that, data);
			}
		});
	}

	m.vkLogin.prototype.getProfile = function(id, callback, loadCity)
	{
		var fields = 'uid,first_name,last_name,nickname,domain,sex,bdate,city,country,timezone,photo,photo_medium,photo_big,has_mobile,rate,contacts,education';
		var that = this;

		VK.Api.call('getProfiles', {uids : id, fields : fields}, function(profile) {
			var data = profile.response[0];

			if (loadCity && profile.response[0].country != '0' && profile.response[0].city != '0') {
				VK.Api.call('places.getCountryById', {cids:profile.response[0].country}, function(country) {
					VK.Api.call('places.getCityById', {cids:profile.response[0].city}, function(city) {
						data.country = country.response[0];
						data.city = city.response[0];

						callback.call(that, data);
					});
				});
			} else {
				callback.call(that, data);
			}
		});
	}

	m.vkLogin.prototype.onError = function(data)
	{
		alert('Ошибка авторизации');
	}

	m.vkLogin.prototype.onSuccess = function(data)
	{
		m.loading.show();

		if (typeof(data.url) == 'string') {
			window.location = data.url;
		} else if ($('#server-request-method').text() == 'get') {
			window.location.reload();
		} else {
			window.location = data.default_redirect;
		}
	}
}) (jQuery);
