
Type.registerNamespace('FriendsCategories');

//Used for paging calls.
var quickfind = null;
FriendsCategories.QuickFind = function(totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached, itemsPerPage)
{
	this._inputbox = null;
	this._category = "all";
	this._friendsInfo = null;
	this._livelistcategoryId = null;
	this._onUserInputCallback = null;
	this._onQuickFindDataReceivedCallback = null;
	this.filteredFriends = null;
	this._ItemsPerPage = 40;
	if(itemsPerPage)
	{
		this._ItemsPerPage = itemsPerPage;
	}
	this._MAXCOUNT = 400;
	this._searchChar = null;
	this._prevInputValue = "";
	this._nameLength = 7;
	
	this._totalFriendCount = totalFriendCount;
	this._requesterId = requesterId;
	this._inputbox = $get('quickfindinput');
	this._onUserInputCallback = onUserInput;
	this._onQuickFindDataReceivedCallback = onQuickFindDataReceived;
	this._isQFCached = (isQFCached.toLowerCase() == "true");
		
	//Register handler for KeyPress
	$addHandlers(this._inputbox, {keyup:this.OnQuickInput},this);		
	
	//Set Context for Callback function to the current object
	MySpace.Web.Modules.Friends.Services.FriendsService.set_defaultUserContext(this);	
	
	quickfind= this;
		
}

