if(window.MyOpenSpace === undefined){
MyOpenSpace = {};
}
if(MyOpenSpace.Widgets === undefined){
MyOpenSpace.Widgets = {version:0.2};
}

MyOpenSpace.Widgets.Utility = {
applyInlineStyle: function(element, style){
if(!element || !style) return;

var styleVal;
var stylePart;
for(stylePart in style){
try{
styleVal = eval("style." + stylePart);
eval("element.style." + stylePart + "= \"" + styleVal + "\";");
}
catch(ex){
alert(ex.message + ":\n\n " + stylePart + "\n" + styleVal)
}
}

},
safeAttachEvent: function(element, eventName, action){
if(!element){
return;
}
if(element.addEventListener){
element.addEventListener(eventName, action, false);
}
else if(element.attachEvent){
element.attachEvent("on"+eventName, action);
}
},
domElement: function(tag, contents, attributes){
var elem = document.createElement(tag);
var dbs = 'created dom: ' + tag;
if(contents){
dbs += "\n\nwith: \n" + contents.toString()
}
if(!!(window.attachEvent && !window.opera)){
}

if(contents){
if(typeof(contents) == "string"){
elem.innerHTML = contents;
}
else{
if(contents.length){
var el;
for(var i=0; i < contents.length; i++){
try{
if (typeof(contents[i]) == "string") {
var txtNode = document.createElement("span");
txtNode.innerHTML = contents[i];
elem.appendChild(txtNode);
}
else {

if (contents[i]) {
elem.appendChild(contents[i])
}
else {
alert('null elem')
}
}
}
catch(ex){
alert("dom build failed: " + ex.message)
}
}
}
else{
try{
elem.appendChild(contents);					
}
catch(ex){
alert("single dom build failed: " + ex.message)
}
}
}
}

if(attributes){
var val;
for(var attr in attributes){
val = eval("attributes." + attr);
elem.setAttribute(attr, val);
}
}		
return elem;		
}
}

MyOpenSpace.Widgets.FriendList = function(friendsData){
this._friendsData = null; //OSocial response collection

this.firstNameTree = null;
this.lastNameTree = null;
this.friendMap = new Array();
this._pagingFriends	= new Array();

this.initialize(friendsData);

}

MyOpenSpace.Widgets.FriendList.prototype = {
initialize: function(friendsData){
this._friendsData = friendsData;
if(this._friendsData != null){
var thisRef = this;
this._friendsData.each(function(friendData){
thisRef.addFriend(friendData);
});
}
},

getFriend: function(id){
return this.friendMap[id];
},

findFriends: function(findLike){
var results = new Array();
if(this.firstNameTree != null){
results = this.firstNameTree.findLike(findLike);
}
if(this.lastNameTree != null){
if(!results){
results = new Array();
}
results = results.concat(this.lastNameTree.findLike(findLike));
}
return results;
},

addFriend: function(person){
var key = person.getField(opensocial.Person.Field.ID)
if (key) {
key = key.toString();
}
else {
alert('no key');
return;
}

if (!this.friendMap[key]) {
this.friendMap[key] = person;
this._pagingFriends.push(person);
}

var xName = person.getField(opensocial.Person.Field.NAME);
if (xName != null && xName.length > 0) {
var parts = xName.split(" ");
if (this.firstNameTree == null) {
this.firstNameTree = new MyOpenSpace.Widgets.FriendList.Node(parts[0], person);
}
else {
this.firstNameTree.addPerson(parts[0], person);
}
if (parts.length > 1) {
var lname = parts[parts.length - 1];
if (this.lastNameTree == null) {
this.lastNameTree = new MyOpenSpace.Widgets.FriendList.Node(lname, person);
}
else {
this.lastNameTree.addPerson(lname, person);
}
}
}
}
}

