rhSocial = {
    loginBtnSelector  : '.socialAuthLogin',
    socialMenuSelector: '.socialMenu',
    authWinId: 'mb-social-login-auth-window',
    loggedKeyCookie:'rhclientid',
    arrowMenuSelector: '.client-links-button-dropdown',
    clientNameSelector: '#client-name',
    listSector: '.client-links-list',
    logoutSelector: '#client-logout',
    viewedLiSelctor: '#client-viewed',
    sendedLiselector: '#client-sended',
    highlighLiClass: 'client-links-list-on',
    
    init: function(){
        $(rhSocial.loginBtnSelector).bind('click', rhSocial.showAuthWin);
        rhSocial.vk.init();
        rhSocial.fb.init();
        
        $(rhSocial.arrowMenuSelector).bind('click',rhSocial.showDropDownList);
        $(rhSocial.socialMenuSelector).bind('click',rhSocial.showDropDownList);
        $('html').bind('click',  rhSocial.hideDropDownList );
        
        $(rhSocial.logoutSelector).bind('click', rhSocial.logout);
    },
    showAuthWin: function(){
        rhModal.showWin( rhSocial.authWinId );
    },
    logout: function(){
         // unset cookies
        $.cookie(rhSocial.loggedKeyCookie, null);
        var date = new Date();
        date.setTime(date.getTime()+(-1*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
        var path = window.location.pathname;
        document.cookie = rhSocial.loggedKeyCookie+""+expires+"; path=/";
        //document.cookie = rhSocial.loggedKeyCookie+""+expires+"; path="+path;
        
        $(rhSocial.listSector).hide();
        $(rhSocial.socialMenuSelector).hide();
        $(rhSocial.clientNameSelector).html(null);
        $(rhSocial.loginBtnSelector).show();
    },
    hideDropDownList: function(){
        $(rhSocial.listSector).hide();
        var li = $(rhSocial.listSector).parent();
        li.removeClass(rhSocial.highlighLiClass);
    },
    showDropDownList: function(){
        if($(rhSocial.listSector).css('display') == 'none'){
            var li = $(rhSocial.listSector).parent();
            var top = 0;
            top += li.outerHeight();//true);

            $(rhSocial.listSector).offset({top:top});//, left: left});
            li.addClass(rhSocial.highlighLiClass);
            $(rhSocial.listSector).show();
        }else{
            rhSocial.hideDropDownList();
        }
        return false;
    },
    showMenu: function(client){
        
        var name = null;
        if(client.first_name){
            name = client.first_name+" ";
        }
        if(client.last_name){
            name += client.last_name;
        }
        var countViewed = 0, countSended = 0;
        var hrefViewed = '#', hrefSended = '#';
        if(client.viewed){
           countViewed = client.viewed.length;           
           if(countViewed > 0){
                hrefViewed = '/rentals/?offer='+client.viewed.join('.');
           }
        }
        if(client.sended){
           countSended = client.sended.length;
           if(countSended>0){
                hrefSended = '/rentals/?offer='+client.sended.join('.');
           }
        }
        $(rhSocial.viewedLiSelctor+'>a').html('Просмотрено ('+countViewed+')');
        $(rhSocial.viewedLiSelctor+'>a').attr('href',hrefViewed);
        
        $(rhSocial.sendedLiselector+'>a').html('Отправлено ('+countSended +')');
        $(rhSocial.sendedLiselector+'>a').attr('href', hrefSended);
        
        $(rhSocial.clientNameSelector).html(name);
        $(rhSocial.loginBtnSelector).hide();
        $(rhSocial.socialMenuSelector).show();
    },
    auth: function(data){
        // unset cookies
        $.cookie(rhSocial.loggedKeyCookie, null);
        data.action = 'login';
        $.ajax({
            url: "/social/index.php",
            data: data,
            success: function(client){
                client = $.parseJSON(client);
                if(client){
                    var clientId = client.id; 
                    if(!isNaN(parseInt(clientId))){
                        $.cookie(rhSocial.loggedKeyCookie, parseInt(clientId));
                        rhSocial.showMenu(client);
                    }
                }
                rhModal.hide();
            },
            error: function(){
                rhModal.hide();
            }
        });
    },
    authError: function(){
        rhModal.hide();
    }
}

rhSocial.vk = {
    //appID: 2691576, //dev
    appID: 2698636, // renthome.ru
    idLoginBtn: 'vk_login_button',
    authInfo: function(response) {
          if (response.session) {
              if(response.session.user){
                  var data = {
                      firstname: response.session.user.first_name,
                      lastname: response.session.user.last_name,
                      vkid: response.session.user.id
                  };
                  rhSocial.auth(data);
                  return;
              }
          }
          rhSocial.authError();
    },
    init: function(){
        VK.init({
            apiId: rhSocial.vk.appID
        });
        VK.UI.button(rhSocial.vk.idLoginBtn);
        $('#'+rhSocial.vk.idLoginBtn).bind('click', function(){
            VK.Auth.login(rhSocial.vk.authInfo);
            VK.Auth.getLoginStatus(rhSocial.vk.authInfo);
        });
    }
}

rhSocial.fb = {
    appID: 125674707544894,
    //appID: 249414575117917, //dev
    idLoginBtn: 'rh-fb-login-btn',// 'fb-login-button',
    getUserInfo: function(userId){
        var query = FB.Data.query('SELECT uid, name, first_name, last_name, email, proxied_email, email_hashes FROM user WHERE uid = me()');
        query.wait(function(rows) {
            var data = {
                      firstname: rows[0].first_name,
                      lastname:  rows[0].last_name,
                      fbid:      rows[0].uid
                      //email: rows[0].email
                  };
           if(rows[0].email){
               data.email = rows[0].email;
           }
           rhSocial.auth(data);
        });
    },
    init: function(){
        window.fbAsyncInit = function() {
            
            FB.init({
                  appId      : rhSocial.fb.appID, // App ID
                  //channelUrl : '//dboytsov.dev.renthome.ru/channelFB.html',
                  status     : true, // check login status
                  cookie     : true, // enable cookies to allow the server to access the session
                  oauth      : true, // enable OAuth 2.0
                  xfbml      : true  // parse XFBML
            });
            //redefine
            FB.QS.decode = function(f){
                var a=decodeURIComponent,d={},e=f.split('&'),b,c;
                try{
                    for(b=0;b<e.length;b++){
                        c=e[b].split('=',2);
                        if(c&&c[0])
                            d[a(c[0])]=a(c[1]||'');
                    }
                }catch(exc){};
                return d;
           }
            
        };
        $('#'+rhSocial.fb.idLoginBtn).bind('click', function(){
            FB.login(function(response) {
                   if (response.authResponse) {
                     rhSocial.fb.getUserInfo(response.authResponse.userID);
                   } else {
                     rhSocial.authError();
                   }
            }, {scope: 'email'});
        });
        
        // 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 = "http://connect.facebook.net/en_US/all.js";
             //js.src = "//connect.facebook.net/ru_RU/all.js";
             d.getElementsByTagName('head')[0].appendChild(js);
        }(document));

    }
}


