<% provide(:title, "Facebook Invitations") %>
<%= javascript_include_tag "jquery" %>
<%= javascript_include_tag "jqfmfs/jquery.facebook.multifriend.select" %>
<%= stylesheet_link_tag "jqfmfs/jquery.facebook.multifriend.select" %>
<h1>Facebook Invitations</h1>

<div class="row">
    <div class="span6 offset3">
        <!-- required element. do not remove -->
        <div id="fb-root"></div>


        <a id="invite_friends_via_facebook" href="#">Invite Friends via Facebook</a>
    </div>
</div>
<div class="row">
    <div id="facebook-invitations">

        <div id="username"></div>
        <button id="send-friends" class="btn btn-primary">Send</button>
        <button id="cancel-friends" class="btn">Cancel</button>
        <div id="jfmfs-container"></div>
    </div>
</div>


<script type="text/javascript">

    window.fbAsyncInit = function() {
        // init the FB JS SDK
        FB.init({
            appId      : '<%= SampleApp::Application.config.facebook_key %>', // App ID from the App Dashboard
            // channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File for x-domain communication
            status     : true, // check the login status upon init?
            cookie     : true, // set sessions cookies to allow your server to access the session?
            xfbml      : true  // parse XFBML tags on this page?
        });

        // Additional initialization code such as adding Event Listeners goes here

        function handle_login_response(response) {
            if (response.status === 'connected') {
                // the user is logged in and has authenticated your
                // app, and response.authResponse supplies
                // the user's ID, a valid access token, a signed
                // request, and the time the access token
                // and signed request each expire
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;
                window.fb_logged_in_state = "connected";
            } else if (response.status === 'not_authorized') {
                // the user is logged in to Facebook,
                // but has not authenticated your app
                // TODO: popup authorization dialog
                window.fb_logged_in_state = "not_authorized";
            }
            else {
                // the user isn't logged in to Facebook.
                window.fb_logged_in_state = "not_logged_in";
            }
        }

        // listen to see if the user is known/logged in
        FB.getLoginStatus(function(response) {
            handle_login_response(response)
        });

        fb_login = function login() {
            alert("logging in ha")
            //try {}
            FB.login(function(response) {
                alert("handle login response")
                handle_login_response(response);
            }, {scope:'publish_stream'});
        }

        function send_messages(selected_ids) {

            FB.api('/me/feed', 'post',
            {name:"Facebookin All Day", caption:"But yeah true",
                description:"describing it all for you" ,
                redirect_uri: 'http://jamkazamdev.local:3000/',
                link: 'https://developers.facebook.com/docs/reference/dialogs/',
                picture: 'http://fbrell.com/f8.jpg',
                message: "oh right you have to make a message @" + selected_ids[0]},

                    function(response) {
                        if (!response || response.error) {
                            console.log("error in sending: %o", response)
                            alert('Error occured');
                        }
                        else {
                            alert('Post ID: ' + response.id);
                        }
                    })

        }

        function show_feed_dialog() {
            var obj = {
                method: 'feed',
                redirect_uri: 'http://jamkazamdev.local:3000/',
                link: 'https://developers.facebook.com/docs/reference/dialogs/',
                picture: 'http://fbrell.com/f8.jpg',
                name: 'Facebook Dialogs',
                caption: 'Reference Documentation',
                description: 'Using Dialogs to interact with users.'
            };

            function callback(response) {
                console.log("feedback dialog closed: " + response['post_id'])
            }

            FB.ui(obj, callback);
        }

        function show_request_dialog() {
            function sendRequestToRecipients() {
                var user_ids = [100005124960838]
                FB.ui({method: 'apprequests',
                    message: 'My Great Request',
                    to: user_ids
                }, function(response) {
                    console.log("request dialog response: %o", response)
                });
            }

            function sendRequestViaMultiFriendSelector() {
                FB.ui({method: 'apprequests',
                    message: 'My Great Request'
                }, function(response) {
                    console.log("request dialog response: %o", response)
                });
            }

            sendRequestViaMultiFriendSelector()
        }

        function show_dialog() {
            alert("requesting /me data")
            FB.api('/me', function(response) {

                // TODO: check for error

                $("#username").html("<img src='https://graph.facebook.com/" + response.id + "/picture'/><div>" + response.name + "</div>");

                $("#jfmfs-container").jfmfs({
                    max_selected: 15,
                    max_selected_message: "{0} of {1} selected",
                    friend_fields: "id,name,last_name",
                    pre_selected_friends: [1014025367],
                    exclude_friends: [1211122344, 610526078],
                    sorter: function(a, b) {
                        var x = a.last_name.toLowerCase();
                        var y = b.last_name.toLowerCase();
                        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
                    }
                });
                $("#jfmfs-container").bind("jfmfs.friendload.finished", function() {
                    console.log("finished loading!");
                    $('#jfmfs-container').show()
                });
                $("#jfmfs-container").bind("jfmfs.selection.changed", function(e, data) {
                    console.log("changed", data);
                });
            });
        }

        function get_selected_friends() {
            var friendSelector = $("#jfmfs-container").data('jfmfs');
            return friendSelector.getSelectedIds();
        }

        $("#invite_friends_via_facebook").click(function(e) {
            e.stopPropagation()

            $('#facebook-invitations').show()

            var fb_state = window.fb_logged_in_state

            if (fb_state == "connected") {
                show_dialog()
                //show_feed_dialog()
                //show_request_dialog()
            }
            else if (fb_state == "not_authorized") {
                fb_login()
            }
            else {
                fb_login()
            }
        })

        $("#send-friends").click(function(e) {
            e.stopPropagation()

            var selected_ids = get_selected_friends()

            // check if empty
            if (!selected_ids || selected_ids.length == 0) {
                alert("no friends selected.")
                return;
            }

            send_messages(selected_ids)

            $('#facebook-invitations').hide()
        })

        $("#cancel-friends").click(function(e) {
            e.stopPropagation()

            $('#facebook-invitations').hide()
        })
    };


    // Load the SDK's source Asynchronously
    // Note that the debug version is being actively developed and might
    // contain some type checks that are overly strict.
    // Please report such bugs using the bugs tool.
    (function(d, debug) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
        ref.parentNode.insertBefore(js, ref);
    }(document, /*debug*/ true));
</script>
</div>
</div>
