var FriendsSearchRoot="http://0.app.joost.com";
var FriendsAddRoot="http://1.app.joost.com";
var FriendsActiveRoot="http://2.app.joost.com";
var FriendFavoritesRoot="http://3.app.joost.com";
var FriendListRoot="http://4.app.joost.com";
var FriendPendingListRoot="http://5.app.joost.com";
var FriendRecentlyWatchedRoot="http://6.app.joost.com";

Friends = {
  theUser:undefined,
  service: "/api/friends/"
 };

// nItems: number of items to show in the list
Friends.setUser=function(u,count,start){
  this.theUser=u;
  this.refreshList(count,start);
},

Friends.message=function(text, where){
  document.getElementById(where).innerHTML = text;
};

Friends.refreshList=function(count,start,accept){
  var userJoostName = "";
  var newbe = 'NO';


  if (!this.theUser && window.User_Details){
    var userJoostName=window.User_Details.joostName;
  }
  else {
   userJoostName = this.theUser;
  }

  if (accept) {
	  var newbe = 'YES';
  }
  var url=(this.service+"get/"+userJoostName+"?type=FRIEND&status=ACTIVE&newbe="+newbe+"&start="+start+"&count="+count+"&json_function=Friends.handleGetResponse");
  if (window.FriendListRoot) {
    url=window.FriendListRoot+url;
  }
  jsonRequest(url);

};

Friends.refreshBigList=function(accept) {
	Friends.refreshList('','',accept);
}

Friends.handleGetResponse=function(obj) {
  if (obj.success) {
    Friends.displayResults(obj);
  } else {
    if (obj.resultCode==1001) {
      var el=document.getElementById("friendsListBrick");
      el.style.display="none";
    }
    Friends.message(obj.message,"friendsMsg");
  }
};

Friends.displayResults=function(obj) {
  var friendsList=document.getElementById("friendsList");
  var friendsBigList=document.getElementById("friendsBigList");
  var apiResults=obj.friends;
  var nApiResults=obj.friends.length;
  if(nApiResults==0){
    var msg=document.getElementById("friendsMsg");
    if (msg) {
      msg.innerHTML= "<p>User has no friends at the moment</p>";
    }
  } else {
	   var msg=document.getElementById("friendsMsg");
       if (msg) {
          msg.innerHTML = "";
      }
  }
  
  var outputList=[];

  for (var i=0;i<nApiResults;i++) {
    var joostName=obj.joostName==apiResults[i].target ? apiResults[i].source : apiResults[i].target;
    if (friendsList) {
        var avatar = getAvatar(apiResults[i], 'small');
    }
	if (friendsBigList) {
        var avatar = getAvatar(apiResults[i], 'large');
    }

    if (!joostName || joostName=="") { continue; }

    var status=apiResults[i].status;
	
    var fbid = 'undefined';
    if(apiResults[i].fbid) {
        fbid=apiResults[i].fbid;
    } else {
        fbid = 'undefined';
    }
    var youIndicator = "";
    if (window.User_Details) {
      if(window.User_Details.joostName == joostName) {
        youIndicator = '<br/><img src="/static/minilabel-you.png" class="minilabelYou" alt="You"/>';
      }
    }
    
    outputList.push({title: escapeHTML(apiResults[i].userName),
                     thumbnail:avatar,
                     link:'users/'+joostName+"/",
                     type:'user',
                     showProfile: apiResults[i].showProfile,
                     fbid: fbid,
                     friend: apiResults[i].friend,
                     description: friendFormat(joostName,obj.mood) + youIndicator
                    });
  }
  if (friendsList) {
    friendsList.innerHTML=renderThumbAndTextList(outputList);
    setTimeout(FBParseDom, 0);
  }
  if (friendsBigList && obj.newbe == 'YES' && obj.friends.length < 24) {

	var addCont = renderUserBrickInThumbMode(outputList,false);
    friendsBigList.innerHTML=addCont;
    setTimeout(FBParseDom, 0);
  }
};

Friends.handleResponse=function(obj) {
  if (!obj.success) {
    document.getElementById('blockTopErrorContainer').innerHTML=escapeHTML(obj.message);
    document.getElementById('blockTopError').style.display='block';
  }
  Friends.refreshList();
};
//########## Active friends ######################################################################

Friends.Active = {
  service: '/api/friends/getActiveFriends?json_function=Friends.Active.response'
};


Friends.Active.refreshList=function(){
  var url=Friends.Active.service;
  if (window.FriendActiveRoot) {
    url=window.FriendActiveRoot+url;
  }
  Friends.Active.cleanList();
  jsonRequest(url);
};

