﻿window.fbAsyncInit = function() {
	FB.init({appId: '128841892804', status: true, cookie: true, oauth: true, xfbml: true});
// если пользователь не авторизован у нас, проверяем внешнюю авторизацию
	if (document.cookie.indexOf('userData') == -1){


		FB.getLoginStatus(function(response) {
			if (response.authResponse) {
				// logged in and connected user, someone you know
				AuthFbUser();

//				FB.api('/me', function(response) {
//					alert(
//						'Name: ' + response.name + 
//						', Id: ' + response.id + 
//						', Gender: ' + response.gender + 
//						', E-mail: ' + response.email +
//						', Birthday: ' + response.birthday +
//						', Location: ' + response.location.name +
//						', Picture link: ' + 'http://graph.facebook.com/' + response.id + '/picture'
//					);
//				});

	
			} else {
				// no user session available, someone you dont know
			}
		});
		FB.Event.subscribe('auth.login', function (response) {
//			авторизуем пользователя у нас
			AuthFbUser();
		});
	};
};


// Load the SDK Asynchronously
(function(d){
	var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	d.getElementsByTagName('head')[0].appendChild(js);
}(document));


function AuthFbUser() {
//	получаем информацию по пользователю
	FB.api('/me', function(response) {
		var dtBirthArray = response.birthday.split('/');
		var dtBirth = dtBirthArray[2] + '-' + dtBirthArray[0] + '-' + dtBirthArray[1];
		var locationArray = response.location.name.split(', ');
		var cityName = locationArray[0];
		var countryName = locationArray[locationArray.length - 1];
//		авторизуем пользователя
		$.post('/ajax/createAuth.html', { 'authId': response.id, 'authFrom': 'facebook', 'authName': response.name, 'authSex': response.gender, 'authEmail': response.email, 'authCity': cityName, 'authCountry': countryName, 'authDtBirth': dtBirth, 'authPicture': 'http://graph.facebook.com/' + response.id + '/picture' }, function() {
//		если пришел новый пользователь, делаем редирект на создание профайла
			if (document.cookie.indexOf('authType') != -1) {
				window.location = '/register/update/';
// если пользователь существует у нас - обновляем страницу
			} else {
				window.location.reload();
			};
		});
	});
};


function LogoutFbUser() {
	FB.logout(function(response) {
		// user is now logged out
		$.post('/ajax/clearAuth.html', function() {
			window.location = '/'
		});
	});
}