MyOpenSpace.Widgets.FriendList.Node = function(key, person){
this.key = key;
this.person = person;
this.leftNode = null;
this.rightNode = null;
this.parentNode = null;
this.subNodeCount = 0;  //count of child nodes under this node

this.addPerson = function(key, person){
if(!key){
return;
}

this.subNodeCount++;

if(this.compareTwoPartialKeys_(this.key, key) < 0){
if(this.rightNode == null){
this.rightNode = new MyOpenSpace.Widgets.FriendList.Node(key, person);
}
else{
this.rightNode.addPerson(key, person);
}
}
else{
if(this.leftNode == null){
this.leftNode = new MyOpenSpace.Widgets.FriendList.Node(key, person);
}
else{
this.leftNode.addPerson(key, person);
}
}
};

this.compareTo = function(node){
if(node == null){
return 1;
}
return this.compareTwoPartialKeys_(this.key, node.key);
};

this.compareTwoPartialKeys_ = function(mainKey, testKey){
var a = mainKey.toLowerCase();
var b = testKey.toLowerCase();
if(a.length > b.length){
a = a.substr(0, b.length)
}
if(a<b){
return -1;
}
else if(a==b){
return 0;
}
else{
return 1;
}
};

this.findLike = function(partialKey){
var results = new Array();
if(partialKey == null || partialKey.length == 0){
return results;
}
var keyTest = this.compareTwoPartialKeys_(this.key, partialKey);
if(keyTest == 0){
results.push(this.person);
}
if(this.subNodeCount > 0){
//test right node if keytest is less or equal to node
if(keyTest == -1){
if (this.rightNode != null) {
results = results.concat(this.rightNode.findLike(partialKey));
}
}
else if (keyTest == 0) {
if (this.leftNode != null) {
results = results.concat(this.leftNode.findLike(partialKey));
}
if (this.rightNode != null) {
results = results.concat(this.rightNode.findLike(partialKey));
}
}
else {
if (this.leftNode != null) {
results = results.concat(this.leftNode.findLike(partialKey));
}
}
}
return results;		
}
}

MyOpenSpace.Widgets.FriendPicker = function(){
this.version				= 0.2;
this.MAX_FRIENDS			= 1000;
this.currentPage 			= 1;
this.pageSize				= 12;
this.dataLoaded				= false;
this.DOMElement 			= null;
this._DOMBuilt 				= false;
this._friendDisplayElem 	= null;
this._emptyNode 			= document.createTextNode("");
this._osContainer			= opensocial.Container.get();
this._popupRetries			= 0;
this.MAX_RETRIES			= 100;
this.displayWidth			= "730px";
this.displayHeight			= "310px";
this.friendClickAction		= null;
this.buildSelectedUI		= true;

this.selectedFriend			= null;

this.friendsCatalog			= null;

this._isIE = !!(window.attachEvent && !window.opera); //credit to prototype.js

this.ElementIDs = {
pagingLabel: 		'_mys_pageLabel',
searchBox: 			'_mys_searchTextBox',
searchResults: 		'_mys_searchResults',
popTrigger:			'_mys_popTrigger'
}

this.Styles = {
styleFriendPickBlock: {
padding: 	"2px",
cursor:		"pointer",
marginTop:	"5px",
marginRight	:"5px",
fontSize:	"13px",
fontWeight:	"bold",
minHeight:  "60px",
height: "60px",
overflow:'hidden',
zIndex: 10
},

styleFriendPickImageBlock: {
align:		"middle"
},

styleQuickBorder: {
border:	"1px solid green",
padding: "4px"
},

styleButton: {
border:	"1px solid #AAA",
padding: "3px",
backgroundColor: "#DDD",
cursor: "pointer",
width: "18px",
height: "18px",
overflow: "hidden",
textAlign: "center",
marginRight:"3px",
fontSize: "7pt",
fontFamily: "courier, sans-serif"
},

styleSearchResults: {
position: "absolute",
border: "1px solid green",
height: "200px",
width: "180px",
display: "none",
backgroundColor: "white",
fontSize: "8pt",
fontWeight: "normal"
},

styleTitleBar: {
borderTop: "1px solid #333",
borderBottom: "1px double #333",
fontSize: "6pt",
paddingLeft: "3px",
backgroundColor: "#003399",
display:'none'			
},

stylePopupWindow: {
height:this.displayHeight,
overflow:"hidden"
}

};

// icons sources
this.Icons = {
prev: "http://a454.ac-images.myspacecdn.com/images01/56/m_04c6d68883ac1df9b2dab3db57013845.png",
next: "http://a142.ac-images.myspacecdn.com/images01/38/m_e7abc35000473693de736157ab6358ad.png",
close: "http://a609.ac-images.myspacecdn.com/images01/35/m_a6c0aff73a2df676f879728e442895a0.png",
showgrid: "http://a172.ac-images.myspacecdn.com/images01/116/m_6c186813c7786593d2ccd6cca39fb0f3.png",
showlist: "http://a809.ac-images.myspacecdn.com/images01/49/m_77ebb6795ff95264bfe73e5f7dfc0b70.png"
}


if(arguments.length > 0){
this.initialize(arguments[0]);
}

};