Friends.Active.response=function(obj) {
  if (obj.success) {
    Friends.Active.displayResults(obj);
  } else {
    Friends.Active.message(obj.message);
  }
};

Friends.Active.cleanList=function(obj) {
  document.getElementById("friendsActiveList").innerHTML="";
};

Friends.Active.message=function(text){
  document.getElementById("friendsActiveList").innerHTML = text;
};

Friends.Active.displayResults=function(obj) {
  var apiResults=obj.friends;
  var nApiResults=obj.friends.length;
  if(nApiResults==0){
    if(window.Friends){
      document.getElementById("friendsActiveMsg").innerHTML="<p>"+Friends.theUser+" has no active friends at the moment</p>";
    }else{
      document.getElementById("friendsActiveMsg").innerHTML="<p>No friends at the moment</p>";      
    }
  }

  var outputList=[];

  for (var i=0;i<nApiResults;i++) {
    var joostName=apiResults[i].joostId;
    var avatar = getAvatar(apiResults[i], 'small');
    var outputListItem={};
    if (!joostName || joostName=="") { continue; }
        outputListItem.title= escapeHTML(apiResults[i].userName);
        outputListItem.thumbnail=avatar;
        outputListItem.link='users/'+joostName+"/";
        outputListItem.type='user';
        outputListItem.description=friendFormat(apiResults[i]);
        outputList.push(outputListItem);
  }
  document.getElementById('friendsActiveList').innerHTML=renderThumbAndTextList(outputList);
};


Friends.Active.toggle=function() {
  if (document.getElementById("friendsActive").style.display==="block") {
    document.getElementById("friendsActive").style.display="none";
    document.getElementById("friendsActiveButton").innerHTML="[+]";
  } else {
    document.getElementById("friendsActive").style.display="block";
    document.getElementById("friendsActiveButton").innerHTML="[-]";
  }
};
FriendsRequests = {
  theUser:undefined,
  service: "/api/friends/"
 };

FriendsRequests.message=function(text, where){
  document.getElementById(where).innerHTML = text;
};

FriendsRequests.refreshList=function(addTime,accept){
  var newbe = 'NO';
  if (accept) {
	  var newbe = 'YES';
  }
  var url=this.service+"get?type=FRIEND&status=PENDING&role=TARGET&newbe="+newbe+"&json_function=FriendsRequests.handleResp"+(addTime ? "&_d="+new Date().valueOf() : "");
  if (window.FriendPendingListRoot) {
    url=window.FriendPendingListRoot+url;
  }
  jsonRequest(url);
};

FriendsRequests.handleResp = function(obj) {
  if (obj.success) {
    FriendsRequests.displayResults(obj);
    if(document.getElementById('friendsBrick')){
        Friends.refreshList(true);
    }
    if (document.getElementById('friendsBigList') && obj.newbe != 'NO'){
      Friends.refreshBigList(true,true);
    }
  } else {
    FriendsRequests.message(obj.message,"friendsRequestsMsg");
  }
};

FriendsRequests.displayResults=function(obj) {
  var friendsList=document.getElementById("friendsRequestsList");
  var apiResults=obj.friends;
  var nApiResults=obj.friends.length;
  var count=0;
  var outputList=[];

  for (var i=0;i<nApiResults;i++) {
    // only display if we're the recipient of the request for friendship
    if (apiResults[i].target == obj.joostName) {
      var friend=apiResults[i];
      
      var firstName=friend.firstName;
      var lastName=friend.lastName;
      var desc=[];
     
      var fbid = 'undefined';
      if(apiResults[i].fbid) {
        fbid=apiResults[i].fbid;
      } else {
        fbid = 'undefined';
      }

      desc.push(friendFormat(friend),"<br/>");
      var avatar = getAvatar(friend, 'small');

      desc.push('<a class="miniButton miniButtonAccept" title="accept" onclick="FriendsRequests.accept(&quot;'+apiResults[i].source+'&quot;);return false;" href="#"><img alt="accept" src="/static/transparent.gif"/><span class="label">accept</span></a>');
      desc.push('<a class="miniButton miniButtonRefuse" title="refuse" onclick="FriendsRequests.refuse(&quot;'+apiResults[i].source+'&quot;); return false;" href="#"><img alt="refuse" src="/static/transparent.gif"/><span class="label">refuse</span></a>');

      count++;
      outputList.push({title: escapeHTML(apiResults[i].userName),
                       thumbnail:avatar,
                       link:'users/'+encodeURIComponent(apiResults[i].source)+'/',
                       type:'user',
                       showProfile: apiResults[i].showProfile,
                       fbid: fbid,
                       description:desc.join('')
                       });
    }
  }
  if(count==0){
    document.getElementById('friendsRequestsBrick').style.display="none";
    document.getElementById('friendsRequestsList').innerHTML="";
    document.getElementById("friendsRequestsMsg").innerHTML="<p>No friend requests at the moment</p>";
  } else {
    document.getElementById('friendsRequestsBrick').style.display="block";
    document.getElementById('friendsRequestsList').innerHTML=renderThumbAndTextList(outputList,'',3);
    setTimeout(FBParseDom,0);
  }
};



