//
// Facebook Friends Map 1.0
//
// Florian Gilles
//
google.setOnLoadCallback(initializeServices);

var map; // Google Map

var max_friends_allowed = 1500;
var friends_per_request = 20;

// Initialize Google Maps and Facebook
function initializeServices() {
    addDebug("Initialize Services");

    // Register Event Handler
    Event.observe('facebookfriendsmap-connect-button',    'click', facebookConnect);
    Event.observe('facebookfriendsmap-disconnect-button', 'click', facebookDisconnect);      
        
    if (GBrowserIsCompatible()) {      
        map = new GMap2($('facebookfriendsmap-canvas'));
        map.setCenter(new GLatLng(32.879587,13.183594), 2); // Tripoli, Libya
        map.enableScrollWheelZoom();
        map.addMapType(G_PHYSICAL_MAP); 
        map.setMapType(G_PHYSICAL_MAP);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());    

        // Initialize Facebook Connects
        //FB.init("a5a1988d60f81e58c3cfeea470f9eb6d", "../../fileadmin/utilities/xd_receiver.htm", {"ifUserConnected":onUserConnected, "ifUserNotConnected":onUserNotConnected});

		alert('Currently not available');
		
    } else {
        addDebug('Browser not compatible');     
        alert("Failed: Browser not compatible");
    }
}

// Create a marker on the map
function createMarker(uid, name, img, city, lat, lng) { 
    var m = new GMarker(new GLatLng(lat, lng));   
    var s = '<div><div style=\'float:left;margin-right:10px\'><a href=\'http://www.facebook.com/profile.php?id='+uid+'\' target=\'_blank\'><img src=\''+img+'\'></a></div>';
    s += '<a href=\'http://www.facebook.com/profile.php?id='+uid+'\' target=\'_blank\'><b>'+name+'</b></a><br>'+city;
    s += '</div><div style=\'clear:left\'></div>';
    GEvent.addListener(m, "click", function() { m.openInfoWindowHtml(s); });
    map.addOverlay(m);     
}    

// Called when User wants to connect to Facebook
function facebookConnect() {
    FB_RequireFeatures(["Connect"], function() { FB.Connect.requireSession(); }); 
}

// Called when User wants to disconnect
function facebookDisconnect() {
    FB.Connect.logout(function() { addDebug("User disconnected"); });
    map.clearOverlays(); 
}

// Callback FB.init: User connected
function onUserConnected(uid) {
    $('facebookfriendsmap-connect').hide();
    $('facebookfriendsmap-disconnect').show();
    $('facebookfriendsmap-canvas').show();
    $('facebookfriendsmap-debugtoogle').hide();
    $('facebookfriendsmap-debug').hide();
    addDebug("User is now logged into Facebook and also this app ("+uid+")");
    parseFriends();
} 

// Callback FB.init: User not connected
function onUserNotConnected() { 
    $('facebookfriendsmap-connect').show();
    $('facebookfriendsmap-disconnect').hide(); 
    $('facebookfriendsmap-canvas').show();
    $('facebookfriendsmap-debugtoogle').hide();
    $('facebookfriendsmap-debug').hide();
    FB.ensureInit(function() {
        FB.Connect.get_status().waitUntilReady(function(status) {
            if (status == FB.ConnectState.userNotLoggedIn) {
                addDebug("User is not logged into Facebook");
            }
            if (status == FB.ConnectState.appNotAuthorized) {
                addDebug("User is logged into Facebook but this app is not authorized");
            }
        });
    });
}

// Debug
function addDebug(text) {
    var t = new Date();
    var h = t.getHours();
    var m = (t.getMinutes() < 10) ? ('0'+t.getMinutes()) : t.getMinutes();
    var s = (t.getSeconds() < 10) ? ('0'+t.getSeconds()) : t.getSeconds();
    $('facebookfriendsmap-debug').innerHTML += h+':'+m+':'+s+' - '+text+'<br>';
}

