var loginExec = false;

window.vkAsyncInit = function() {
	VK.Observer.subscribe('auth.login', function(response) {
		// window.location = '/user/home';
		//$.cookie("unload", "1");
		//getInitData();
		if (loginExec) {
			getInitData();
		}
	});
	VK.Observer.subscribe('auth.logout', function() {
		// console.log('logout');
	});
	VK.Observer.subscribe('auth.statusChange', function(response) {
		// console.log('statusChange');
	});
	VK.Observer.subscribe('auth.sessionChange', function(r) {
		// console.log('sessionChange');
	});
	VK.init( {
		apiId : 1930527,
		nameTransportPath : '/xd_receiver.html'
	});	
	
	if (document.location.pathname == '/' || 
		document.location.pathname == '/user/settings' ||
		document.location.pathname == '/user/settings/' ||
		document.location.pathname == '/user/login/' ||
		document.location.pathname == '/user/login') {
		VK.UI.button('vk_login');
	}
};
(function() {
	var el = document.createElement('script');
	el.type = 'text/javascript';
	el.src = 'http://vkontakte.ru/js/api/openapi.js';
	el.charset = 'windows-1251';
	el.async = true;
	document.getElementById('vk_api_transport').appendChild(el);
}());

var vk_members_data = {}, lastCommentsResponse, lastCommentsPage = null, baseURL = window.location.protocol
		+ '//' + window.location.hostname + '/';

function doLogin() {
	VK.Auth.login(
	 getInitData()//, 4
	);
}

function doLogout() {
	VK.Auth.logout(function() {document.location = '/user/logout/';
	});
}

function getInitData() {
	loginExec = true;
	
	var code;
	code = 'return {';
	code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "nickname,sex,photo_rec,bdate,city,country,timezone,photo,photo_medium,photo_big,has_mobile,rate,contacts,education,home_phone,mobile_phone,university,university_name,faculty,faculty_name,graduation"})[0]';
	code += ',info: API.getGroupsFull({gids:1})[0]';
	code += ',news: API.pages.get({gid:1, pid: 2424933, need_html: 1})';
	code += ',friends: API.getProfiles({uids: API.getAppFriends(), fields: "photo"})';
	code += '};';
	VK.Api.call('execute', {
		'code' : code
	}, onGetInitData);
}

function onGetInitData(data) {
	if (data.response) {
		VK.Auth.getLoginStatus();
		$.ajax( {
			type : "POST",
			url : '/user/registrationvk',
			data : data.response.me,
			success : function(resp) {
				if (resp == 'ok' || resp == 'registered') {
					window.location = '/user/home';
				} else {
					alert('Ошибка регистрации, зарегистрируйтесь самостоятельно.');
				}
			}
		}); // data.response.me
	}
}