FriendsRequests.handleAcceptResponse=function(obj) {
  var user="";
  var err="";
  if(obj.joostName){
    user=obj.joostName;
    userName=obj.userName;
  }
  if(obj.message){
    err=obj.message;
  }
  errorOrNote(obj.success,obj.message,"You have added <a href='/users/"+user+"'/>"+escapeHTML(userName)+"</a> as a friend");

  FriendsRequests.refreshList(true,true);
};

FriendsRequests.handleRefuseResponse=function(obj) {
  var user="";
  var err="";
  if(obj.joostName){
    user=obj.joostName;
    userName=obj.userName;
  }
  if(obj.message){
    err=obj.message;
  }
  errorOrNote(obj.success,obj.message,"You have refused the friend invite from <a href='/users/"+user+"/'>"+escapeHTML(userName)+"</a>");

  FriendsRequests.refreshList(true);
};

FriendsRequests.accept=function(joostname) {
  var url=this.service+"confirm/"+joostname+"?json_function=FriendsRequests.handleAcceptResponse";
  if (window.FriendAddRoot) {
    url=window.FriendAddRoot+url;
  }
  jsonRequest(url);
};

FriendsRequests.refuse=function(joostname) {
  var url=this.service+"remove/"+joostname+"?json_function=FriendsRequests.handleRefuseResponse";
  if (window.FriendAddRoot) {
    url=window.FriendAddRoot+url;
  }
  jsonRequest(url);
};


//########## Search friends ######################################################################

FriendsSearch = {
  overlay: undefined,
  service:'/api/friends/',
  friendSearchProvider:'/api/friends/search?json_function=FriendsSearch.handleResponse&q=%q'
};

FriendsSearch.search=function(q){
  var q2=encodeURIComponent(q);
  var url=FriendsSearch.friendSearchProvider.replace(/%q/gim,q2);
  if (window.FriendSearchRoot) {
    url=window.FriendSearchRoot+url;
  }
  FriendsSearch.cleanList();
  document.getElementById("friends_search_throbber").style.display="block";
  jsonRequest(url);
};

FriendsSearch.handleResponse=function(obj) {
  document.getElementById("friends_search_throbber").style.display="none";
  if (obj.success) {
    // Should do some sort of notifier here
    FriendsSearch.displayResults(obj);
  } else {
    document.getElementById("friendsSearchList").innerHTML="<p>" +  obj.message + "</p>";
  }
};

FriendsSearch.cleanList=function(obj) {
  document.getElementById("friendsSearchList").innerHTML="";
};

FriendsSearch.displayResults=function(obj) {
  var ul=document.getElementById("friendsSearchList");
  var apiResults=obj.search.results;
  var nApiResults=obj.search.results.length;
  var outputList=[];

  for (var i=0;i<nApiResults;i++) {
    var joostName=apiResults[i].screenname;
    var firstName=apiResults[i].firstName;
    var lastName=apiResults[i].lastName;
    var friend=apiResults[i].friend;
    var target=apiResults[i].target;
    var fbid = 'undefined';
    if(apiResults[i].fbid) {
        fbid=apiResults[i].fbid;
    } else {
        fbid = 'undefined';
    }
    var avatar = getAvatar(apiResults[i], 'small');

    if (!joostName || joostName==="") { continue; }
      var v=[friendFormat(apiResults[i])];
      if (firstName||lastName) {
        var vNames=[];
        if (firstName) {
          vNames.push(escapeHTML(firstName));
        }
        if (lastName) {
          vNames.push(escapeHTML(lastName));
        }
        v.push(" ("+vNames.join(' ')+")");
      }

      if (joostName != User_Details.joostName && (!friend || (friend=="suspended"&&target==User_Details.joostName))) {
        v.push('<p id="sf-'+joostName+'"><a class="miniButton miniButtonMore" title="add" onclick="FriendsSearch.request(&quot;'+joostName+'&quot;); return false;" href="#"><img alt="more" src="/static/transparent.gif"/><span class="label">add</span></a></p>');
      }
      else {
        if(friend==true){
          v.push('<p>(friend)</p>');

        }else{
          if(friend=="suspended"){
            //do we tell them if they're blocked?
            //v.push('<p>(blocked)</p>');
          }
          else if(friend=="pending"){
            v.push('<p>(pending)</p>');
          }else{
            v.push('<p><img src="/static/minilabel-you.png" class="minilabelYou" alt="You"/></p>');
          }
        }
      }

      outputList.push({
       title:joostName,
       thumbnail:avatar,
       link:'users/'+joostName+"/",
       type:'user',
       fbid: fbid,
       description: v.join('')});
  }
  if (nApiResults==0) {
    document.getElementById('friendsSearchList').innerHTML="<h2>Search Results</h2><p>No match found.</p><p>Why not <a href='/people/invite/'>invite your friend</a>?</p>";
  } else {
    document.getElementById('friendsSearchList').innerHTML="<h2>Search Results</h2>"+renderThumbAndTextList(outputList);
    setTimeout(FBParseDom,3000);
  }
};