MyOpenSpace.Widgets.FriendPicker.prototype = {

addFriend: function(person){
var key = person.getField(opensocial.Person.Field.ID)
if (key) {
key = key.toString();
}
else {
alert('no key');
return;
}

if (!this.friendMap[key]) {
this.friendMap[key] = person;
this._pagingFriends.push(person);
}
else {
//			alert('Double entry');
}
},

searchFriends: function(searchString){
var retval = new Array();
if(this.friendsCatalog == null){
return retval;
}
else{
return this.friendsCatalog.findFriends(searchString);
}
},

_loadOpenSocialFriends: function(){
var dataReqObj = this._osContainer.newDataRequest();
var viewerReq = this._osContainer.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER);
dataReqObj.add(viewerReq);

var viewerFriendsReq = this._osContainer.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS);

dataReqObj.add(viewerFriendsReq);
var thisRef = this; // gets around callback context, but only allows one per page
var callBack = function(dataResponse){
thisRef._loadOsFriendsDataResponse(dataResponse);
};
dataReqObj.send(callBack);
},

_loadOsFriendsDataResponse: function(dataResponse){
var errMsg = '';
if (dataResponse.hadError()) {
var data = dataResponse.get(opensocial.DataRequest.Group.VIEWER_FRIENDS);
//throw "Friends load error: " + data.getErrorCode() + '\n' + data.getErrorMessage();
errMsg = 'Error in friend load: ' + data.getErrorCode() + '\n' + data.getErrorMessage();
}

this.viewerData = dataResponse.get(opensocial.DataRequest.PersonId.VIEWER).getData();
this._friendsData = dataResponse.get(opensocial.DataRequest.Group.VIEWER_FRIENDS).getData();
if(this._friendsData == null){
errMsg += 'No friend data found for picker';
alert(errMsg);
return;
}
this.friendsCatalog = new MyOpenSpace.Widgets.FriendList(this._friendsData);
this.dataLoaded = true;
this._setLoadingMessageDisplay(false);
},

_buildDOM: function(){
if (!this._DOMBuilt) {
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;			

if (!this.DOMElement) {
throw "Friend picker must be initialized with a DOM element";
}

while(this.DOMElement.hasChildNodes()){
this.DOMElement.removeChild(this.DOMElement.lastChild);
}

try{
styleIt(this._friendDisplayElem, this.Styles.styleFriendPickBlock)
}
catch(ex){
alert("Style error: " + ex)
}

this.popupWindow = this._buildPopupWindowDOM();

var picker = this._buildPopupPicker();

this.DOMElement.appendChild(picker);

if (!this._isIE) {
this.DOMElement.appendChild(this._buildLoadingNotice());
}
this.DOMElement.appendChild(this.popupWindow);
if (this.buildSelectedUI) {
var selectedUI = makeElem("div", " ", {id:"__selectedFriendDiv"});
this.DOMElement.appendChild(selectedUI);
}

this.popupIsOpen = false;
this._DOMBuilt = true;
}
},

_buildPopupWindowDOM: function(){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

var titleBar = makeElem("div", "MyOpenSpace.Widgets.FriendPicker - version " + this.version);
styleIt(titleBar, this.Styles.styleTitleBar);

var toolbar = this._buildToolbarDOM();

var searchbar = this._buildSearchDOM();

var fstyle = "width:" + this.displayWidth + ";height:" + this.displayHeight + ";";
fstyle += "overflow:auto;"
this._friendDisplayElem = makeElem("div", "", {style:fstyle});
var popWindow = makeElem("div", [titleBar, toolbar, searchbar, this._friendDisplayElem] );
try{
styleIt(popWindow, this.Styles.stylePopupWindow);
}
catch(ex){
alert('popup style failed: ' + ex.message)
}
return popWindow;
},

