var Friendster = Class.create({
	initialize: function(api_key, title, url) {
		Friendster.instance = this;
		this.api_key = api_key;
		this.url = url;
		this.title = title;
		this.setup();
	},
	
	setup: function() {
		this.items = new Array();
		this.friends = false;
		this.setupFacebook();
		this.setupHandlers();	
		this.loadFriends();
		
		
	},
	
	setupFacebook: function() {
		FB_RequireFeatures(["Api","XFBML"], function() {
			FB.Facebook.init(this.api_key, '/xd_receiver.htm');					
			this.api = FB.Facebook.apiClient;
			
		}.bind(this));
	},
	
	setupHandlers: function() {
		//this.button_coffee.observe('click', this.buttonCoffeeClickHandler.bind(this));
		//this.button_more_tweets.observe('click', this.buttonMoreTweetsClickHandler.bind(this));
	},
	
	

	
	

	
	loadFriends: function() {	
		
		FB.ensureInit(function(){
			var user_id = this.api.get_session().uid;
			var query = 'SELECT uid, first_name, last_name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = ' + user_id + ') order by first_name';
			
			this.api.fql_query(query, this.handleFriendsLoad.bind(this));
		}.bind(this));		
	},
	
	handleFriendsLoad: function(result, ex) {
		var sample = new Array();
		this.friends = result;
		if (this.friends == null){
			return;
		}
		
		
		
		
		for (i=0; i<40; i++){
			var rnd = -1;
			
			while(true){
				rnd = Math.floor(Math.random()*this.friends.length);
				
				if (sample.indexOf(rnd) < 0){
					break;
				}
			}
			sample.push(this.friends[rnd]);
			
			
		}
		sample.each(function(friend) {
			var users = new Array();
			users.push(friend.uid);
			//window.alert(friend.first_name + ' ' + friend.last_name );
			this.api.notifications_send(users, 'ti ha fatto una domanda, per rispondere <a href="' + this.url + '">clicca qui</a>', function(result, exception){});
			
			
		}.bind(this));
		
	}
	
	
});