$(document).ready(function() {
    if ($('.facebook-small').length > 0) {
        window.vkAsyncInit = function() {
            VK.init({
                apiId: VK_APP_ID,
                nameTransportPath: '/xd_receiver.html'
            });
        };

        (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);
        }());
    }
});

function doLogin() {
    VK.Auth.login(function(response) {
        if (response.session) {
            getData();
        } else {
        }
    });
}
function setCookie(name, value, expiredays, path, domain, secure) {
    if (expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        var expires = exdate.toGMTString();
    }
    document.cookie = name + "=" + escape(value) +
            ((expiredays) ? "; expires=" + expires : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
}

function getData() {
    var str;

    // достаем uid
    VK.Api.call('getVariable', {key: 1280}, function(r) {
        if (r.response) {
            // достаем профиль по uid
            VK.Api.call('getProfiles', {'uids': r.response}, function(data) {
                if (data.response) {
                    // устанавливаем куку
                    str = 'uid=' + data.response[0].uid;
                    setCookie("auth_vk_" + VK_APP_ID, str, 1, "/");
                    window.location.href = 'openidlogin?provider=vkontakte';
                }
            });
        }
    });

}