_buildSearchDOM: function(){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

var thisRef = this;
var action = function(){
var slem = document.getElementById(thisRef.ElementIDs.searchBox);
if(!slem){
alert('missing search box');
return;
}
thisRef.showSearchResults(thisRef.searchFriends(slem.value), slem.value);
}

var box = makeElem("input", null, 
{
id: this.ElementIDs.searchBox,
type: "text",
autocomplete: "off",
disableautocomplete: "true"
});

MyOpenSpace.Widgets.Utility.safeAttachEvent(box, "keyup", action);

var sresults = makeElem("div", null, 
{
id: this.ElementIDs.searchResults,
type: "text"
});

styleIt(sresults, this.Styles.styleSearchResults);
var text = document.createTextNode(' (Type the name here to search or select from the list below)');
var br = document.createElement('BR');
var br2 = document.createElement('BR');
var elem = makeElem("div", [br, box, text,br2, sresults] );
return elem;
},

_buildLoadingNotice: function(){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

var elem = makeElem("div", "Loading Friends ... please wait", 
{
id:"__pickerLoadingDiv",
style:"font-size:8pt;display:none;position:absolute;border:2px solid grey;left:30px;top:35px;"
}

);

return elem;		
},

_buildPopupPicker: function(){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

try{

var elem = makeElem("span", "[Click here to select a friend]", 
{
style:"color:#888;font-size:13px;cursor:pointer;font-weight:bold;padding:2px;display:none;",
id: this.ElementIDs.popTrigger
}
);

styleIt(elem, this.Styles.styleQuickBorder);
var thisRef = this;
var action = function(){
thisRef.togglePopup();
};

elem.onclick = action;
}
catch(ex){
alert('err: ' + ex.message)
}
return makeElem("div");
},

_buildSelectedUIDOM: function(person){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

var imgSrc = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
var name = person.getField(opensocial.Person.Field.NAME);

var imgOpts = {id:"__selectedFriendImage", 
src:imgSrc, 
align:"top"};

var imgStyle = "height:65px;margin-right:10px;";
if(this._isIE){
imgStyle += "width:60px;"
imgOpts.width = "60";
imgOpts.height = "65";
}
imgOpts.style=imgStyle;


var elem = makeElem("div",
[
makeElem("img", null, imgOpts),
makeElem("span", name, {id:"__selectedFriendName", style: "margin-left:2px;width:140px;overflow:hidden;"})] );
var thisRef = this;
elem.onclick = function(){
thisRef.togglePopup();
};

return elem;
},

_buildToolbarDOM: function(){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

var prevLink = this._buttonElem_Prev();
var nextLink = this._buttonElem_Next();
var gridLink = this._buttonElem_DisplayGrid();
var listLink = this._buttonElem_DisplayList();
var closeLink = this._buttonElem_Close();


var pgLabel = makeElem("span", null, {id: this.ElementIDs.pagingLabel, style:"font-size:13px;"});

var toolbar;

toolbar = makeElem("div",
[prevLink,
"  ",
pgLabel,
"  ",
nextLink
],
{style: "padding:2px"}
);
$(toolbar).setStyle({
	
	padding:'2px'
	
});
return toolbar;
},
_buttonElem_Image: function(source, imgWidth, imgHeight, text, action){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;

var opts = {
src: source,
width: imgWidth,
height: imgHeight,
alt: text,
title: text
}

var img = makeElem("img", null, opts);

return this._buttonElem_Generic(img, action);
},

_buttonElem_Generic: function(face, action){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;

var button = makeElem("button", face, {style:"width:26px;padding:0;height:20px;"});

if(action){
button.onclick = action;
}
return button;
},

_buttonElem_Close: function(){
var thisRef = this;

var action = function(){
thisRef.popDown();
};
var btn = this._buttonElem_Image(this.Icons.close, 16, 16, "close", action);
btn.setAttribute("title", "Close");
return btn;
},
_buttonElem_Next: function(){
var thisRef = this;

var action = function(){
thisRef.nextPage();
};
var btn = this._buttonElem_Image(this.Icons.next, 16, 16, "next", action);
btn.setAttribute("title", "Next");
return btn;
},
_buttonElem_Prev: function(){
var thisRef = this;

var action = function(){
thisRef.prevPage();
};
var btn = this._buttonElem_Image(this.Icons.prev, 16, 16, "previous", action);
btn.setAttribute("title", "Prev");
return btn;
},

_buttonElem_DisplayGrid: function(){
var thisRef = this;

var action = function(){
alert('Grid display not implemented');
};
var btn = this._buttonElem_Image(this.Icons.showgrid, 16, 16, "grid display", action);
btn.setAttribute("title", "Grid Display");
return btn;
},
_buttonElem_DisplayList: function(){
var thisRef = this;

var action = function(){
alert('List display already active');
};
var btn = this._buttonElem_Image(this.Icons.showlist, 16, 16, "list display", action);
btn.setAttribute("title", "List Display");
return btn;
},