FriendsCategories.QuickFind.prototype = 
{	
	OnQuickInput : function(evt)
	{
		if(evt.keyCode != 13 && this._inputbox.value != this._prevInputValue)
		{
			this._prevInputValue = this._inputbox.value;
			this._onUserInputCallback.call(this,this._inputbox.value, evt.keyCode);
			if(this._inputbox.value == "")
			{
				//Keep it cached if the no of friends <= _MAXCOUNT since we retrieve all
				//in this case.
				if(this._totalFriendCount > this._MAXCOUNT)
				{
					this._friendsInfo = null;
					this._processing = false;
				}												
			}		
			else if(this._friendsInfo == null)
			{		
				if(!this._processing)
				{
					this._processing = true;
					this._searchChar = this._inputbox.value;	
					
					if(this._totalFriendCount <= this._MAXCOUNT)
					{
						this._searchChar = "all";
					}
					
					if(this._isQFCached)
					{								
						MySpace.Web.Modules.Friends.Services.FriendsService.FindFriendsGet(this._requesterId, this._searchChar,this.OnFriendsDataReceived, this.OnServerCallFailed);						
					}
					else
					{
						MySpace.Web.Modules.Friends.Services.FriendsService.FindFriends(this._requesterId, this._searchChar,this.OnFriendsDataReceived, this.OnServerCallFailed);						
					}
				}	
			}
			else if(!this._processing)
			{
				this.FilterFriends();
			}
		}
		else
		{
			evt.stopPropagation();
			evt.preventDefault();			
			return false;
		}
	},
	
	ClearInput : function()
	{
		if(this._inputbox.value != "")
		{		
			this._inputbox.value = "";
			this._prevInputValue = "";
			blurBox(this._inputbox);			
		}
	},
	
	FilterFriends : function()
	{
			//Search inside the data		
			var filteredData = new Array();			
			for (var i=0;i<this._friendsInfo.length;i++)
			{
				if(this._friendsInfo[i].displayName!= null && this._friendsInfo[i].displayName.toLowerCase().startsWith(this._inputbox.value.toLowerCase()))
				{
					Array.add(filteredData,this._friendsInfo[i]);
				}
			}		
			
			this.filteredFriends = filteredData;
			if(filteredData.length>0)
			{
				this.GenerateAddMembersHtml(1);
			}
			else
			{
				this.GenerateNoFriendsHtml();
			}
	},
	
	SetCurrentCategory : function (category)
	{
		this._category = category;
	},
	
	OnFriendsDataReceived : function(result, userContext, methodName)
	{		
		//Check for errors
		if(! result.ErrMsg)
		{			
			if(result.QuickFindData.length > 0)
			{
				userContext._friendsInfo = result.QuickFindData;
				userContext._processing = false;
				userContext.FilterFriends();
			}
			else
			{
				userContext.GenerateNoFriendsHtml();
				userContext._processing = false;
			}
		}
		else
		{
			userContext.GenerateNoFriendsHtml(result.ErrMsg);
			userContext._processing = false;
		}		
		
	},	
	
	OnServerCallFailed : function(result, userContext, methodName)
	{
		userContext._processing = false;
	},
	
	GenerateNoFriendsHtml : function(msg)
	{	
		if(this.ShowResults())
		{
			msg = msg ? msg : MySpaceRes.ViewAllFriendsPage.NoFriendsToDisplay;
			var nofriends ='<span class="nofriendsmsg">' + msg + '</span>';
			this._onQuickFindDataReceivedCallback.call(this, nofriends, "", "");		
		}
	},
	
	ShowResults : function()
	{
		var inp = this._inputbox.value;
		
		if(inp == "" ||  this._inputbox.className == "inp grey" || (this._searchChar.toLowerCase()!= "all" && inp.substring(0,1).toLowerCase() != this._searchChar.toLowerCase()))
		{
			return false;
		}
		
		return true;		
	},
	
	//Virtual Method
	GenerateAddMembersHtml : function(currentPageNo)
	{
		throw ("Implement it");			
	},
	
	QFPage: function(pageNo)
	{
		this.GenerateAddMembersHtml(pageNo);	
	},
	
	DisableUnload : function(e)
	{		
		return false;		
	},
	
	GenerateAddMembersPager : function(currentPageNo)
	{
		//{0} Pager listing title
		//{1} Links
		//{2} Last Page Link
		//{3} Prev Link
		//{4} Next Link
				
		var pagerContainer = '<DIV class="alphaLine" id="nav_bottom"><SPAN class="nav_left"><SPAN class="pgerTitle">{0}</SPAN>{1} ' + MySpaceRes.ViewAllFriendsPage.Of + ' {2} </SPAN><SPAN class="nav_right">{3} | {4}</SPAN></DIV>'
		var linkString = '<a href="{0}" onclick = quickfind.DisableUnload() class="pagingLink">{1}</a>';
        var selectedLinkString = '<a class="highlight">{0}</a>';
        var prevnextlink =  '<a href="{0}" onclick = quickfind.DisableUnload() class="nextPagingLink">{1}</a>';
        var disabledprevnextlink = '<a class="nextPagingLink disabledPaging">{0}</a>';
        
        var pagerMethod ="javascript:quickfind.QFPage({0})";
        
        var perPage = this._ItemsPerPage;
        var totalItems = this.filteredFriends.length;
        var totalPageCount = Math.ceil(totalItems/perPage);
        var startItem = 1 + ((currentPageNo -1) * perPage);
        var endItem = (totalItems > (currentPageNo * perPage)) ? (currentPageNo * perPage) : totalItems;
        
        //{0} Pager listing title
        var listingTitle = String.format(MySpaceRes.ViewAllFriendsPage.ListingString,startItem + "-" + endItem ,totalItems);
        
        //{1} Links
        var links = new Sys.StringBuilder("");      
        
        var totalpageLinks = (totalPageCount > 5) ? 5 : totalPageCount;
        
        var startPageNo =1;        
        if((currentPageNo -3) >= 0 && ((currentPageNo + 2) <= totalPageCount) )
        {
          	//In Middle
			startPageNo = currentPageNo-2;
        }
        else if((currentPageNo -3) >= 0 && ((currentPageNo + 2) > totalPageCount) )
        {
			startPageNo = currentPageNo - (4 - (totalPageCount - currentPageNo));
			
			if(startPageNo < 1) {startPageNo = 1;}
        }
        else
        {
			startPageNo = 1;
        }
        
        if(currentPageNo > 3)
        {
			links.append(String.format(linkString, String.format(pagerMethod,1),1));
			links.append("&nbsp;");
			//Show <<
			links.append(String.format(linkString, String.format(pagerMethod, startPageNo -1),"&laquo;"));
			links.append("&nbsp;");					
        }
        
        for(var i=0;i<totalpageLinks;i++)
        {
			if( (startPageNo + i) == currentPageNo )
			{
				links.append(String.format(selectedLinkString,startPageNo + i));
				links.append("&nbsp;");
			}
			else
			{
				links.append(String.format(linkString, String.format(pagerMethod,startPageNo + i),startPageNo + i));
				links.append("&nbsp;");
			}
        }
        
        if(currentPageNo + 3 <= totalPageCount)
        {			
			links.append(String.format(linkString, String.format(pagerMethod, startPageNo + 5),"&raquo;"));
			links.append("&nbsp;");					
        }
        
        //{2} Last Page Link
        var lastPageLink;
        if(currentPageNo == totalPageCount)
        {
			lastPageLink = String.format(selectedLinkString,totalPageCount);
        }
        else
        {
			lastPageLink = String.format(linkString, String.format(pagerMethod,totalPageCount),totalPageCount);
        }
        
        //{3} Prev Link
        var prevLink;
        if(currentPageNo-1 > 0)
        {
			prevLink = String.format(prevnextlink, String.format(pagerMethod,currentPageNo-1),MySpaceRes.ViewAllFriendsPage.PreviousShort);
        }
        else
        {
			prevLink = String.format(disabledprevnextlink,MySpaceRes.ViewAllFriendsPage.PreviousShort);
        }
        
        //{4} Next Link
        var nextLink;
        if(currentPageNo+1 <= totalPageCount)
        {
			nextLink = String.format(prevnextlink, String.format(pagerMethod,currentPageNo+1),MySpaceRes.ViewAllFriendsPage.NextShort);
        }
        else
        {
			nextLink = String.format(disabledprevnextlink,MySpaceRes.ViewAllFriendsPage.NextShort);
        }
        
        //Create the full pager now.
        
        return String.format(pagerContainer, listingTitle, links.toString(),lastPageLink, prevLink, nextLink);        
		
	},
	
	GetTruncatedName : function(displayName)
	{
		if(displayName.length > (this._nameLength + 3))
		{
			return displayName.substring(0,this._nameLength) + " ..";
		}
		
		return displayName;
	}	
}

