/************************************************/
/* IPB3 Javascript                              */
/* -------------------------------------------- */
/* ips.facebook.js - Facebook Connect code      */
/* (c) IPS, Inc 2008                            */
/* -------------------------------------------- */
/* Author: Matt Mecham, Rikki Tissier           */
/************************************************/

var facebook = {
    api: '',
    linkedMember: {},
    mem_fb_uid: 0,
    
    /*------------------------------*/
    /* Constructor                  */
    init: function()
    {
    },
    
    /**
     * Wrapper for loadUser when used on the log in page
     */
    login_loadUser: function()
    {
        /* Annoyingly, this has to go here */
        facebook.api = FB.Facebook.apiClient;
        
        facebook.loadUser();
    },
    
    /**
     * Wrapper for loadUser when used on the register page
     */
    register_loadUser: function()
    {
        var content = $('fb-template-main').innerHTML;
        
        /* Annoyingly, this has to go here */
        facebook.api = FB.Facebook.apiClient;
        
        $('fbUserBox').set('html', content );
        FB.XFBML.Host.parseDomTree();
        
        /* Set up handler */
        $('fbc_completeNewAcc').addEvent('click', facebook.login_completeNewAcc );
    },
    
    //Fix
    /**
     * Wrapper for loadUser when used on the UserCP page
     */
    usercp_loadUser: function()
    {
        /* Has this ID been saved, yet? */
        if ( facebook.mem_fb_uid < 1 )
        {
            window.location = '/myaccount/facebookLink/?do=custom&secure_key=' + $('secure_key').value;
        }
        
        /* Annoyingly, this has to go here */
        facebook.api = FB.Facebook.apiClient;
        
        fbUserId = FB.Facebook.apiClient.get_session().uid;

        if (facebook.mem_fb_uid != fbUserId) {
            var userConflict = '<div class="box"><h3 class="blocktitle upper">Facebook Connect Error</h3><p>The <em>Facebook account</em> you are currently logged into is already linked to another Closet Couture account. You may only link your Facebook account to one user account on Closet Couture.</p><p>If you have the wrong Facebook and Closet Couture accounts associated with each other, you must logout and log back into Closet Couture using the correct Facebook Connect account. Once you have logged back in, you must unlink this account from Facebook, logout and repeat the procedure with your other account. Once both accounts have been unlinked from Facebook accounts, you can start the Facebook Connect process over again and link the desired Closet Couture account to your Facebook user. If you need help doing this, please email <a href="mailto:help@closetcouture.com">help@closetcouture.com</a> for assistance.</p><fb:login-button size="medium" background="light" length="long" autologoutlink="true" onlogin="facebook.usercp_loadUser(); window.location.reload();"></fb:login-button></div>';
            $('fb-template').set('html',userConflict);        
        }
        
        if (facebook.mem_fb_uid > 0) {
            $$('.fbconnect_login_button').setStyle('display','none');
            if ($('editFBC_Settings')) {
                $('editFBC_Settings').setStyle('display','block');
            }
        }
        
        $('fb-loginbutton').setStyle('display','none');
        $('fb-template').setStyle('display','block');
        FB.XFBML.Host.parseDomTree();
        
        /* Set up handler */
        if ($('fbc_sync')) {
            $('fbc_sync').addEvent('click', facebook.usercp_resync );
        }
        
        if ($('fbc_remove')) {
            $('fbc_remove').addEvent( 'click', facebook.usercp_remove );
        }
    },
    
    /**
    * Updates the log in box
    *
    */
    login_updateBox: function()
    {
        /* INIT */
        var content       = $('fb-template-main').innerHTML;
        
        if ( facebook.linkedMember['member_id'] > 0 )
        {
            content = content + $('fb-template-linked').innerHTML;
        }
        else
        {
            content = content + $('fb-template-notlinked').innerHTML;
        }

        $('fbUserBox').set('html', content );
        FB.XFBML.Host.parseDomTree();
            
        /* Set up handlers */
        $('fbc_completeNewAcc').addEvent('mousedown', facebook.login_completeNewAcc );
        $('fbc_completeWithLink').addEvent('mousedown', facebook.login_linkCheck );
        $('fbc_complete').addEvent('mousedown', facebook.login_complete );
    },
    
    /**
    * Loads the URL to remove the app
    *
    */
    usercp_remove: function()
    {
        window.location = '/myaccount/facebookRemove/?do=custom&secure_key=' + $('secure_key').value;
    },
    
    /**
    * Loads the URL to resync
    *
    */
    usercp_resync: function()
    {
        $('userCPForm').submit();
        //window.location = ipb.vars['base_url'] + 'app=core&module=usercp&tab=members&area=facebookSync&do=custom';
    },
    
    /**
    * Simply submits our form so PHP can do the final checks
    *
    */
    login_completeNewAcc: function()
    {
        $('fbc_linkNewAccForm').submit();
    },
    
    /**
    * Simply submits our form so PHP can do the final checks
    *
    */
    login_complete: function()
    {
        $('fbc_linkAlreadyForm').submit();
    },
    
    /**
    * Check, via AJAX for an existing account
    *
    */
    login_linkCheck: function()
    {
        /* Fetch FB ID */
        fbUserId = FB.Facebook.apiClient.get_session().uid;
        
        new Request.JSON({
                            method: 'post',
                            data: { 'referer': $('referer').value, 'emailaddress' : $('fbc_emailAddress').value, 'password' : $('fbc_password').value },
                            onSuccess: function(t) {

                                if(!t)
                                {
                                    return false;
                                }

                                _result = t;
                                if ( _result.status == 'error' )
                                {
                                    $('fbc_linkError').set('html',"Email or password incorrect");
                                    $('fbc_linkError').setStyle('display','block');
                                }
                                else
                                {
                                    if ( _result.memberData.fb_uid != 0 ) {
                                        $('fbc_linkError').set('html',"That member is already linked to a facebook account");
                                        $('fbc_linkError').setStyle('display','block');
                                    }
                                    else {
                                        /* Submit the form and let PHP re-check this and use the facebook PHP facebook.api to validate the signature, etc */
                                        $('fbc_linkForm').submit();
                                    }
                                }
                            }
                        }
                    ).get('/more/fbc/?do=authenticateUser');
    },
    /**
     * Check to see if the facebook user is linked to an IPB account
     */
    loadUser: function()
    {
        /* Already been here? */
        if ( typeof( facebook.linkedMember['member_id'] ) != 'undefined' )
        {
            return;
        }
        /* Fetch FB ID */
        fbUserId = FB.Facebook.apiClient.get_session().uid;
        
        /* Got a linked member? */
        new Request.JSON({
                        onSuccess: function(t) {
                            if(t) {
                                facebook.linkedMember = t;
                            }
                            else {
                                facebook.linkedMember = { 'member_id' : 0 };
                            }
                            
                            facebook.login_updateBox();
                        }
                    }).get('/more/fbc/?do=getUserByFbId&fbid=' + fbUserId);        
    }
}

facebook.init();