showSearchResults: function(results, searchString){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var elemID

var sresults = document.getElementById(this.ElementIDs.searchResults);
if(!sresults) return;

while(sresults.hasChildNodes()){
sresults.removeChild(sresults.lastChild);
}

if(results == null || results.length == 0 ){
sresults.style.display="none";
if (this._isIE) {
sresults.style.visibility="hidden";
}

return;
}
var person;
var text;
var id;
var action;
var ediv, action;
var thisRef = this;
var re = new RegExp(searchString, "ig");
for(var i=0; i < results.length; i++){
person = results[i];
id = person.getField(opensocial.Person.Field.ID)
text = person.getField(opensocial.Person.Field.NAME);
text = text.replace(re, "<b>" + searchString + "</b>");
action = function(){
var myid;
if (thisRef._isIE) {
var thisElem;
if(window.event && window.event.srcElement){
myid = window.event.srcElement.getAttribute("personid");
}
}
else{
myid = this.getAttribute("personid");
}				

if(myid == null){
return;
}
thisRef._setSelectedFriend(myid, thisRef);
if(window.event){
window.event.cancelBubble = true;
}
thisRef.showSearchResults(null, ''); //clear results window
var sw = document.getElementById(thisRef.ElementIDs.searchBox);
if(sw){
sw.value = "";
}
return false;
};

ediv = makeElem("div", 
makeElem("a", text, {
href: "#",
style: "text-decoration:none;color:#333;",
onclick: "return false",
personid: id
}),
{
style: "margin-bottom:3px;border-top:1px solid #777;",
personid: id
}	
)
MyOpenSpace.Widgets.Utility.safeAttachEvent(ediv, "click", action);

sresults.appendChild(ediv);
}		

sresults.style.display="block";
if (this._isIE) {
sresults.style.visibility="visible";
}
},

drawFriendsPage: function(pageNum){
this.currentPage = Math.max(0, Math.min(pageNum, this.pageCount()));
if (!this._DOMBuilt) {
this._buildDOM();
}
while (this._friendDisplayElem.hasChildNodes()) {
this._friendDisplayElem.removeChild(this._friendDisplayElem.lastChild);
}

var thisPerson;
var startPos = Math.min(this.friendsCatalog._pagingFriends.length-1, ((pageNum * this.pageSize) - this.pageSize));
var endPos = Math.min(this.friendsCatalog._pagingFriends.length-1, ((pageNum * this.pageSize)-1));
startPos = Math.max(0, startPos);
for(var i=startPos;i <= endPos; i++){
thisPerson = this.friendsCatalog._pagingFriends[i];
this._friendDisplayElem.appendChild(this._getFriendDOM(thisPerson));
}

var lbl = document.getElementById(this.ElementIDs.pagingLabel);
if(lbl){
lbl.innerHTML = "Page " + this.currentPage + " of " + (this.pageCount());
}
},

pageCount: function(){
var pages = Math.floor(this.friendsCatalog._pagingFriends.length / this.pageSize);
if(this.friendsCatalog._pagingFriends.length % this.pageSize > 0){
pages++;
}
return pages;
},

_setLoadingMessageDisplay: function(visible){
var elem = document.getElementById("__pickerLoadingDiv");
if(elem){
if(visible){
elem.display="block";
}
else{
elem.disabled="none";
}
} 
},

togglePopup: function(){
if(!this.popupIsOpen){
this.popUp();
}
else{
this.popDown();
this.popupIsOpen = false;
}
},

popUp: function(){
if(!this.dataLoaded){
var thisRef = this;
this._setLoadingMessageDisplay(true);
if(++this._popupRetries < this.MAX_RETRIES){
window.setTimeout(function(){
thisRef.popUp();
}, 250);
return;
}
else{

var msg = "Time loading friends.\nContinue waiting?"
if(confirm(msg)){
this._popupRetries = 0;
this.popUp();
}
}

}
this.drawFriendsPage(this.currentPage);
if(this.popupWindow){
this.popupWindow.style.display="block"
if(this.popupX > 0){
this.popupWindow.style.left = this.popupX;
this.popupWindow.style.top = this.popupY;
}
}
this.popupIsOpen = true;
var searchBox = document.getElementById(this.ElementIDs.searchBox);
if(searchBox){
}
if(window.event){
window.event.cancelBubble = true;
}
},