//Inherit from the base class
FriendsCategories.AddMembersFind = function(totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached, livelistcategoryId) 
{
    FriendsCategories.AddMembersFind.initializeBase(this, [totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached]);
    this._livelistcategoryId = livelistcategoryId;
}

FriendsCategories.AddMembersFind.prototype =
{

	UpdateMemberShipStatus : function(friendId, isAdded)
	{
		if(this._friendsInfo != null)
		{
			for (var i=0;i<this._friendsInfo.length;i++)
			{
				if(this._friendsInfo[i].friendId == friendId)
				{
					this._friendsInfo[i].isMember = isAdded;
					break;
				}
			}		
			
		}
	},
	OnFriendsDataReceived : function(result, userContext, methodName)
	{		
		//Check for errors
		if(! result.ErrMsg)
		{			
			if(result.QuickFindData.length > 0)
			{
				userContext._friendsInfo = result.QuickFindData;			
				var friendIds = new Array();
				for (var i=0;i<result.QuickFindData.length;i++)
				{
					Array.add(friendIds, result.QuickFindData[i].friendId);
				}
										
				MySpace.Web.Modules.Friends.Services.FriendsService.BelongsToCategoryInfo(userContext._livelistcategoryId, friendIds, userContext.OnMemeberInfoReceived, userContext.OnServerCallFailed);									
			}
			else
			{
				userContext.GenerateNoFriendsHtml();
				userContext._processing = false;
			}
		}
		else
		{
			userContext.GenerateNoFriendsHtml(result.ErrMsg);
			userContext._processing = false;
		}		
		
	},
	
	OnMemeberInfoReceived : function(result, userContext, methodName)
	{
		//Check for errors
		if(! result.ErrMsg)
		{
			if(userContext._friendsInfo != null && userContext.ShowResults())
			{
				var memeberInfo = result.MemberInfo;			
				for (var i=0;i<memeberInfo.length;i++)
				{
					userContext._friendsInfo[i].isMember = memeberInfo[i];
				}		
				
				userContext._processing = false;
				userContext.FilterFriends();
			}
		}
		else
		{
			userContext.GenerateNoFriendsHtml(result.ErrMsg);
			userContext._processing = false;
		}
	},
	
	GenerateAddMembersHtml : function(currentPageNo)
	{
		//{0} FriendId
		//{1} DisplayName
		//{2} ImageUrl
		//{3} FriendsCssClass
		//{4} ActionBarCssClass
		
		if(! this.ShowResults()) return;		
		
		var memberItem = new Sys.StringBuilder("");
		memberItem.append('<li><div class="{3}" id="friendsbox_{0}" onclick="manageFriends.AddOrRemoveFriend(this,{0})">');
		memberItem.append('<input type="hidden" id="FriendsId_{0}"  value="{0}"/>');
		memberItem.append('<div class="friendsimagebox">');
		memberItem.append('<div class="actionbar {4}" id="actionbar_{0}"></div>');
		memberItem.append('<span class="friendname" id="friendname_{0}">{1}</span>');
		memberItem.append('<div class="friendphoto"><img id="friendimg_{0}" src="{2}" alt="" width="60px" height="53px"/></div>');
		memberItem.append('</div></div></li>');
		
		var memberHtml = new Sys.StringBuilder("");
		var friendList = new Sys.StringBuilder("");
		
		var perPage = this._ItemsPerPage;
        var totalItems = this.filteredFriends.length;       
        var startItem = 1 + ((currentPageNo -1) * perPage);
        var endItem = (totalItems > (currentPageNo * perPage)) ? (currentPageNo * perPage) : totalItems;
        
		var pagecount = (this.filteredFriends.length > this._ItemsPerPage) ? this._ItemsPerPage : this.filteredFriends.length;
		
		for(var i=startItem-1;i<endItem;i++)
		{			
			with(this.filteredFriends[i])
			{
				if(this.filteredFriends[i].isMember)
				{
					friendList.append(friendId);
					friendList.append(",");
				}
								
				var friendCssClass = this.filteredFriends[i].isMember ? "friendsbox friendsboxinlist" : "friendsbox";
				var actionCssClass = this.filteredFriends[i].isMember ? "actionExists" : "actionNotExists";				
				memberHtml.append(String.format(memberItem.toString(),friendId, displayName, imageURL, friendCssClass, actionCssClass));
			}
		}
		
		var membersHtml = "<div class='memberspanel'><ul>" + memberHtml.toString() + "</ul></div>";
		var pagerHtml = this.GenerateAddMembersPager(currentPageNo)
		this._onQuickFindDataReceivedCallback.call(this, membersHtml, pagerHtml, friendList.toString());		
		
	}		
}

