var baseURL = window.location.href;

$(function(){

    function authinfo(response) {
//	alert(response);
	if (response.session) {
//	alert(response);
	setusername();
	}
//  window.location = baseURL;
            
    
    };
//window.location = baseURL

function doLogin() {
//    alert(1);
  VK.Auth.login(
    authinfo,
    VK.access.FRIENDS | VK.access.WIKI
  );

  VK.Auth.getLoginStatus(authinfo);

}

function doLogout() {
  VK.Auth.logout(logoutOpenAPI);
}
function loginOpenAPI() {
  getInitData();
}
function logoutOpenAPI() {
  /*window.location.reload();*/
  window.location = baseURL;
}


function SetInfo(info) {
//   alert(info);
    if (info){
	$("#info").html('<img src="'+info.photo+'" /> Привет, '+info.first_name+' '+info.last_name+'! '+'<br /><a href="#" id="logout_button">Выйти</a>');
    }
}


function setusername() {
//	    alert(1);
          var code;
    	  code = 'return {';
          code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
          code += '};';
	VK.Api.call('execute', {'code': code}, function(data) {
	    // Действия с полученными данными
	    if (data.response){
		r = data.response;
		if (r.me) {
//		 alert(r.me.first_name+' '+r.me.last_name);
		$.ajax({
		    url: '/cgi-bin/ajax.pl?do=setusername&id='+r.me.uid+'&username='+r.me.first_name+' '+r.me.last_name,
		    type: "GET",
		    success: function(data){
			window.location = baseURL;
		    }
		});
		} else {
		  alert("Not response me");
		}
		
	    } else {
		alert("Not response data 1");
	    }
	});
}

function GetInfo() {

          var code;
    	  code = 'return {';
          code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
          code += '};';
    	  var info;
//    	  alert(1);
	VK.Api.call('execute', {'code': code}, function(data) {
	    // Действия с полученными данными
	    if (data.response){
		r = data.response;
//		alert(r.me.first_name);
		if (r.me) {
//		 alert(r.me.first_name);
		 SetInfo(r.me);
		}
	    } else {
//		alert("Not response data 2");
	    } 
//	    alert(2);
	});
//	alert(3);
}

//GetInfo();
VK.Auth.getLoginStatus(GetInfo);


//$("#login_button").click(function(){
$("#vk_login").live("click", function(e) {
    doLogin();
});

$("#logout_button").live("click", function(e) {
    doLogout();
});

});


