var facebook_birthday = {
	get_birthdays: function(num, callback){
		
		// remove the old birthday cookie 
		document.cookie = "birthdays=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
		
	    // only do this if we know they are in facebook
		//if(_facebook_logged_in){
			var birthdays = new Array();
			
			// ensureInit runs 2 times on some pages (pages with facebook iframes) 
			run_once = false;
			FB.ensureInit(function() {
				FB.Facebook.get_sessionState().waitUntilReady(function(session) {
					if(!run_once){
						birthdays = [];
						reload = false;
						found = false;
						if(/birthday_data=([^;]+)/.test(document.cookie)){
							found = true;

							var api = FB.Facebook.apiClient;
							uid = api.get_session().uid;
				
					        birthday_data = eval(unescape(/birthday_data=(.*?)(?:;|$)/.exec(document.cookie)[1]));
					        
							if(birthday_data['user_'+uid]){
								birthdays = birthday_data['user_'+uid];
							}
							if(birthday_data['retrieved']){
								loaded_time = birthday_data['retrieved'];
								// if not today's date, reload
								loaded = new Date(loaded_time);
								now = new Date();
								if ((loaded.getMonth() != now.getMonth()) || (loaded.getDate() != now.getDate())){
									reload = true;
								}
							}
						}

						if (found && !reload) {
							// if for some reason we have a blank cookie array lets make sure they dont have any
							// friends and just get all the users again 
							if(birthdays.length == 0){
								facebook_birthday.init_birthdays(num, callback);
							}
							else{
								callback(birthdays.splice(0,num));
							}
						}else{
							// this will put 12 of the birthdays into cookies
							facebook_birthday.init_birthdays(num, callback);
						}
						run_once = true;
					}
				});
			});
	},
	// get the users friends form facebook
	get_all_friends: function(callback){
	    //var api = new FB.ApiClient(_facebook_api, _xd_receiver, null);
	    
		FB_RequireFeatures(["Api"], function(){
			FB.Facebook.get_sessionState().waitUntilReady(function() { 
				var api = FB.Facebook.apiClient;
				var myQuery='SELECT name, birthday, pic_square, uid FROM user  WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1='+api.get_session().uid+')';
				api.requireLogin(function(exception){
				    api.fql_query(myQuery,callback);
				});
			 });
		});
	},
	// get the birthdays form facebook
	init_birthdays: function(num, callback){
	    //var api = new FB.ApiClient(_facebook_api, _xd_receiver, null);
	    
		once = RunOnce(function(){
			//FB.Facebook.get_sessionState().waitUntilReady 
			JJFacebook.facebookReady(function() {
				var api = FB.Facebook.apiClient;
				var myQuery='SELECT name, birthday, pic_square, uid FROM user  WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1='+api.get_session().uid+')';
				api.requireLogin(function(exception){
				    api.fql_query(myQuery,function(users){
				        facebook_birthday.getFQLResponse(users, num, callback);
				    });
				});
			 });
		});
		FB_RequireFeatures(["Api"], once);
	},
	
	getFQLResponse: function(users, num, callback){

	    var birthdays = new Array();
	    var now = new Date();
		// set the date to only Month Day Year
		now.setTime(Date.parse((now.getMonth()+1)+'/'+now.getDate()+'/'+now.getFullYear()));
		
	    for(i= 0; i<users.length; i++){    
	        if(users[i].birthday){
	            // when is your birthday *this* year
	            users[i].birthday = users[i].birthday.replace(/,\s\d{4}/gi, "")
	            users[i].birthday = Date.parse(users[i].birthday+', '+now.getFullYear())
	            birthdays.push(users[i]);
	        }
	    }

	    // sort the users by there birthday
	    birthdays.sort(function (thisObject,thatObject) {	
	        if (thisObject.birthday > thatObject.birthday)
	            return 1;
	        else if (thisObject.birthday < thatObject.birthday)
	            return -1;
	        return 0;
	    });

		var pre = 0;
	    // find the index last birthday before now
	    now = now.getTime();
		for(i= 0; i<birthdays.length; i++) {  
	        if(now > birthdays[i].birthday)
	            pre = i+1
	    }
	    // add the past birthdays to the end of the list
		
	    birthdays = birthdays.concat(birthdays.splice(0,pre))

	    // serialize the data for the cookie
	    ret = new Array();
	    for(i= 0; i<12; i++){   
			if(birthdays[i]){
	        	ret.push(escape("{uid:'"+birthdays[i].uid+"', name:'"+birthdays[i].name.replace(/'/g, "\\'")+"', pic_square: '"+birthdays[i].pic_square+"', birthday: '"+birthdays[i].birthday+"'}"));
			}
	    }

	    // set the cookie for cache and run the callback
		expires = new Date();
		//expires.setDate(expires.getDate() + 1);
		// expire the cookie at midnight.
		expires.setTime(Date.parse((expires.getMonth()+1)+'/'+expires.getDate()+'/'+expires.getFullYear()));
		expires.setDate(expires.getDate() + 1);
		now = new Date();
		
		var api = FB.Facebook.apiClient;
		uid = api.get_session().uid;
	    document.cookie = "birthday_data=({retrieved:"+now.getTime()+",user_"+uid+":["+ret.join(',')+']'+'}); expires=' + expires.toGMTString() + '; path=/';
		//document.cookie = 'birthdays=['+ret.join(',')+']';
	    callback(birthdays.splice(0,num));
	},
	parse_date: function(epoch){
		
		var now = new Date();
		now.setTime(Date.parse((now.getMonth()+1)+'/'+now.getDate()+'/'+now.getFullYear()));
		
		var d = new Date(epoch);
		var curr_date = d.getDate();
		var curr_month = d.getMonth();
		var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
		
		if((curr_month == now.getMonth()) && (curr_date == now.getDate())){
			return "Today"
		}
		if((curr_month == now.getMonth()) && (curr_date == now.getDate()+1)){
			return "Tomorrow"
		}		
	
		return m_names[curr_month]+ " " + curr_date;
	},
	hide_birthdays: function(jquery_obj){
		jquery_obj.hide('slow');
		document.cookie = 'hide_birthday=1; path=/';		
	},
	show_birthdays: function(jquery_obj){
		if(!/hide_birthday=([^;]+)/.test(document.cookie)){
			// wait a few seconds then show the birthdays s l o w l y 
			window.setTimeout(function(){
				jquery_obj.show('slow');
			}, 1000)		
		}
	},
	can_show_birthday: function(){
		return !/hide_birthday=([^;]+)/.test(document.cookie);
	},
	load_birthdays: function(number, placeholder, container){
		
		// make sure we have something to do with the birthdays.
		if(!placeholder || !container || !placeholder.html() || !container.html() ){
			return;
		}
		
		facebook_birthday.get_birthdays(number, function(users){
			facebook_birthday.render_birthdays(users, placeholder, container);
		});	
	},
	render_birthdays: function(users, placeholder, container) {
		content = placeholder.html();	
		for(i=0; i<users.length; i++){
			// replace the placeholders in the content
			// if we dont have an image for the user show this. 
			if(!users[i].pic_square) {
				users[i].pic_square = '/images/facebook_blank.gif';
			}
				
			div_content = content.replace(/rel=["']#img["']/,"src='" + users[i].pic_square + "'");
			div_content = div_content.replace('#name',users[i].name);			
			div_content = div_content.replace('#uid',users[i].uid);

			if (users[i].birthday) {
				dDate = new Date(parseInt(users[i].birthday));
				bd = facebook_birthday.parse_date(dDate);
				div_content = div_content.replace('#birthday',bd);
			} else {
				div_content = div_content.replace('#birthday','');
			}

			// add the new element
			container.append(div_content);
		}
	}
};
