var fbapi = null;
var tripData = {};
var Tripeedo = function() {};
var firstName = '';
var friendsWithApp = [];
var friendsInCity = []; // to be populated by list of ids

FB_RequireFeatures(["XFBML", "Api"], function(){ 
FB.init("46925c2836ba954b20f8fb3e8f27ccb2", "/xd_receiver.htm"); // prod
//FB.init("9d2f6bd36983293640f5641455e4df70", "/xd_receiver.htm"); // dev
	
fbapi = FB.Facebook.apiClient;
	

//<YOUR CODE HERE>	

// FB.Connect.requireSession(function(exception){
    
//})
//FB.ensureInit(function() { 
//  FB.Connect.ifUserConnected(function() { 
	
    //FB.LoggedIn(); 
//});
//});
});


Tripeedo.friendsWithApp = function() {
  fbapi.friends_getAppUsers( function(data) { friendsWithApp = data; });
}

Tripeedo.shareTripOnFacebook = function() {
var user_message_prompt = "Share this summary or customize to your heart's content";
var user_message = {"value":tripData.message};
//var template_data = {"actor":"nick","location":"london","from":"may 17","to":"may 27"};
var body_general = "";

FB.Connect.showFeedDialog(85098975495, tripData, [], body_general, null, FB.RequireConnect.doNotRequire, Tripeedo.afterFacebookShare, user_message_prompt, user_message);

}



Tripeedo.assignFirstName = function(result, exception) {
	firstName = (" "+result[0]['first_name']).toLowerCase();
	jQuery("#firstName").html("hi"+firstName+"!");
}

Tripeedo.getFirstName = function() {
	fbapi.users_getInfo(fbapi.get_session().uid,'first_name',Tripeedo.assignFirstName);
}

Tripeedo.afterFacebookShare = function() {
    
};
//Tripeedo.afterConnect = function(data) {
//    alert("afterconnect")
//    var fbapi = FB.Facebook.apiClient; 
//    var uid = fbapi.users_getLoggedInUser(function(result, exception) {});
//    alert(uid)
//};

Tripeedo.showFriendsInDestination = function() {
	
	// reset this to empty
	friendsInCity=[];
	
    var uid = fbapi.get_session().uid
   
    location_label = tripData.destination.label
    city = tripData.destination.city
    state = tripData.destination.stateprovince
    country = tripData.destination.country    

    qry = "select uid, first_name, last_name, current_location, pic_square_with_logo, profile_url from user where uid in (select uid2 from friend where uid1=" + uid + ")";
    
    qry += " and (('" + location_label + "' in affiliations.name) OR (";
    // if country is US, then lookup by state, otherwise by country
    if (country == 'United States') {
	  qry += "current_location.city = '" + city + "' and current_location.state='" + state + "'";
    } else {
      qry += "current_location.city = '" + city + "' and current_location.country='" + country + "'";
    }
    // can't figure out syntax to order by last_name then first_name
    qry += ")) ORDER BY last_name ASC";

	//alert(qry);
	fbapi.fql_query(qry, function(result, ex) {  
		if(result.length) {
		    
			var data = "<table cellpadding='0' align='left' style='height:"+ result.length * 31 + "px' cellspacing='0' border='0'>";  
	        //var data = '<fb:serverfbml><fb:user-table cols="3">';
               
	        for (i=0;i<result.length;i++)  
	        {  
	            friendsInCity[i] = result[i].uid;
			  		data += "<tr><td width='25' height='25' style='padding:3px 10px 3px 0px' valign='middle' align='center'><a target='new' href='"+ result[i].profile_url +"'><img width='25' height='25' src='"+ result[i].pic_square_with_logo +"' border='0'/></a></td><td width='150' height='33' valign='middle' align='left'><a target='new' href='"+ result[i].profile_url +"'>"+ result[i].first_name + " " + result[i].last_name+"</a></td></tr>";  
			  		// data += "<tr><td><input type='checkbox' value='"+result[i].uid+"' name='friends[]' id = 'friend"+result[i].uid+"' /></td><td>"+ result[i].first_name + " " + result[i].last_name+"</td></tr>";  
	           		// data += "<tr><td>"+ result[i].first_name + " " + result[i].last_name+"</td></tr>";  
               		// data += '<fb:user-item uid="' + result[i].uid + '"></fb:user-item>';
	        }  
	        data +="</table>";
	      	// data += '</fb:user-table></fb:serverfbml>'
	      	// jQuery('#destination_friends').css({"overflow-y":"scroll","height":"200px","width":"180px","border":"1px solid #ccc"});  
			jQuery('#destination_friends').html(data);  
			jQuery("div.scroll-pane").jScrollPane({scrollbarWidth:17});
		}
		else {
			var data = "Aww, looks like you don't have any friends around there.<br/><br/>That's a little sad.";
			jQuery('#destination_friends').html(data);
		}
	});

	
	//alert("done");
};

