var user = Array();
var selected_friends = Array();
var max_friends=10; // Limit number of friends to publish

//*************		INIT Facebook JS framework
(function() {
	var e = document.createElement('script');
	e.type = 'text/javascript';
	e.src = document.location.protocol + '//connect.facebook.net/da_DK/all.js';
	e.async = true;
	document.getElementById('fb-root').appendChild(e);
}());

//**************	Login / Logout CTRL
window.fbAsyncInit = function() {

	FB.init({appId: '123715657668080', status: true, cookie: true, xfbml: true});

	FB.Event.subscribe('auth.login', function(response) {
		fb_getLoginUser();
		$("#addSocial_friends").fadeIn();
		fb_getFriends();
	});

    FB.getLoginStatus(function(response) {
    	if (response.session) {
			fb_getLoginUser();
			$("#addSocial_friends").fadeIn();
    		fb_getFriends();
        } else {
			$("#addSocial_friends").hide();
			
			}
    });		

	FB.Event.subscribe('auth.sessionChange', function(response) {
	   if (response.session) {
			fb_getLoginUser();
		} else {
			$("#addSocial_friends").hide();
		}
	});
}



//**************	FETCH USER
function fb_getLoginUser() {
    FB.api('/me', function(response) {	
		var query = FB.Data.query('select name, pic_square, email, uid from user where uid={0}', response.id);
		query.wait(function(rows) {
			user.unshift(rows[0]); // Can be accessed by user[0].name,email,pic_square
		});
	 });
}



//**************	FETCH FRIENDS
function fb_getFriends() {
    FB.api('/me', function(response) {	
	var query = FB.Data.query('SELECT name,pic_square,sex,uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0})', response.id);
	query.wait(function(user_friends) {
		$.each(user_friends, function(i,imgsrc){
           		if (imgsrc.pic_square) {
           		$("<img/>").attr({
           		"src": imgsrc.pic_square,
           		"data-name": imgsrc.name,
           		"data-sex": imgsrc.sex,		           		
           		"data-uid": imgsrc.uid,
           	    "title" : imgsrc.name,
           	    "data-filtername": imgsrc.name.toLowerCase()
           		}).appendTo("#addSocial_friends_pictures");}
		  	});
		});
	});
}

//**************	STREAM CTRL
// PUBLISH TO WALL - ACCEPT MESSAGE
function userStreamPublish(message) {
	var body = message; // WALL POST GOES HERE
	FB.api('/me/feed', 'post', { message: body }, function(response) {
        if (!response || response.error) {
            //ERROR CTRL
        }
	});
}
	 	
// PUBLISH TO FRIEND WALL - ACCEPT FRIEND UID ARRAY+MESSAGE
function friendStreamPublish(message) {
    var body = message; // FRIEND PUBLISH TXT GOES HERE
    selected_friends = [];
    $("#addSocial_friends_selected img").each(function() {
    	selected_friends.push($(this).attr("data-uid"));
    });
    for (f=0; f < selected_friends.length; f++) {
        FB.api('/'+selected_friends[f]+'/feed', 'post', { message: body }, function(response) {
            if (!response || response.error) {
            	//ERROR CTRL
            }
		});
	}
}

