// $Id: openapi.js,v 1.14 2010/10/06 19:35:51 romka Exp $

var
  vk_members_data = {},
  lastCommentsResponse,
  lastCommentsPage = null,
  baseURL =window.location;
  // window.location.protocol + '//' + window.location.hostname + '/'+  window.location;
  //alert(baseURL);
basePath='';
function array_unique(ar){
  if (ar.length && typeof ar !== 'string') {
    var sorter = {};
    var out = [];
    for (var i=0, j=ar.length; i<j; i++) {
      if(!sorter[ar[i]+typeof ar[i]]){
        out.push(ar[i]);
        sorter[ar[i]+typeof ar[i]]=true;
      }
    }
  }
  return out || ar;
}

function doLogin() {
  VK.Auth.login(getInitData);
}

function doUnite() {
  VK.Auth.login(uniteGetInitData);
}

//------- Private methots JS
function SendRequestFrends()
{
	alert('SendRequestFrends');
	VK.callMethod("showInviteBox",{});	
	VK.callMethod("resizeWindow", 510, 600);
}

function showPaymentBox(votes)
{
	alert('showPaymentBox');
//	VK.callMethod("showPaymentBox",{1});	
}

function showSettingsBox()
{
	alert('showSettingsBox');
	VK.callMethod("showSettingsBox",{});	
}

function saveWallPost()
{
	
		//VK.callMethod("saveWallPost",{hash});	
}

function superPanelVK(idP)
{
  var X='';
    X+='<div id="panelsVK_1"><a href="#" onClick="SendRequestFrends(); return false;">Пригласить друга</a></div>';
	X+='<div id="panelsVK_2"><a href="#" onClick="showSettingsBox(); return false;">Настройки</a></div>';
	X+='<div id="panelsVK_3"><a href="#" onClick="showPaymentBox(1); return false;">Пожертовать 1 голос</a></div>';
	X+='<div id="panelsVK_4"><a href="#" onClick="saveWallPost(); return false;">Запись на стене</a></div>';
	var elIdp= document.getElementById(idP);
	if (elIdp)
	{
		elIdp.innerHTML=X;
	}
}
function doLogout(api,mid,sid) {

 
 document.location='http://vkontakte.ru/logout.php?openapi=1&app='+api+'&mid='+mid+'&sid='+sid+'&rnd='+parseInt(Math.random()*10000);
  VK.Auth.logout(logoutOpenAPI+'?vklogout=1');
}

function loginOpenAPI() {
  getInitData();
}

function logoutOpenAPI() {
  window.location = baseURL;
}

function getInitData() {
  var code;
  code = 'return {';
  code += 'me: API.getProfiles({uids: API.getVariable({key: 1280})})[0]';
  /*
    ,sex,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
  */
  code += '};';
  VK.Api.call('execute', {'code': code}, onGetInitData);
}

function uniteGetInitData() {
  var code;
  code = 'return {';
  code += 'me: API.getProfiles({uids: API.getVariable({key: 1280})})[0]';
  /*
    ,sex,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
  */
  code += '};';
  VK.Api.call('execute', {'code': code}, uniteOnGetInitData);
}


function onGetInitData(data) {
  var r, i, j, html;
  if (data.response) {
    r = data.response;
    /* Insert user info */
	alert(basePath + 'vk/login');
	alert(var_dump( data.response));
    if (r.me) {
		alert('Yes');
      $.ajax({
        cache: false,
        data: {uid: r.me.uid, first_name: r.me.first_name, last_name: r.me.last_name, nickname: r.me.nickname},
        dataType: 'json',
        success: function(data) { succesLogin(data); },
        error: function(data) { errorLogin(data); },
        type: 'POST',
		    url: basePath + 'vk/login'
      });
    }    
  } else {
	  //window.location = baseURL + 'vk/login/error';
	  window.location = baseURL;
  }
}

function uniteOnGetInitData(data) {
  var r, i, j, html;
  if (data.response) {
    r = data.response;
    /* Insert user info */
    if (r.me) {
      $.ajax({
        cache: false,
        data: {uid: r.me.uid, first_name: r.me.first_name, last_name: r.me.last_name, nickname: r.me.nickname},
        dataType: 'json',
        success: function(data) { succesLogin(data); },
        error: function(data) { errorLogin(data); },
        type: 'POST',
		    url: basePath + 'vk/succesfull-unite'
      });
    }    
  } else {
    window.location = baseURL + 'vk/error-unite';
  }
}

function succesLogin(data) {
	if(data.error) {
		alert(data.message);
	}
	window.location = baseURL + data.redirect_url;
}

function errorLogin(data) {
	if(data.error) {
		alert(data.message);
	}
	alert('Error connecting to server.');
	//window.location = baseURL + data.redirect_url;
}

/*
function onGetStatus(data) {
  alert('try to set status');
  if (data.response) {
    r = data.response;
    alert(r.me.activity);
  }
}
*/

<!--- Anontation --->
 function vkConnect_onClick(obj) 
 {
        AMS.RegisterAuthorizationTry("Vkontakte");
		VKExt.LoginAndCheckPermissions(
		    //on success
            function(sessionData){
                __doPostBack("VKConnect");
            },
            //on fail
            function() {
                AMS.RegisterAuthorizationFail("Vkontakte", "ID: LoginAndCheckPermissions failed");                
            }
		);
	}

function Delete_Cookie( name, path, domain ) 
{
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
	
	function Get_Cookie( name ) {

var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) &&
( name != document.cookie.substring( 0, name.length ) ) )
{
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}