Tripeedo.shareTripOnTripeedo = function() {
    //alert('works');
    // ajax call to tripeedo sharing trip
    jQuery.get( '/trips/share', {"purpose":tripData.purpose,"destination":tripData.destination.label,"arrival_date":tripData.arrival_date, "departure_date":tripData.departure_date}, function (data) {eval(data);});
    
};

Tripeedo.ifUserConnected = function(fxn1, fxn2) {
    FB.ensureInit(function() { 
      FB.Connect.ifUserConnected(fxn1, fxn2);
  });
};

Tripeedo.shareTrip = function() {
    if (jQuery('#purpose').attr('value') != default_purpose) {
    	tripData.purpose = jQuery('#purpose').attr('value');    
	}
	
    if (tripData.purpose) {
      tripData.message = tripData.message + ' (' + tripData.purpose + ')';
    }
    if (jQuery('#notifyFriendsCheckbox').attr('checked')) {
        Tripeedo.notifyFriendsOfTrip();
    }
       
    jQuery(document).trigger('close.facebox');
       
    Tripeedo.shareTripOnTripeedo();    
    
    Tripeedo.shareTripOnFacebook();
};
// attach behavior to rel facebox
//jQuery(document).ready(function($) {
//  $('a[rel*=facebox]').facebox() 
//});

Tripeedo.inviteFriends = function() {
    Tripeedo.ifUserConnected(Tripeedo.showInviteFriends, function() {
        jQuery.facebox("You need to connect with Facebook before you can invite friends. Click on the 'Connect' button!");
    });
}

Tripeedo.showInviteFriends = function() {
    var content = '<fb:request-form \
                action="http://www.tripeedo.com"\
                method="POST"\
                invite="true"\
                type="Tripeedo"\
                content="Connect with Tripeedo to share travel plans with your friends.  All the cool kids are doing it. <fb:req-choice url=\'http://www.facebook.com/add.php?api_key=46925c2836ba954b20f8fb3e8f27ccb2&v=1.0\' label=\'Connect to Tripeedo - share travel plans\' />">\
                <fb:multi-friend-selector\
                showborder="false"\
                exclude_ids="' + friendsWithApp + '"\
                rows="3"\
                bypass="cancel"\
                actiontext="Go on - invite your friends to use Tripeedo too.">\
                </fb:multi-friend-selector>\
                        </fb:request-form>';
                
    var popup = new FB.UI.FBMLPopupDialog('Invite friends to use Tripeedo', content);
    popup.setContentWidth(700);
    popup.set_placement(FB.UI.PopupPlacement.topCenter);
    popup.show();
    
};

jQuery("body").ready(function(){
	FB.XFBML.Host.parseDomTree();
});

Tripeedo.refreshFacebookTags = function() {
    FB.XFBML.Host.parseDomTree();
};

Tripeedo.notifyFriendsOfTrip = function() {
  
  var notification_text = tripData.message;
  fbapi.notifications_send(friendsInCity, notification_text, Tripeedo.afterNotifyFriends);  
};

Tripeedo.afterNotifyFriends = function() {
    
};
Tripeedo.tripSaved = function() {
    // nothing
};
Tripeedo.tripNotSaved = function() {
    // nothing
};

Tripeedo.poll_for_friends_trips = function(element_id) {
  setTimeout(function() {
    new Ajax.Request('/trips/friends_trips', {
      method: 'get',
      onComplete: function(transport) {
              if (transport.status == 304) {
                Tripeedo.poll_for_friends_trips(element_id);
              } else if (transport.status == 200) {
                jQuery('#' + element_id).html(transport.responseText);
              } else {
                jQuery('#' + element_id).html('error');
              }
            }
    }) },
    1000
  );
};
Tripeedo.refresh_my_trips = function() {
    new Ajax.Request('/trips/my_trips', {
      method: 'get',
      onSuccess: function(transport) {             
                jQuery('#my_trips').html(transport.responseText);              
            }
    })
};
Tripeedo.deleteTrip = function(id) {
    new Ajax.Request('/trips/delete/' + id, {
      method: 'get',
      onSuccess: Tripeedo.refresh_my_trips
    })
};
var default_purpose = "to meet the president?  for a wedding?";
var share_html = "<div style='padding:20px'>\
<center><span style='font-size:18px'><b>share this trip</b></span></center>\
<br/>\
<span style='font-size:14px'>\
save this trip on tripeedo so your friends can see where you're going.  we just need one more detail...</span>\
<br/><br/>\
<span style='font-size:14px;font-weight:bold'>business or pleasure?</span> <span style='font-size:14px;font-weight:normal'>(as in, why are you going?)</span><br/>\
<form onsubmit='Tripeedo.shareTrip();return false;'>\
<input type='text' onfocus='this.value=\"\";this.style.color=\"#000\"' value='" + default_purpose + "' class='fb_status_text' id='purpose'></input><br/>\
<br/>\
<input type='checkbox' checked id='notifyFriendsCheckbox'/> Notify my friends at my destination about this trip\
</form>\
<br/><br/>\
<div id='share_button' class='fb_status_text' onclick='Tripeedo.shareTrip();'>save</div><br/>\
</div>";