FriendsSearch.request=function(joostname) {
  document.getElementById("sf-"+joostname).innerHTML=""; // remove the button that's been clicked
  var url=this.service+"add/"+joostname+"?json_function=FriendsSearch.handleResponse2";
  if (window.FriendAddRoot) {
    url=window.FriendAddRoot+url;
  }
  jsonRequest(url);
};

FriendsSearch.handleResponse2=function(obj) {

  var err="";

  if(obj && obj.message){
    err=obj.message;
    if(obj.message.indexOf("SUSPENDED")!=-1){
      err="Friendship not possible &ndash; person has refused a previous offer of friendship";
    } else if (obj.message.indexOf("ACTIVE")!=-1){
      err="You are already friends!";
    } else if (obj.message.indexOf("PENDING")!=-1){
      err="You have already requested friendship.";
    }

  }

  errorOrNote(obj.success,"Failed to add friend: "+err,"Friendship request sent");
};

var FriendsFavorites={
  api:"/api/friends/getFriendsFavorites?json_function=FriendsFavorites.load"
};

FriendsFavorites.refreshList=function() {
  var url=FriendsFavorites.api;
  if (window.FriendFavoritesRoot) {
    url=window.FriendFavoritesRoot+url;
  }
  jsonRequest(url);
};

FriendsFavorites.refreshListW=function() {
  var url=FriendsFavorites.api;
  if (window.FriendFavoritesRoot) {
    url=window.FriendFavoritesRoot+url;
  }
  jsonRequest(url+"W");
};

FriendsFavorites.load=function(obj) {
  FriendsFavorites.render('ff_list',obj);
}

FriendsFavorites.loadW=function(obj) {
  FriendsFavorites.render('ff_list_w',obj,true);
}

FriendsFavorites.render=function(id,obj,wide) {
  var el=document.getElementById(id);
  if (obj && obj.success && obj.entries.length>0) {
    if (wide) {
      if (view=="list") {
        el.innerHTML=renderVideoListWide(obj.entries, [
          {"title": "Add to My Queue", "href": "#", "onclick": "epgPage.addToList(event, 'playlist', '%i', 'video_%i'); return false;", "icon": "miniButtonQueueAdd16","nolabel": "true"}
        ]);
      } else {
        el.innerHTML=renderVideoListWideThumbs(obj.entries, [
          {"title": "Add to My Queue", "href": "#", "onclick": "epgPage.addToList(event, 'playlist', '%i', 'video_%i'); return false;", "icon": "miniButtonQueueAdd16","nolabel": "true"}
        ]);
      }
    } else {
      el.innerHTML=renderVideoList(obj.entries,'friendsFavorites');
    }
    fixPNG();
  } else {
    if (el) {
      el.innerHTML="<p>No friends favorites at the moment.</p>";
    }
  }
};
var FriendsRecentlyWatched={
  api:"/api/events/getwatchedbyfriends?json_function=FriendsRecentlyWatched.load"
};

FriendsRecentlyWatched.refreshList=function() {
  var url=FriendsRecentlyWatched.api;
  if (window.FriendRecentlyWatchedRoot) {
    url=window.FriendRecentlyWatchedRoot+url;
  }
  jsonRequest(url);
};

FriendsRecentlyWatched.load=function(obj) {
  FriendsRecentlyWatched.render('fvv_list',obj);
}

FriendsRecentlyWatched.render=function(id,obj) {
  var el=document.getElementById(id);
  if (obj && obj.success && obj.events.length>0) {
    el.innerHTML=renderVideoList(obj.events,'friendsRecentlyWatched');
  } else {
    if (el) {
      el.innerHTML="<p>Your friends haven't watched anything recently.</p>";
    }
  }
};


if (window.FriendsDelayedExecute) {
  for (var i=0;i<FriendsDelayedExecute.length;i++) {
    try {
      FriendsDelayedExecute[i]();
    } catch (e) {
      // so others are not blocked
    }
  }
}
