﻿var isAuth = 0;
var updateProfilePath = '/register/update/';



// РАЗОБРАТЬСЯ С КУКАМИ
var qqq = readCookie('authType')


window.vkAsyncInit = function() {
	VK.init({
		apiId: 2648528
	});
// если пользователь не авторизован у нас, проверяем внешнюю авторизацию
	if (document.cookie.indexOf('userData') == -1){
		VK.Auth.getLoginStatus(function(response) {
			if (response.session) {
				/* Авторизованный в Open API пользователь */
				if (document.cookie.indexOf('authType') == -1 && document.cookie.indexOf('authFrom') == -1) {
					/* авторизуем пользователя у нас, если он не новый и еще не авторизован */
					var userId = response.session.mid;
					authVkUser(userId,0);
				}
			} else {
				/* Неавторизованный в Open API пользователь */
			}
		});
	}
	var loginButton = document.getElementById('vk_login');
	if (loginButton != null) {
		VK.UI.button('vk_login');
	}
};


setTimeout(function() {
	var el = document.createElement("script");
	el.type = "text/javascript";
	el.src = "http://vkontakte.ru/js/api/openapi.js";
	el.async = true;
	document.getElementById("vk_api_transport").appendChild(el);
}, 0);


function doLogin() {
	VK.Auth.login(function(response) {
		if (response.session) {
			/* Пользователь успешно авторизовался */
			var userId = response.session.mid
			/* авторизуем пользователя у нас на сайте */
			authVkUser(userId,1);
			if (response.settings) {
				/* Выбранные настройки доступа пользователя, если они были запрошены */
			}
		} else {
			/* Пользователь нажал кнопку Отмена в окне авторизации */
		}
	});
}


function doLogout() {
	VK.Auth.logout();
	$.post('/ajax/clearAuth.html', function() {
		window.location = '/'
	});
}


function authVkUser(userId,registerUser) {
	VK.api('getProfiles', {uids: userId, fields: "uid, first_name, last_name, photo, sex, bdate, city, country"}, function(data) {
		if (data.error) {
			alert(data.error.error_msg);
		} else {
			if (data.response) {
				/* имя и фамилия */
				var userName = data.response[0].first_name;
				var userSurname = data.response[0].last_name;
				var sex;
				if (data.response[0].sex == 2) {sex = 'male'} else {sex = 'female'}
				var cityId = data.response[0].city;
				var countryId = data.response[0].country;
				var cityName;
				var countryName;
				/* получаем название города */
				if (data.response[0].city) {
					VK.api('places.getCityById', {cids: cityId}, function(data) {
						if (data.response) {
							cityName = data.response[0].name
						}
					});
				}
				/* получаем название страны */
				if (data.response[0].country) {
					VK.api('places.getCountryById', {cids: countryId}, function(data) {
						if (data.response) {
							countryName = data.response[0].name
						}
					});
				}
				/* авторизуем пользователя */
				setTimeout(function() {
// если пользователь нажал кнопку "войти", авторизуем его и создаем нового, если такого пользователя у нас нет
					if (registerUser == 1) {
						$.post('/ajax/createAuth.html', { 'authId': userId, 'authFrom': 'vkontakte', 'authName': userName + ' ' + userSurname, 'authSex': sex, 'authCity': cityName, 'authCountry': countryName, 'authDtBirth': data.response[0].bdate }, function() {
// если пришел новый пользователь, делаем редирект на создание профайла
							if (document.cookie.indexOf('authType') != -1) {
								window.location = updateProfilePath
// если пользователь существует у нас - обновляем страницу
							} else {
								window.location.reload();
							}
						})
// иначе авторизуем существующего пользователя и не создаем нового
					} else {
						$.post('/ajax/createUser.html', { 'authId': userId, 'authFrom': 'vkontakte', 'authName': userName + ' ' + userSurname, 'authCity': cityName, 'authCountry': countryName, 'authDtBirth': data.response[0].bdate }, function() {
							window.location.reload();
						})
					}
				}, 300)
			}
		}
	});
}


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