// Toogle Debug
function toogleDebug() {
    if ($('facebookfriendsmap-debug').visible()) {
        $('facebookfriendsmap-debug').hide();
    } else {
       $('facebookfriendsmap-debug').show();
    }
}

// Parse friends and display on the map
function parseFriends() {

    addDebug("Start parsing friends");
    map.clearOverlays(); 
    $('facebookfriendsmap-loading').show();  
            
    FB_RequireFeatures(["Api"], function() {

        // Require user to login 
        FB.Facebook.apiClient.requireLogin(function(exception) {
                    
              
        //alert("Current user id is " + FB.Facebook.apiClient.get_session().uid);
    
            // Get friend list
            FB.Facebook.apiClient.friends_get(new Array(), function(friends, exception) {
                        
                // Get additional information of friend list
                FB.Facebook.apiClient.users_getInfo(friends, ['uid','name','pic_small','hometown_location','current_location'], function(friendsinfo) {
                    
					
                    
                    $('facebookfriendsmap-total').innerHTML = friends.length;
                    addDebug(friends.length+" friends found");
                    
                    var postbody_starts_with = 'type=facebook';
                    var postbody = postbody_starts_with;
                    var friends_appended = 0; // 0...friends_per_request  
                    var friends_with_locations = 0;
                    var requests_sent = 0;
                    var responses_received = 0;
                    var response_errors = 0;                    
                                        
                    // Parse friends
                    for (var i = 0; i < friends.length; i++) {                     

                        if (friendsinfo[i].hometown_location && friends_with_locations < max_friends_allowed) {
                        
                            $('facebookfriendsmap-location').innerHTML = ++friends_with_locations;
                        
                            // Append POST body
                            postbody += '&arg'+friends_appended+'='+i; // friendsinfo id
                            postbody += '&city'+friends_appended+'='+encodeURI(friendsinfo[i].hometown_location.city);
                            postbody += '&state'+friends_appended+'='+encodeURI(friendsinfo[i].hometown_location.state);
                            postbody += '&country'+friends_appended+'='+encodeURI(friendsinfo[i].hometown_location.country);
                            friends_appended++;
                        }
                        
                        // Submit request
                        if (friends_appended == friends_per_request || i == friends.length - 1) {
                          
                            addDebug("Submit request with "+friends_appended+" friends");
                            
                            new Ajax.Request('/fileadmin/utilities/geocoding.php', { 
                                method: 'post',
                                postBody: postbody,
                                asynchronous: true,
                                onComplete: function(d) { 
                                                                        
                                    var responses = d.responseXML.getElementsByTagName('response');
                                    
                                    for (var ii = 0; ii < responses.length; ii++) {                                                                                 
                                        if (responses[ii].getAttribute("status") == "200") {                                                                                   
                                            var arg = responses[ii].getAttribute("arg");
                                            var lat = responses[ii].getAttribute("lat");
                                            var lng = responses[ii].getAttribute("lng");                                          
                                            createMarker(friendsinfo[arg].uid, friendsinfo[arg].name, friendsinfo[arg].pic_small, friendsinfo[arg].hometown_location.city, lat, lng);
                                            $('facebookfriendsmap-success').innerHTML = parseInt($('facebookfriendsmap-success').innerHTML) + 1;
                                        } else {
                                            response_errors++;
                                        }
                                    }
                                    
                                    addDebug("Response received with "+responses.length+" friends");

                                    if (++responses_received == requests_sent) {
                                        $('facebookfriendsmap-loading').hide(); 
                                        addDebug("Finished, "+requests_sent+" requests sent ("+response_errors+" errors)");
                                    }
                                }
                            });
                            
                            requests_sent++;
                                
                            // Reset
                            postbody = postbody_starts_with;
                            friends_appended = 0;
                        }                                           
                    }
                });                                
            });
        });
    });
}

 