//Inherit from the base class
FriendsCategories.TopFriendsFind = function(totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached, topfriendsRef, ItemsPerPage) 
{
    FriendsCategories.TopFriendsFind.initializeBase(this, [totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached]);       
    this._topfriendsRef = topfriendsRef;
    if(ItemsPerPage)
    {
		this._ItemsPerPage = ItemsPerPage;
	}
}

FriendsCategories.TopFriendsFind.prototype =
{

	FilterFriends : function()
	{
			//Search inside the data		
			var filteredData = new Array();			
			for (var i=0;i<this._friendsInfo.length;i++)
			{
				if(this._friendsInfo[i].displayName!= null && this._friendsInfo[i].displayName.toLowerCase().startsWith(this._inputbox.value.toLowerCase()) &&  Array.indexOf(this._topfriendsRef._topfriendList, this._friendsInfo[i].friendId)== -1)
				{
					Array.add(filteredData,this._friendsInfo[i]);
				}
			}		
			
			this.filteredFriends = filteredData;
			if(filteredData.length>0)
			{
				this.GenerateAddMembersHtml(1);
			}
			else
			{
				this.GenerateNoFriendsHtml();
			}
	},
	
	GenerateNoFriendsHtml : function(msg)
	{	
		if(this.ShowResults())
		{			
			this._onQuickFindDataReceivedCallback.call(this, "", "");		
		}
	},
	
	GenerateAddMembersHtml : function(currentPageNo)
	{
		//{0} FriendId
		//{1} ProfileLink
		//{2} DisplayName
		//{3} FriendUrl
		
		if(! this.ShowResults()) return;
		
		var memberItem = new Sys.StringBuilder("");
		memberItem.append('<div class="griditem" friendid="{0}">');
		memberItem.append('<a href="{1}">{2}</a><br /><img src="{3}" onload="javascript:resizeImage(this)" /></div>');
		
		var memberHtml = new Sys.StringBuilder("");
		var friendList = new Sys.StringBuilder("");
		
		var perPage = this._ItemsPerPage;
        var totalItems = this.filteredFriends.length;       
        var startItem = 1 + ((currentPageNo -1) * perPage);
        var endItem = (totalItems > (currentPageNo * perPage)) ? (currentPageNo * perPage) : totalItems;
        
		var pagecount = (this.filteredFriends.length > this._ItemsPerPage) ? this._ItemsPerPage : this.filteredFriends.length;
		
		for(var i=startItem-1;i<endItem;i++)
		{			
			with(this.filteredFriends[i])
			{	
				if(Array.indexOf(this._topfriendsRef._topfriendList, friendId)== -1)
				{											
					memberHtml.append(String.format(memberItem.toString(),friendId, "javascript:void(0)", this.GetTruncatedName(displayName), imageURL));
				}
			}
		}
		
		var membersHtml = memberHtml.toString();
		var pagerHtml = this.GenerateAddMembersPager(currentPageNo)
		this._onQuickFindDataReceivedCallback.call(this, membersHtml, pagerHtml);		

	},
	
	DisableUnload : function()
	{
		 this._topfriendsRef._noPrompt = true;
	},
	
	QFPage: function(pageNo)
	{
		if(! this._topfriendsRef._isRandom)
		{
			this.GenerateAddMembersHtml(pageNo);	
		}
	}
}