popDown: function(){
if(this.popupWindow){
this.popupWindow.style.display="none"
}
this.popupIsOpen = false;
},

_setSelectedFriend: function(person){

if(typeof(person) === "string"){
person = this.friendsCatalog.getFriend(person);
}

this.selectedFriend = person;
if(this.buildSelectedUI){
var elem = document.getElementById("__selectedFriendDiv");
if(elem){
while(elem.hasChildNodes()){
elem.removeChild(elem.lastChild);
}
elem.appendChild(this._buildSelectedUIDOM(person));
}
}
var selElem = document.getElementById(this.ElementIDs.popTrigger);
if(selElem){
selElem.style.display="none";
}
this.popDown();
if(this.friendClickAction){
if (typeof(this.friendClickAction) == "function") {
this.friendClickAction(person);
}
else if (typeof(this.friendClickAction) == "String") {
try{
window.eval(this.friendClickAction+"(" + person + ")");
}
catch(ex){}
}
}

},

_getFriendDOM: function(person){
var makeElem = MyOpenSpace.Widgets.Utility.domElement;
var styleIt = MyOpenSpace.Widgets.Utility.applyInlineStyle;			

if (person == null || !person.getField) {
return this._emptyNode;
}

var id = person.getField(opensocial.Person.Field.ID);
var name = person.getField(opensocial.Person.Field.NAME);
var cleanName = name;
if (cleanName) {
re = /"/g
cleanName = cleanName.replace(re, "'");
}
var keyId = person.getField(opensocial.Person.Field.ID);
var imgBucket = makeElem("span",
[
makeElem("span", 
this._getFriendThumbnail(person), {style:"width:70px;text-align:left;"}),
makeElem("span", name)
],
{friendid:id});

var stuff = makeElem("div", imgBucket);
styleIt(imgBucket, this.Styles.styleFriendPickImageBlock);
styleIt(stuff, this.Styles.styleFriendPickBlock);
$(stuff).setStyle({
	'float':'left',
	'backgroundColor':'#eeeeee',
	'width': '170px'
	
});
styleIt(stuff, {cursor:"pointer"})
var funcs = new Array();
var thisRef = this;

stuff.onclick=function(){
thisRef._setSelectedFriend(person);
};

return stuff;
},

_getFriendThumbnail: function(person){
if (person == null) {
return this._emptyNode;
}

var src = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
if (src == null) 
return this._emptyNode;

var cleanName = person.getField(opensocial.Person.Field.NAME);
if (cleanName) {
re = /"/g
cleanName = cleanName.replace(re, "'");
}

var imgStyle = "height:40px;margin-right:10px;";
if(this._isIE){
imgStyle += "width:40px;"
}

var img = document.createElement("img");
img.setAttribute("src", src);
img.setAttribute("alt", "Picture of " + cleanName);
img.setAttribute("align", "middle");
img.setAttribute("style", imgStyle)
img.setAttribute("height", "40");
if (this._isIE) {
img.setAttribute("width", "40");
}
return img;
},

goToPage: function(pageNum){
var maxPages = this.pageCount();
if (pageNum < 1){
alert('At first page')
pageNum = 1;
}
else if(pageNum > maxPages){
alert('At last page')
pageNum = maxPages;
}			

this.drawFriendsPage(pageNum);
},

loadData: function(){
if(this.dataLoaded){
this._friendsData = null;
this.friendMap = new Array();
}
this._loadOpenSocialFriends();
},

personSelected: function(personID){
var person = this.friendMap[personID];
var name = person.getField(opensocial.Person.Field.NAME);
alert('You clicked on ' + name);
},

nextPage: function(){
this.goToPage(this.currentPage+1);		
},	
prevPage: function(){
this.goToPage(this.currentPage-1);		
},	
firstPage: function(){
this.goToPage(1);
},	
lastPage: function(){
this.goToPage(99);
},

initialize: function(args){
var element = null;
if(!args){ return;}
if(typeof(args)== 'string'){
element = args;
}

element = args.element;
this.friendClickAction = args.friendClickAction;
this.buildSelectedUI = args.buildSelectedUI;

if (typeof(element) == 'string') {
this.DOMElement = document.getElementById(element);
}
else {
this.DOMElement = element;
}
this.loadData();
this._buildDOM();
}
};