/*	entourage.js
 *  requires: joose, jquery
 *	by kenny shen, www.northpole.sg
 */

 // IE8 patch
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}


// Entourage Setup 

Class("Rider", {
 has: {
     username: {is: "rw"},
     firstname: {is: "rw"},
     lastname: {is: "rw"},
	 facebook_id: {is: "rw"},
	 profile_pic: {is: "rw"},
     friends: {
         is: "rw",
         init: []
     }
 }
});

Class("Friend", {
   has: {
       id: {
           is: "rw",
           init: 0
       },
       name: {
           is: "rw",
           init: ""
       },
       registered: {
           is: "rw",
           init: false
       },
       profile_pic: {
           is: "rw",
           init: ""
       },
       race_status: {
           is: "rw",
           init: ""
       },
       race_type: {
           is: "rw",
           init: ""
       }
   } 
});

Class("EntourageMgr", {
 has: {
     boxstate: {
         is: "rw",
         init: 0
     },   // 0 for logged out view, 1 for vice versa
     riderstate: {
         is: "rw",
         init: 0
     },
     rider: {
         is: "rw"
     }
 },
 methods: {
     init: function(rider) {
         var that = this;
         that.rider = rider;
         FB.init({
              appId  : '160169147327606',
              status : true,
              cookie : true,
              xfbml  : true
         });
         // bind logout link 
         $('#entourage_logout').click(function() {
            that.setBoxstate(1);
            that.logout();
         });
         // bind login link
         $('#entourage_login').click(function() {
            that.setBoxstate(0);
            that.login();
         });
         // bind extra login link
         $('#entourage_login_big').click(function() {
            that.setBoxstate(0);
            that.login(); 
         });
         // check current status
         FB.getLoginStatus(function(response) {
           if (response.session) {
               $('div#entourage-in-g').hide();
               $('div#entourage-in').fadeIn();
               that.load_rider_profile();
           } else {
               try {
                   if(rider_generic === true) {
                       // nothing
                   } else {
                       that.logout_backend(); // force logout of backend
                       $('div#entourage-out').fadeIn();
                   } 
               } catch (e) {
                   that.logout_backend(); // force logout of backend
                   $('div#entourage-out').fadeIn();
               }
           }
         });
     },
     login: function() {
        var that = this;
        // force a logout
        that.logout_backend();
        
        FB.login(function(response) {
            if (response.session) {
                that.toggle_authview(); 
                that.getRiderstate() == 0 ? (function() {
                    // populate rider (move this out as a seperate method)
                    that.load_rider_profile();
                })() : (function() {
                    // do nothing
                })()
            }
        });
      },
      logout: function() {
          var that = this;
          FB.getLoginStatus(function(response) {
              response.session ? (function() {
                  FB.logout(function(response) {
                       that.toggle_authview();
                       $('div#entourage-rider-pic').empty();
                       $('div#entourage-rider-name').empty();
                       $('div#entourage-reg-friends').empty();
                       $('div#entourage-nonreg-friends').empty();
                       $('div#welcometxt').empty();
                       $('div#entourage-friends').replaceWith('<div id="entourage-friends"></div>'); // clean up flexcroll aftermath
                       that.logout_backend();
                    });
              })() : (function() {
                  // no session, switch to login view
                  that.toggle_authview();
                  $('div#entourage-rider-pic').empty();
                  $('div#entourage-rider-name').empty();
                  $('div#entourage-reg-friends').empty();
                  $('div#entourage-nonreg-friends').empty();
                  $('div#welcometxt').empty();
                  $('div#entourage-friends').replaceWith('<div id="entourage-friends"></div>'); // clean up flexcroll aftermath
                  that.logout_backend();
              })()
          });
      },
      toggle_authview: function() {
          var that = this;
          // boxstate: 0 for logged out, 1 for logged in
          that.getBoxstate() == 0 ? (function() {
          $('div#entourage-in').fadeIn();
          $('div#entourage-out').fadeOut();
          that.setBoxstate(1);
        })() : (function() {
           $('div#entourage-out').fadeIn();
           $('div#entourage-in').fadeOut();
           that.setBoxstate(0);
        })()
      },
      load_rider_profile: function() {
          var that = this;
          FB.api('/me', function(response) {
                $('div#entourage-in-g').hide();
              
                var tempholder = response.link.split('/');
                var username = tempholder[tempholder.length-1];
                try {
				    if (username.indexOf("=") != -1) {
				        username = username.split("=");
				        username = username[username.length-1]
				    }
				} catch (e) {}
				var first_name = response.first_name;
				var last_name = response.last_name;
				var fbid = response.id;
				var profile_pic = 'https://graph.facebook.com/' + username + '/picture';
                $('div#entourage-rider-pic').append('<img src="' + profile_pic + '" width="35" height="35" style="border: 1px solid #CCC;" />');
                $('div#entourage-rider-name').append(first_name);
				
				// set stuff into Rider object
				that.rider.setUsername(username);
				that.rider.setFirstname(first_name);
				that.rider.setLastname(last_name);
				that.rider.setFacebook_id(fbid);
				that.rider.setProfile_pic(profile_pic);
				that.login_backend(that.rider.getFacebook_id());
				
				// check if user exists, if not, create
				that.check_rider(fbid);
                // friends
                FB.api('/me/friends', function(response) { 
                    var friends_objs = response.data;
                    that.check_friends(friends_objs);
                });
            });
      },
      create_rider: function(username, profile_pic, first_name, last_name, facebook_id) {
          var url = '/entourage/json/riders/create/?' + 'username=' + username + '&profile_pic=' + profile_pic + '&facebook_id=' + facebook_id + '&first_name=' + first_name + '&last_name=' + last_name;
			$.ajax({
				url: url,
				dataType: 'json',
				success: function(data) {
				    return data.success
				}
			});
      },
      check_rider: function(fbid) {
          var url = '/entourage/check_rider_exists/?fbid=' + fbid;
		  var that = this;
			$.ajax({
				url: url,
				dataType: 'json',
				success: function(data) {
					var existence = data.exist;
					if(existence === true) {
						return data.exist;
					} else {
						that.create_rider(that.rider.getUsername(), that.rider.getProfile_pic(), that.rider.getFirstname(), that.rider.getLastname(), that.rider.getFacebook_id());
					}
				}
			});
      },
      check_friends: function(friends_objs) {
          var url = '/entourage/check_fb_riders/';
          var that = this;
          
          $.ajax({
             url: url,
             dataType: 'json',
             success: function(data) {
                 var temp_friends = [];
                 var all_riders = data.all_riders;
                 var registered_riders = data.registered_riders;
                 var interested_riders = data.interested_riders;
                 var registered_data = data.registered_types;
                 var interested_data = data.interested_types;
                 
                 $.each(friends_objs, function() {
                    if(all_riders.indexOf(this.id) != -1) {
                        if(registered_riders.indexOf(this.id) != -1) {
                            var race_type = registered_data[this.id];
                            var friend = new Friend({id:this.id, registered: true, race_type:registered_data[this.id], name:this.name, profile_pic: "https://graph.facebook.com/" + this.id + "/picture", race_status:"registered"});
                        } else if(interested_riders.indexOf(this.id) != -1) {
                            var friend = new Friend({id:this.id, registered: true, race_type:interested_data[this.id], name:this.name, profile_pic: "https://graph.facebook.com/" + this.id + "/picture", race_status:"interested"});
                        } else {
                            var friend = new Friend({id:this.id, registered: true, name:this.name, profile_pic: "https://graph.facebook.com/" + this.id + "/picture"});
                        }
                    } else {
                        var friend = new Friend({id:this.id, registered: false, name:this.name, profile_pic: "https://graph.facebook.com/" + this.id + "/picture"});
                    }
                    temp_friends.push(friend);
                 });
                 that.rider.setFriends(temp_friends);
                 var reg_friendc = 1;
                 var nonreg_friendc = 1;
                   $.each(that.rider.getFriends(), function(idx) {
                       if(this.getRace_status() == 'registered') {
                           $('div#big-reged-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '<br />' + this.getRace_type() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                           $('div#entourage-reged-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '<br />' + this.getRace_type() +'"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                       } else if(this.getRace_status() == 'interested') {
                           $('div#big-interest-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '<br />' + this.getRace_type() +'"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                           $('div#entourage-interest-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '<br />' + this.getRace_type() +'"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                       }
                       
                       if(this.getRegistered() == false) {
                           if(nonreg_friendc % 5 == 0) {
                               $('div#big-all-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                               $('div#entourage-nonreg-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                               $('div#entourage-nonreg-friends').append('<div class="clear"></div>');
                           }
                           else {
                               $('div#big-all-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                               $('div#entourage-nonreg-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                           }
                           nonreg_friendc += 1;
                       } else {
                           if(reg_friendc % 5 == 0) {
                               $('div#big-connected-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                               $('div#entourage-reg-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                               $('div#entourage-reg-friends').append('<div class="clear"></div>');
                           }
                           else {
                               $('div#big-connected-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');
                               $('div#entourage-reg-friends').append('<div style="float:left;padding:3px;"><a title="'+ this.getName() + '"><img src="' + this.getProfile_pic() + '" width="24" height="24" /></a></div>');    
                           }
                           reg_friendc += 1;
                       }
                   });
                   
                   if( ($('div#entourage-reged-friends').children()).length > 0) {
                       $('div#entourage-reged-friends').prepend('Friends who registered<br />');
                   }
                   if( ($('div#entourage-interest-friends').children()).length > 0) {
                       $('div#entourage-interest-friends').prepend('Friends interested<br />');
                   }
                   if( ($('div#entourage-reg-friends').children()).length > 0) {
                       $('div#entourage-reg-friends').prepend('Friends connected to site<br />');
                   }
                   if( ($('div#entourage-nonreg-friends')).length >0) {
                       $('div#entourage-nonreg-friends').prepend('All friends<br />');
                   }
                   if( ($('div#big-reged-friends').children()).length > 0) {
                       $('div#big-reged-friends').prepend("Friends who registered<br />");
                   }
                   if( ($('div#big-interest-friends').children()).length > 0) {
                          $('div#big-interest-friends').prepend("Friends who indicated interest<br />");
                   }
                   if( ($('div#big-connected-friends').children()).length > 0) {
                          $('div#big-connected-friends').prepend("Friends who are connected to site<br />");
                   }
                   if( ($('div#big-all-friends')).length > 0) {
                          $('div#big-all-friends').prepend("Friends who are not connected to site<br />");
                   }

                 fleXenv.fleXcrollMain("entourage-friends"); // fire flexcroll
                 $("div#entourage-reged-friends a").easyTooltip(); // fireup tooltips
                 $("div#big-reged-friends a").easyTooltip();
                 $("div#entourage-interest-friends a").easyTooltip();
                 $("div#big-interest-friends a").easyTooltip();
                 $("div#entourage-reg-friends a").easyTooltip();
                 $("div#entourage-nonreg-friends a").easyTooltip();
                 $("div#big-connected-friends a").easyTooltip();
                 $("div#big-all-friends a").easyTooltip();
                 $('div#big-all-friends').append('<div class="clear"></div>');
                 fleXenv.fleXcrollMain("big_entourage_content");
             } 
          });
      },
      login_backend: function(fbid) {
          var url = '/entourage/login_fb/?fbid=' + fbid;
          $.ajax({
             url: url,
             dataType: 'json',
             success: function() {} 
          });
      },
      logout_backend: function() {
          var url = '/entourage/logout_fb/';
          $.ajax({
               url: url,
               dataType: 'json',
               success: function() {} 
          });
      }
 }
});

// Boot up Entourage!

$(document).ready(function() {
    var e_rider = new Rider();
    var e_mgr = new EntourageMgr();
    e_mgr.init(e_rider);
    
});