//Inherit from the base class
FriendsCategories.FriendSuggestionFind = function(totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached, itemsPerPage) 
{
    FriendsCategories.FriendSuggestionFind.initializeBase(this, [totalFriendCount, requesterId, onUserInput, onQuickFindDataReceived, isQFCached, itemsPerPage]);
}

FriendsCategories.FriendSuggestionFind.prototype =
{

	GenerateAddMembersHtml : function(currentPageNo)
	{
		//{0} FriendId
		//{1} DisplayName
		//{2} ImageUrl
		
		if(! this.ShowResults()) return;		
		
		var memberItem = new Sys.StringBuilder("");
		memberItem.append('<li id="friendli_{0}"><div class="friendsbox" id="friendsbox_{0}" FriendId={0}>');
		memberItem.append('<input type="hidden" id="FriendsId_{0}"  value="{0}"/>');
		memberItem.append('<div class="friendsimagebox" id="imgbox_{0}">');
		memberItem.append('<div class="actionbar actionNotExists" id="actionbar_{0}"></div>');
		memberItem.append('<span class="friendname" id="friendname_{0}">{1}</span>');
		memberItem.append('<div class="friendphoto"><img id="friendimg_{0}" src="{2}" alt="" width="60px" height="53px"/></div>');
		memberItem.append('</div></div></li>');
		
		var memberHtml = new Sys.StringBuilder("");		
		
		var perPage = this._ItemsPerPage;
        var totalItems = this.filteredFriends.length;       
        var startItem = 1 + ((currentPageNo -1) * perPage);
        var endItem = (totalItems > (currentPageNo * perPage)) ? (currentPageNo * perPage) : totalItems;
        
		var pagecount = (this.filteredFriends.length > this._ItemsPerPage) ? this._ItemsPerPage : this.filteredFriends.length;
		
		for(var i=startItem-1;i<endItem;i++)
		{			
			with(this.filteredFriends[i])
			{				
				memberHtml.append(String.format(memberItem.toString(),friendId, displayName, imageURL));
			}
		}
		
		var membersHtml = "<ul>" + memberHtml.toString() + "</ul>";
		var pagerHtml = this.GenerateAddMembersPager(currentPageNo)
		this._onQuickFindDataReceivedCallback.call(this, membersHtml, pagerHtml);		
		
	}		
}

FriendsCategories.QuickFind.registerClass('FriendsCategories.QuickFind');
FriendsCategories.AddMembersFind.registerClass('FriendsCategories.AddMembersFind', FriendsCategories.QuickFind);
FriendsCategories.TopFriendsFind.registerClass('FriendsCategories.TopFriendsFind', FriendsCategories.QuickFind);
FriendsCategories.FriendSuggestionFind.registerClass('FriendsCategories.FriendSuggestionFind', FriendsCategories.QuickFind);






