var ContentChains = {
        NOT_LOGGED:0,MANUAL_FORWARD:1,RECOMMENDATIONS_AREA:2,FEATURED:3, PROFILE:4,TAGS:5, SHARING: 6, FRIEND_UPDATES: 7, FEEDS: 8, MY_CONTENT:9 };


function PhotoAlbum(jsonObj)
{
    this.items = [];
    this.itemsSparse = [];
    for (var i =0; i < jsonObj['items'].length; i++)
    {
        var pContentItem = new ContentItem(jsonObj['items'][i]);
        this.items.push(pContentItem);
        this.itemsSparse[pContentItem['pid']] = i;
    }
    this.currentActive = 0;
}

PhotoAlbum.prototype.renderContentArea = function()
{
    var pDiv = new Element('div', {className:'imageViewer'});
    var pSpacer = new Element('img',{src:'/images/blank.gif', style:'height:600px; width:2px; visiblity:hidden'}) 
    pDiv.insert(pSpacer);
    for (var i = 0; i < this.items.length; i++)
    {
        var pImg = new Element('img', {style:'display:none', 'ripl:contentid':this.items[i].pid, 'src':this.items[i].preview_image_url, id:'i_' + this.items[i].pid }) 
        var pStr = ''; 
          
        pDiv.insert(pImg); 
    }
    return pDiv;
}
PhotoAlbum.prototype.getIndexFromPid = function(pid)
{
    return this.itemsSparse[pid] + 1;
}
PhotoAlbum.prototype.renderBar = function()
{
    var pDiv = new Element('div', {className:'tabbed_image_container', width:'100%'});
    var pUl = new Element('ul',{className:'tabbed_images', id:'photo_tabs'});
    for (var i = 0; i < this.items.length; i++)
    {
        var pLi = new Element('li');
        var pA = new Element('a',{'href':'#i_' + this.items[i].pid});
        var pImg = this.items[i].getContentImage();
        pA.update(pImg);
        pLi.update(pA); 
        pUl.insert(pLi);
    }
    pDiv.insert(pUl);
    return pDiv;
};





function Feed(jsonObj)
{
    this.feedItems = [];
    for (var i =0; i < jsonObj['content'].length; i++)
    {
        var pContentItem = new ContentItem(jsonObj['content'][i]);
    }
    for (var i =0; i < jsonObj['users'].length; i++)
    {
        var pUserItem = new User(jsonObj['users'][i]);
    }
    for (var i =0; i < jsonObj['feedItems'].length; i++)
    {
        var pFeedItem = new FeedItem(jsonObj['feedItems'][i]);
        for (var j =0; j < jsonObj['content'].length; j++)
        {
            if (jsonObj['content'][j]['pid'] == pFeedItem.contentId)
            {
                pFeedItem.contentObject = new ContentItem(jsonObj['content'][j]);
                break;
            }
        }
        this.feedItems.push(pFeedItem);
    }
}
Feed.prototype.render = function(areaName,displayStyle)
{
    var pDiv = new Element('div',{style:'width:100%'});
    for (var i = 0; i < this.feedItems.length; i++)
    {
        try
        {
            var pitem = this.feedItems[i].getContentDomObj(displayStyle);
            pDiv.insert(pitem);
        }
        catch (e)
        {
        	try{log.error('content:82: '+e);}catch(e){}
        }
    }
    $(areaName).update(pDiv);
};

function FeedItem(jsonObj)
{
    this.itemType = jsonObj['item_type'];
    this.contentObject;
    this.actionTime = parseInt(jsonObj['action_time'],10);
    this.actionType = jsonObj['action_type'];
    this.contentId = jsonObj['content_id'];
    this.ownerId = jsonObj['owner_id'];
    this.actorId = jsonObj['actor_id'];
    this.count = jsonObj['item_count'];
    this.rating = jsonObj['rating'];
    this.domObj = null;
    this.chain = ContentChains.NOT_LOGGED;
}
FeedItem.prototype.clear = function()
{
    this.domObj = null;
}
FeedItem.actionIcons = {'added':'/images/action_add.png', 'favorited':'/images/action_favorite.png', 'rated':'/images/action_rate.png','commented':'/images/action_comment.png', 'shared':'/images/action_share.png', 'tagged':'/images/action_tag.png' }

FeedItem.prototype.getContentDomObj = function(displayStyle)
{
    switch (displayStyle)
    {        
        case $contentHelpers.outputFormats.INLINE:
//            pContent = ContentItem.getById(this.contentId);
            this.contentObject.chain = this.chain;
//            pContent.chain = this.chain;
            return this.contentObject.getContentDomObj();
//            return ContentItem.getById(this.contentId).getContentDomObj();
            break;
        case $contentHelpers.outputFormats.CARDS:
            if (this.itemType == 'friendFeed') return this.getFriendFeedCard();
            else  return this.getFeedCard();
          //  ContentItem.getById(this.contentId).getContentCard();
            break;
        case $contentHelpers.outputFormats.TEXT:
            return this.getFeedText();
            break;
        case $contentHelpers.outputFormats.PROFILE_TEXT:
            return this.getProfileFeedText();
            break;
    }
}

FeedItem.prototype.getFriendFeedIndicator = function()
{
    var pContentItem = this.contentObject;//ContentItem.getById(this.contentId);
    pContentItem.chain = this.chain;
    
    var pUserItem = User.getById(this.actorId);    
    var pContainer = new Element('div',{style:'display:inline-block; width:184px; height:104px'});
    var pDiv = new Element('div',{'style':'display:inline-block;position:absolute;'});
    try
    {
        pDiv.update(pUserItem.getUserDomObj());
        var pObj = pContentItem.getContentDomObj();
        pObj.style.position= "relative";
        pObj.style.left = "6px"
        pDiv.insert(pObj);
    }
    catch (e){
    	return false;
    }
//    var pOverlay = new Element('div', {'style':'width:178px; height:104px;display:inline-block; position:absolute;'});
    var pImg = new Element('img',{src:FeedItem.actionIcons[this.actionType], 'style':'position:relative; top:36px; left:76px'});
//    pOverlay.update(pImg);
    pContainer.update(pDiv);
    pContainer.insert(pImg);
    return pContainer;
}


FeedItem.prototype.getFriendFeedCard = function()
{
    
    var pContentItem = this.contentObject;//ContentItem.getById(this.contentId);
    pContentItem.chain = this.chain;
    
    var pUserItem = User.getById(this.actorId);
    var pDiv = new Element('div',{className:'FFCardBox'});
    var indicator = this.getFriendFeedIndicator();
    if(!indicator) return;//	return new Element('div',{});
//    pDiv.update(indicator);

    
    var pTable = new Element('table');
    var pTBody = new Element('tbody');
    var pTr = new Element('tr');
    var pTdLeft = new Element('td');
    var pTdRight = new Element('td',{className:'FFCardInfo'});
    pTdLeft.update(indicator);
//    var pTextCell = new Element('div',{className:'CardInfo'});
    var pTitle = pContentItem.getAnchor();
    pTitle.className = 'FFCardTitle';
    pTitle.update(pContentItem.title);
    pTextCellData = '<br />';
    if (this.base_type == 'Music')
    {
        pTextCellData += pContentItem.artist;
        pTextCellData += '<br />';
        pTextCellData += pContentItem.album;
        pTextCellData += '<br />';
    }
    pTextCellData += '<div class="CardUpdated">'+this.actionType + ' ' + new Date(this.actionTime * 1000).format(Date.TIME_SINCE)+ '</div>';
    if (this.actionType=='added' && pContentItem.provider_id!='Ripl' && pContentItem.provider_id!=''){ pTextCellData += ' (through '+ pContentItem.provider_id + ' )';}
    pTextCellData += '<br />';

    pTdRight.update(pTitle);
    pTdRight.insert(pTextCellData);
    
    try
    {
        var pUserName = pUserItem.getAnchor();
        pUserName.update(pUserItem.displayName);
        pTdRight.insert('<span>by </span>');
        pTdRight.insert(pUserName);
    }
    catch (e)
    {}
    pTr.insert(pTdLeft);
    pTr.insert(pTdRight);
    pTBody.insert(pTr);
    pTable.insert(pTBody)
//    pDiv.insert(pTextCell);
   
    return pTable;
}

FeedItem.prototype.getFeedCard = function()
{
    var pContentItem = this.contentObject;//ContentItem.getById(this.contentId);
    pContentItem.chain = this.chain;
    var pUserItem;
    if (this.itemType == 'friendFeed')
    {
        pUserItem = User.getById(this.actorId);
    }
    else
    {
        pUserItem = User.getById(this.ownerId);
    }    
  
        
    var pDiv = new Element('div',{className:'CardBox'});
    pDiv.update(pContentItem.getContentDomObj());
    var pTextCell = new Element('div',{className:'CardInfo'});
    var pTitle = pContentItem.getAnchor();
    pTitle.className = 'CardTitle';
    pTitle.update(pContentItem.title);
    pTextCellData = '';
    if (this.base_type == 'Music')
    {
        pTextCellData += pContentItem.artist;
        pTextCellData += '<br />';
        pTextCellData += pContentItem.album;
        pTextCellData += '<br />';
    }
    if (this.itemType=='friendFeed')
    {
        pTextCellData += '<div class="CardUpdated">'+this.actionType + ' ' + new Date(this.actionTime * 1000).format(Date.TIME_SINCE)+ '</div>';
        if (this.actionType=='added' && pContentItem.provider_id!='Ripl' && pContentItem.provider_id!=''){ pTextCellData += ' (through '+ pContentItem.provider_id + ' )';}
        pTextCellData += '<br />';
    }    
    else if (this.itemType=='newest')
    {
        pTextCellData += '<div class="CardUpdated">added ' + new Date(this.actionTime * 1000).format(Date.TIME_SINCE)+ '</div>';
        if (pContentItem.provider_id != 'Ripl' && pContentItem.provider_id!=''){ pTextCellData += ' (through '+ pContentItem.provider_id + ' )';}
        pTextCellData += '<br />';
    }
    else
    {
        if (this.itemType == 'popular')
        {
            pTextCellData += ' ( ' + this.count + ' views )<br /><br />';
        }        
        pTextCellData += 'added ';
        
    }
    pTextCell.update(pTitle);
    pTextCell.insert(pTextCellData);
    
    try
    {
        var pUserName = pUserItem.getAnchor();
        pUserName.update(pUserItem.displayName);
        pTextCell.insert('<span>by </span>');
        pTextCell.insert(pUserName);
    }
    catch (e)
    {}
    
    pDiv.insert(pTextCell);
   
    return pDiv;
}



FeedItem.prototype.getFeedText = function()
{
    var pDiv = new Element('div', {className:'contentRowUpdated'});
    var pContentItem = this.contentObject;//ContentItem.getById(this.contentId);
    pContentItem.chain = this.chain;
    if (this.itemType =='friendFeed') pContentItem.referer = this.actorId;
    
    if (pContentItem == null) return;
    var pUserItem;
    if (this.itemType == 'friendFeed')
    {
        pUserItem = User.getById(this.actorId);
        
        var pUserName = pUserItem.getAnchor();
        pUserName.update(pUserItem.displayName);
        pDiv.update(pUserName);
        pDiv.insert(' ' + this.actionType + ' ');
    }
    else
    {
        pUserItem = User.getById(this.ownerId);
    }
    
    var pTitle = pContentItem.getAnchor();
    pTitle.update(pContentItem.title);
    pDiv.insert(pTitle);
    
    if (this.itemType == 'friendFeed')
    {
        pTextCellData = ' ' + new Date(this.actionTime * 1000).format(Date.TIME_SINCE);
        if ((this.actionType == 'added') && (pContentItem.provider_id != 'Ripl'))
        { 
            pTextCellData += ' (through '+ pContentItem.provider_id + ')</span>';
        }
        pDiv.insert(pTextCellData);  
    }
    else if (this.itemType == 'popular')
    {
        pDiv.insert( ' ( ' + this.count + ' views )');
    }
    else
    {
        pDiv.insert(' - added by ');
        try
        {
            var pUserName = pUserItem.getAnchor();
            pUserName.update(pUserItem.displayName);
            pDiv.insert(pUserName);
            pDiv.insert(pTextCellData);  
            
        }
        catch (e)
        {
        }
    }

    /*
    else
    {
        pTextCellData = ' ' + new Date(this.actionTime * 1000).format(Date.TIME_SINCE);
        if (pContentItem.provider_id != 'Ripl'){ pTextCellData += ' through '+ pContentItem.provider_id + ' </span>';}
        pDiv.insert(pTextCellData);          
    }
*/
    return pDiv;
}


FeedItem.prototype.getProfileFeedText = function()
{
    var pDiv = new Element('div', {className:'contentRowUpdated'});
    var pContentItem = this.contentObject;//ContentItem.getById(this.contentId);
    pContentItem.chain = this.chain;
    
    var pUserItem;
    pDiv.insert(this.actionType + " ");

    var pTitle = pContentItem.getAnchor();
    pTitle.update(pContentItem.title);
    pDiv.insert(pTitle);


    pTextCellData = ' ' + new Date(this.actionTime * 1000).format(Date.TIME_SINCE);
    if (((this.actionType == 'added') && (this.provider_id != 'Ripl')) && (this.provider_id != undefined)){ pTextCellData += ' (through '+ this.provider_id + ')</span>';}
    pDiv.insert(pTextCellData);  


    return pDiv;
}





var EventHandler = {};
EventHandler.addEventListener = function(eventName,closure)
{
    var pEvent = {'event':eventName, 'closure':closure};
    this.eventListeners.push(pEvent);
}
EventHandler.removeEventListener = function(eventName,closure)
{
    for (var i=0; i < this.eventListeners.length; i++)
    {
        var pEvtObj = this.eventListeners[i];
        if ((pEvtObj.event == eventName) && (pEvtObj.closure == closure))
        {
            this.eventListeners.splice(i,1);
        }
    }
}
EventHandler.checkEventListeners = function(eventName,data)
{
    for (var i=0; i < this.eventListeners.length; i++)
    {
        if (this.eventListeners[i].event == eventName)
        {
            this.eventListeners[i].closure.call(this,data);
        }
    }
}



function FeedParameters(inParameters,inOptions)
{
    this.parameters = Object.extend({
            uid:0,
            feedType:'friendFeed',
            userSel:'u1',
            ownerSel:'u3',
            showOwner:true,
            itemCount:48,
            showOwnerActions:true,
            contentSel:"Video,Music,Photo,Blog",
            contentActionSel:'added,rated,viewed,favorited,commented,shared',
            format:'json'
        },inParameters || {});
    this.parameters.options = Object.extend({
        title:'Custom Feed',
        renderTarget:null,
        targetStyle:$contentHelpers.outputFormats.INLINE,
        targetClosure:null,
        targetDataKey:null,
        itemsPerPage:48,
        typeFilters:['Video','Photo','Blog','Music'],
       displayTypeSelector:false,
       chain:ContentChains.NOT_LOGGED,
       sortKey:'age',
       sortReverse:false,
       referer:-1,
       currentPageNumber:1
              
    },inOptions || {})
 //   alert(printObj(this.parameters.options));

}
FeedParameters.STANDARD_NEW_FROM_FRIENDS = 'fpmNewFriends';
FeedParameters.STANDARD_NEW_ON_RIPL = 'fpmNewRipl';
FeedParameters.STANDARD_POPULAR = 'fpmPopular';
FeedParameters.STANDARD_SUBSCRIPTION = 'fpmSubscription';

FeedParameters.getNamedSet = function(feedId,inOptions)
{
    var options;
    switch(feedId)
    {
        case FeedParameters.STANDARD_NEW_FROM_FRIENDS:
            options = Object.extend({title:'Newest Activity from those You\'re Following'},inOptions || {});
            return new FeedParameters({feedType:'newest'},options);
        case FeedParameters.STANDARD_NEW_ON_RIPL:
            options = Object.extend({title:'Newest Content on RIPL'},inOptions || {});
            return new FeedParameters({feedType:'newest',userSel:'u3'},options); 
        case FeedParameters.STANDARD_POPULAR:
            options = Object.extend({title:'Popular Content on RIPL'},inOptions || {});
            return new FeedParameters({feedType:'popular',userSel:'u3'},options);
        case FeedParameters.STANDARD_SUBSCRIPTION:
        default:  // explicit fall-through
            options = Object.extend({title:'Recent Activity from Followings'},inOptions || {});
            return new FeedParameters({feedType:'friendFeed'},options);
    }
}
FeedParameters.getFromObject = function(inObject)
{
    
}


function FeedList(inOptions)
{
    this._rawItems = [];
    this._availableItems = [];
    
    this._userItems = new UserList();
    this._contentItems = new ContentList();
    
    this.renderTarget = null;
//!
    this.targetStyle = $contentHelpers.outputFormats.INLINE;
    this.targetClosure = null;
    this.targetDataKey = null;

    this.typeFilters = ['Video','Photo','Blog','Music'];
    

    this.sortKey = 'age';
    this.sortReverse = false;
    
    this.chain = ContentChains.NOT_LOGGED;
    
    this.itemsPerPage = 49;
    
    this.dirty = true;
    this.sortDirty = true;
    this.eventListeners = [];    

    this.options = Object.extend({
        title:'',
        renderTarget:null,
        targetStyle:$contentHelpers.outputFormats.INLINE,
        targetClosure:null,
        targetDataKey:null,
        itemsPerPage:48,
        typeFilters:['Video','Photo','Blog','Music'],
       displayTypeSelector:false,
       chain:ContentChains.NOT_LOGGED,
       sortKey:'age',
       sortReverse:false,
       referer:-1,
       currentPageNumber:1,
       padding:'',
       noItems:'No items were found'
              
    },inOptions || {});
    
    
}

FeedList.prototype.addEventListener = EventHandler.addEventListener;
FeedList.prototype.removeEventListener = EventHandler.removeEventListener;
FeedList.prototype.checkEventListeners = EventHandler.checkEventListeners;


FeedList.prototype.getCount = function()
{
    return this._availableItems.length;
}

FeedList.prototype.clear = function(renderNow)
{
    this.dirty = true;
    this._rawItems = [];
    this._userItems.clear();
    this._contentItems.clear();
    if (renderNow) this.render();
}

FeedList._ageSort = function(a,b)
{
    var pRetVal = 0;
    b = (b['actionTime']) ? parseInt(b['actionTime'],10) : 0;
    a = (a['actionTime']) ? parseInt(a['actionTime'],10) : 0;
    return b-a;
    return pRetVal;
}
FeedList._alphaTitle = function(a,b)
{
    var pRetVal = 0;
    a = this._contentItems.getItemById(a.contentId).title.toLowerCase(); b = this._contentItems.getItemById(b.contentId).title.toLowerCase();
    if (a>b) pRetVal = 1;
    if (a <b) pRetVal = -1;
    return pRetVal;    
}

FeedList.prototype.setSortKey = function(sortKey, renderNow)
{
    this.options.sortKey = sortKey;
    this.sortDirty = true;
    if (renderNow) this.render();
}
FeedList.prototype.setSortReverse = function(sortReverse, renderNow)
{
    this.options.sortReverse = sortReverse;
    this.sortDirty = true;
    if (renderNow) this.render();
}
FeedList.prototype.toggleSortOrder = function(renderNow)
{
    
    this.options.sortReverse = !this.sortReverse;
    this.sortDirty = true;
    if (renderNow) this.render();
}

FeedList.prototype.setTargetStyle = function(e,newStyle,renderNow)
{
    this.options.targetStyle = newStyle;
    if (renderNow) this.render();
    this.checkEventListeners('targetStyle_change');
}

FeedList.prototype._sort = function()
{
    var pSortFunction = FeedList._ageSort;
    switch (this.options.sortKey)
    {
        case 'title':
            pSortFunction = FeedList._alphaTitle;
            break;
        case 'age':
        default:
            pSortFunction = FeedList._ageSort;
    }
    this._availableItems = this._availableItems.sort(pSortFunction);
    if (this.options.sortReverse) this._availableItems.reverse();
    this.dirty = false;    
}
FeedList.prototype.addRawData = function(rawData)
{
    this._contentItems.addObjects(rawData['content']);
    this._userItems.addObjects(rawData['users']);
    this.addObjects(rawData['feedItems'],rawData['content']);
}

FeedList.prototype.addObject = function(feedObject,rawContent)
{
    var pItem = new FeedItem(feedObject);
    for (var i=0; i < rawContent.length; i++)
    {
       if (rawContent[i].pid == pItem.contentId)
       {
           pItem.contentObject = new ContentItem(rawContent[i]);
           this.addItem(pItem);
           break;
       }
    }
}
FeedList.prototype.addObjects = function(feedArr,rawContent)
{
    for (var i = 0; i < feedArr.length; i++)
    {
        this.addObject(feedArr[i],rawContent);
    }
}
FeedList.prototype.addItem = function(feedItem,rawContent)
{
    this.dirty = true;
    var pContent = feedItem.contentObject;
//    var pContent = this._contentItems.getItemById(feedItem.contentId);
    var pChain = this.getChain(feedItem.itemType);
    pContent.chain = pChain;
    pContent.referer = (feedItem.actorId >0) ? feedItem.actorId : 0;
    this.options.chain = pChain;
    this._contentItems.chain= pChain;
    feedItem.chain = pChain;
    if (!this._rawItems.inArray(feedItem))
    {
        this._rawItems.push(feedItem);
    }
}
FeedList.prototype.addItems = function(feedItemArr,rawContent)
{
    for (var i = 0; i < feedItemArr.length; i++)
    {
        this.addItem(feedItemArr[i],rawContent);
    }
}

FeedList.prototype.removeItemById = function(index)
{
    this.dirty = true;
    for (var i = this._rawItems.length - 1; i >=0; i--)
    {
        if (this._rawItems[i].id == index)
        {
            return this._rawItems.splice(i,1)[0];
        }
    }
    return false;
}


FeedList.prototype.getChain = function(typeKey)
{
    switch (typeKey)
    {
        case 'newest':
        case 'highestRated':
        case 'list':
        case 'user_newest':
        case 'user_favorites':
        case 'popular':
            return ContentChains.FEEDS;
        case 'recommended':
            return ContentChains.RECOMMENDATIONS_AREA; 
        case 'friendFeed':
        case 'interactions':
            return ContentChains.FRIEND_UPDATES;
        default:
            return ContentChains.UNKNOWN;
                
    }
}
FeedList.prototype.setTypeFilters = function()
{
    
}
FeedList.prototype.goToPage = function(e,pageNumber)
{
    this.options.currentPageNumber = pageNumber;
    this.render();
}

FeedList.prototype.renderTo = function(location)
{
    this.options.renderTarget = $(location);
    this.render();
}

FeedList.prototype._filterList = function()
{
    var retList = [];
    for (var i = 0; i < this._rawItems.length; i++)
    {
        var pItem = this._rawItems[i];
        if ((pItem.contentObject) &&(this.options.typeFilters.inArraySubstring(pItem.contentObject.base_type)))
        {
            retList.push(pItem);
        }
        
    }
    this._availableItems = retList;
    this.dirty = false;
    this._sort();
    
    // stubbed
//    this._availableItems = [].concat(this._rawItems);
//    this._sort();
}

FeedList.prototype.render = function()
{

    if (this.dirty)
    {
        this._filterList();
    }
    else if (this.sortDirty)
    {
        this._sort();
    }
    var pLen = this._availableItems.length;

    var pDiv = new Element('div',{style:'width:100%'});
    
    var pTopBar = new Element('table',{'style':'width:100%;padding:'+this.options.padding});
    var pTopBarBody = new Element('tbody');
    var pTopBarTr = new Element('tr');
    var pTopBarTdLeft = new Element('td',{className:'contentHeader'});
    var pTopBarTdRight = new Element('td',{'style':'text-align:right'});    
    pTopBarTdRight.update(this.getStyleChanger());
    pTopBarTdLeft.update(this.title);

    pTopBarTr.insert(pTopBarTdLeft);
    pTopBarTr.insert(pTopBarTdRight);
    pTopBarBody.insert(pTopBarTr);
    pTopBar.insert(pTopBarBody);
    
    pDiv.update(pTopBar);
    if (pLen == 0) 
    {
        pDiv.insert(this.options.noItems);
    }
    else
    {    

    
        var pStart = (this.options.currentPageNumber -1) * this.options.itemsPerPage;
        var pMax = Math.min(pStart + this.options.itemsPerPage, pLen);

        for (var i = pStart; i < pMax; i++)
        {
            this._availableItems[i].chain = this.options.chain;
            pDiv.insert(this._availableItems[i].getContentDomObj(this.options.targetStyle));
        }
        
        if (pStart > pMax)
        {
            this.options.currentPageNumber = Math.ceil(pMax / this.options.itemsPerPage);
            pStart = (this.options.currentPageNumber -1) * this.options.itemsPerPage;
            pMax = Math.min(pStart + this.options.itemsPerPage, pLen);
        }
        
        if (this.itemsPerPage <= 0)
        {
            pStart = 0;
            pMax = pLen;
        }
        if (pStart > pMax) pStart = pMax;
    

    
        var pBottomBar = new Element('table',{'style':'width:100%'});
        var pBottomBarBody = new Element('tbody');
        var pBottomBarTr = new Element('tr');
        var pBottomBarTdLeft = new Element('td');
        var pBottomBarTdRight = new Element('td',{'style':'text-align:right'});
    
        
        if (this.options.displayTypeSelector)
        {
            pBottomBarTdLeft.update(this.getTypeSelector());
        }
        if ((this.options.itemsPerPage < pLen) && (this.options.itemsPerPage > 0))
        {
            pBottomBarTdRight.update(this.getPageChanger());
        }
        pBottomBarTr.insert(pBottomBarTdLeft);
        pBottomBarTr.insert(pBottomBarTdRight);
        pBottomBarBody.insert(pBottomBarTr);
        pBottomBar.insert(pBottomBarBody);
        pDiv.insert('<br class="clearBoth" />');
        pDiv.insert(pBottomBar);    
    }
    this.options.renderTarget.update(pDiv);    
}
FeedList.prototype.getStyleChanger = function()
{
    var pStyleChanger = new Element("div",{'style':'text-align:right'});    
    var pGrid = new Element('img',{
                    'src':(this.targetStyle==1)?'/images/layout_icon_grid_down.png' : '/images/layout_icon_grid.png',
                    'title':'show as grid',
                    'className':'threeStateButton',
                    'ripl:src':'images/layout_icon_grid.png',
                    'ripl:hover':'images/layout_icon_grid_hover.png',
                    'ripl:down':'images/layout_icon_grid_down.png',
                    'ripl:value':1,
                    'ripl:state':(this.options.targetStyle==1) ? 'down' : 'up'
                });
    var pCard = new Element('img',{
        'src':(this.targetStyle==0) ? '/images/layout_icon_card_down.png' : '/images/layout_icon_card.png',
        'title':'show as grid',
        'className':'threeStateButton',
        'ripl:src':'/images/layout_icon_card.png',
        'ripl:hover':'/images/layout_icon_card_hover.png',
        'ripl:down':'/images/layout_icon_card_down.png',
        'ripl:value':0,
        'ripl:state':(this.options.targetStyle==0) ? 'down' : 'up'
            
    }); 
    var pText = new Element('img',{
        'src':(this.targetStyle==0) ? '/images/layout_icon_text_down.png' : '/images/layout_icon_text.png',
        'title':'show as grid',
        'className':'threeStateButton',
        'ripl:src':'/images/layout_icon_text.png',
        'ripl:hover':'/images/layout_icon_text_hover.png',
        'ripl:down':'/images/layout_icon_text_down.png',
        'ripl:value':2,
        'ripl:state':(this.options.targetStyle==2) ? 'down' : 'up'
    });    
    
    this._bindStyleChangerItem(pGrid);
    this._bindStyleChangerItem(pCard);
    this._bindStyleChangerItem(pText);
    pStyleChanger.update('display: ');
    pStyleChanger.insert(pGrid);
    pStyleChanger.insert(pCard);
    pStyleChanger.insert(pText);
    return pStyleChanger;
}

FeedList.prototype._bindStyleChangerItem = function(el)
{
    el.observe('mouseover',function()
        {
            if (this.readAttribute('ripl:state') == 'up')
            {
                this.src = this.readAttribute('ripl:hover');                    
            }        
        });
    el.observe('mouseover',function()
        {
            if (this.readAttribute('ripl:state') == 'up')
            {
                this.src = this.readAttribute('ripl:src');                    
            }        
        });
    el.observe('click',function()
        {
            var pElements = $$('.threeStateButton');
            for (var i = 0; i < pElements.length; i++)
            {
                pElements[i].src = pElements[i].readAttribute('ripl:src');
                pElements[i].writeAttribute('ripl:state', 'up');
            }
            this.writeAttribute('ripl:state','down');
            this.src = this.readAttribute('ripl:down');
        });
    Event.observe(el, 'click', this.setTargetStyle.bindAsEventListener(this, parseInt(el.readAttribute('ripl:value'),10),true));
}
FeedList.prototype.getTypeSelector = function()
{
    var pPagination = new Element("div",{'style':'font-size:x-small;line-height:20px; white-space: nowrap;padding-top:5px'}).update('content types: ');    
    var pVideoChk = new Element('input',{'id':'chkVideo','type':'checkbox','value':'Video','checked':'checked' })
    var pPhotoChk = new Element('input',{'id':'chkPhoto','type':'checkbox','value':'Photo','checked':'checked' })
    var pMusicChk = new Element('input',{'id':'chkMusic','type':'checkbox','value':'Music','checked':'checked' })
    var pBlogChk = new Element('input',{'id':'chkBlog','type':'checkbox','value':'Blog','checked':'checked' })

    var pVideoLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkVideo'}).insert('Video');
    var pPhotoLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkPhoto'}).insert('Photo');
    var pMusicLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkMusic'}).insert('Music');
    var pBlogLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkBlog'}).insert('Blog &amp; Text');

    pPagination.insert(pVideoChk);
    pPagination.insert(pVideoLabel);
    pPagination.insert(pPhotoChk);
    pPagination.insert(pPhotoLabel);
    pPagination.insert(pMusicChk);
    pPagination.insert(pMusicLabel);
    pPagination.insert(pBlogChk); 
    pPagination.insert(pBlogLabel); 

    Event.observe(pVideoChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    Event.observe(pPhotoChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    Event.observe(pMusicChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    Event.observe(pBlogChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    
    pVideoChk.checked = this.options.typeFilters.inArray('Video');
    pPhotoChk.checked = this.options.typeFilters.inArray('Photo');
    pMusicChk.checked = this.options.typeFilters.inArray('Music');
    pBlogChk.checked = this.options.typeFilters.inArray('Blog');

    return pPagination;
}
FeedList.prototype._typeSelectorChange = function(e)
{
    var pChecked = e.element().checked;
    var pKey = e.element().value;
    var pFilters = [].concat(this.options.typeFilters);
    var pFound = false;
    for (var i =pFilters.length -1; i >=0; i--)
    {
        if (pFilters[i] == pKey)
        {
            pFound = true;
            if (!pChecked)
            {
                pFilters.splice(i,1);
            }
        }
    }
    if ((!pFound) && (pChecked))
    {
        pFilters.push(pKey);
    }
    this.setTypeFilters(pFilters,true);
}

FeedList.prototype.getPageChanger = function()
{
    if (this.options.currentPageNumber < 1) this.options.currentPageNumber = 1;
    
    var pPagination = new Element("div",{'style':'width:100%;text-align:right;height:24px; vertical-align:bottom'});

    var totalPages = Math.ceil(this._availableItems.length/(this.options.itemsPerPage));
    var pageMax = (this.options.currentPageNumber < totalPages) ? false : true;
    var pageMin =(this.options.currentPageNumber != 1) ? false : true;
    var pString = ' page ' + this.options.currentPageNumber + ' of ' + totalPages;
    var pALeft = new Element("a",{style:"cursor:pointer;cursor:hand;"});
    pALeft.update('&lt;&nbsp;prev');
    Event.observe(pALeft, 'click', this.goToPage.bindAsEventListener(this, (this.options.currentPageNumber -1)));
    var pARight = new Element("a",{style:"cursor:pointer;cursor:hand;border:none"});
    pARight.update('next&nbsp;&gt;');
    Event.observe(pARight, 'click', this.goToPage.bindAsEventListener(this, (this.options.currentPageNumber + 1)));
    pPagination.update('&nbsp;page&nbsp;' + this.options.currentPageNumber + '&nbsp;of&nbsp;' + totalPages + '&nbsp;')
    if (!pageMin) pPagination.insert(pALeft);
    if (!pageMin && !pageMax) pPagination.insert('&nbsp;|&nbsp;');
    if (!pageMax) pPagination.insert(pARight);

    return pPagination;
}


var ContentChains = {NOT_LOGGED:0,MANUAL_FORWARD:1,RECOMMENDATIONS_AREA:2,FEATURED:3, PROFILE:4,TAGS:5, SHARING: 6, FRIEND_UPDATES: 7, FEEDS: 8, MY_CONTENT:9 };

function ContentList(inOptions)
{
    this._rawItems = [];
    this._availableItems = [];
    this.eventListeners = [];
    /*      
    this.typeFilters = ['Video','Photo','Blog','Music'];
  
    this.renderTarget = null;
    this.targetStyle = $contentHelpers.outputFormats.INLINE;
    this.targetClosure = null;
    this.targetDataKey = null;

  /*  
    this.sortKey = 'age';
    this.sortReverse = false;
    
    this.chain = ContentChains.NOT_LOGGED;
    this.referer = -1;
    
    this.currentPageNumber = 1;
    this.itemsPerPage = 24;
*/    
    this.dirty = true;
    this.sortDirty = true;
//    this.displayTypeSelector = true;

    
    
    this.options = Object.extend({
        renderTarget:null,
        targetStyle:$contentHelpers.outputFormats.INLINE,
        targetClosure:null,
        mouseover:null,
        targetDataKey:null,
        typeFilters:['Video','Photo','Blog','Music'],
       displayTypeSelector:true,
       chain:ContentChains.NOT_LOGGED,
       sortKey:'age',
       sortReverse:false,
       referer:-1,
       currentPageNumber:1,
       itemsPerPage:24,
       noItems:'No items were found',
       padding:'0'
              
    },inOptions || {});    
    
    
    

}

ContentList.prototype.addEventListener = EventHandler.addEventListener;
ContentList.prototype.removeEventListener = EventHandler.removeEventListener;
ContentList.prototype.checkEventListeners = EventHandler.checkEventListeners;

ContentList.prototype.getIdsAsArray = function()
{
    var pRetVal = [];
    for (var i = 0; i < this._rawItems.length;i++)
    {
        pRetVal.push(this._rawItems[i].pid);
    }
    return pRetVal;
}
ContentList.prototype.getCount = function()
{
    return this._rawItems.length;
}
ContentList.prototype.getAvailableCount = function()
{
    return this._availableItems.length;
}
ContentList.prototype.clear = function(renderNow)
{
    this.dirty = true;
    this._rawItems = [];
    if (renderNow) this.render();
}

ContentList.prototype.getItemById = function(itemId)
{
    for (var i = 0; i < this._rawItems.length; i++)
    {
        if (this._rawItems[i].pid == itemId)
        {
            return this._rawItems[i];
        }
    }
    return false;
}
ContentList._rankSort = function(a,b)
{
    return a.rank-b.rank;
}
ContentList._countSort = function(a,b)
{
    return a.count - b.count;
}

ContentList._ageSort = function(a,b)
{
    var pRetVal = 0;
    return parseInt(b.last_update,10) - parseInt(a.last_update,10);
    return pRetVal;
}
ContentList._ratingSort = function(a,b)
{
    return b.rating - a.rating;
}
ContentList._alphaTitle = function(a,b)
{
    var pRetVal = 0;
    a = a.title.toLowerCase(); 
    b = b.title.toLowerCase();
    if (a>b) pRetVal = 1;
    if (a <b) pRetVal = -1;
    return pRetVal;    
}


ContentList.prototype.setSortKey = function(sortKey, renderNow)
{
    this.options.sortKey = sortKey;
    this.sortDirty = true;
    if (renderNow) this.render();
}
ContentList.prototype.setSortReverse = function(sortReverse, renderNow)
{
    this.options.sortReverse = sortReverse;
    this.sortDirty = true;
    if (renderNow) this.render();
}
ContentList.prototype.toggleSortOrder = function(renderNow)
{
    
    this.options.sortReverse = !this.options.sortReverse;
    this.sortDirty = true;
    if (renderNow) this.render();
}

ContentList.prototype.setTargetStyle = function(e,newStyle,renderNow)
{
    this.options.targetStyle = newStyle;
    if (renderNow) this.render();
    this.checkEventListeners('targetStyle_change');
}

ContentList.prototype._sort = function()
{
    
    var pSortFunction;
    switch (this.options.sortKey)
    {
        case 'title':
            pSortFunction = ContentList._alphaTitle;
            break;
        case 'rating':
            pSortFunction = ContentList._ratingSort;
            break;
        case 'rank':
            pSortFunction = ContentList._rankSort;
        case 'count':
            pSortFunction = ContentList._countSort;
            break;
        case 'age':
        default:
            pSortFunction = ContentList._ageSort;
    }
    this._availableItems = this._availableItems.sort(pSortFunction);
    if (this.options.sortReverse) this._availableItems.reverse();
    this.dirty = false;    
}


ContentList.prototype.addObject = function(contentObj)
{
    pItem = new ContentItem(contentObj);
    this.addItem(pItem);
}
ContentList.prototype.addObjects = function(contentArr)
{
    for (var i = 0; i < contentArr.length; i++)
    {
        this.addObject(contentArr[i]);
    }
}
ContentList.prototype.addItem = function(contentItem)
{
    if (!this._rawItems.ripl_InArrayKey(contentItem, 'pid'))
    {
        this.dirty = true;
        contentItem.chain = this.options.chain;
        if (this.options.referer > -1) contentItem.referer = this.options.referer;

        this._rawItems.push(contentItem);
    }
}
ContentList.prototype.addItems = function(contentItemArr)
{
    for (var i = 0; i < contentItemArr.length; i++)
    {
        this.addItem(contentItemArr[i]);
    }
}
ContentList.prototype.merge = function (cl)
{
    this.dirty = true;
    for (var i = 0; i < cl._rawItems.length; i++)
    {
        this.addItem(cl._rawItems[i]);
    }
}
ContentList.prototype.removeItemById = function(index)
{
    this.dirty = true;
    for (var i = this._rawItems.length - 1; i >=0; i--)
    {
        if (this._rawItems[i].pid == index)
        {
            return this._rawItems.splice(i,1)[0];
        }
    }
    return false;
}
ContentList.prototype.removeItemsByOwner = function(ownerId)
{
    this.dirty = true;
    for (var i = this._rawItems.length - 1; i >=0; i--)
    {
        if (this._rawItems[i].owner_id == ownerId)
        {
            this._rawItems.splice(i,1);
        }
    }
}
ContentList.prototype.getItemsByOwner = function(ownerId)
{
    var pRetVal = [];
    for (var i = this._rawItems.length - 1; i >=0; i--)
    {
        if (this._rawItems[i].owner_id == ownerId)
        {
            pRetVal.push(this._rawItems[i]);
        }
    }
    return pRetVal;
}
ContentList.prototype._filterList = function()
{
    var retList = [];
    for (var i = 0; i < this._rawItems.length; i++)
    {
        var pItem = this._rawItems[i];
        
        if (this.options.typeFilters.ripl_InArraySubstring(pItem.base_type)) retList.push(pItem);
        
    }
    this._availableItems = retList;
    this.dirty = false;
    this._sort();
}

ContentList.prototype.setTypeFilters = function(typeFilters, renderNow)
{
    this.options.typeFilters = typeFilters;
    this.dirty = true;
    if (renderNow) this.render();
    this.checkEventListeners('typeFilters_change');    
}


ContentList.prototype.renderTo = function(inLocation, inStyle, inClosure, inDataKey)
{
    this.options.renderTarget = $(inLocation);
    if (inStyle) this.options.targetStyle = inStyle;
    if (inClosure) this.options.targetClosure = inClosure;
    if (inDataKey) this.options.targetDataKey = inDataKey;
    this.render();
}

ContentList.prototype.goToPage = function(e,pageNumber)
{
    this.options.currentPageNumber = pageNumber;
    this.render();
}

ContentList.prototype.render = function()
{
    if (this.dirty)
    {
        this._filterList();
    }
    else if (this.sortDirty)
    {
        this._sort();
    }
    switch (this.options.targetStyle)
    {
        case $contentHelpers.outputFormats.INLINE:
            this._renderInline();
            break;
        case $contentHelpers.outputFormats.CARDS:
            this._renderCards();
            break;
        case $contentHelpers.outputFormats.TEXT:
            this._renderText();
            break;
    }
}

ContentList.prototype._renderText = function()
{
    var pLen = this._availableItems.length;
    var pDiv = new Element('div', {style:'width:100%'});
    if (pLen == 0) 
    {
        pDiv.update(this.options.noItems);
    }
    else
    {
        for (var i = 0; i < pLen; i++)
        {
            pDiv.insert(this._availableItems[i].getContentText(this.options.targetClosure));        
        }
    }
    this.options.renderTarget.update(pDiv);
}

ContentList.prototype._renderCards = function()
{
    var pLen = this._availableItems.length;

    var pDiv = new Element('div', {style:'width:100%'});
    if (pLen == 0) 
    {
        pDiv.update(this.options.noItems);
    }
    else
    {
        for (var i = 0; i < pLen; i++)
        {
            pDiv.insert(this._availableItems[i].getContentCard(this.options.targetClosure));        
        }
    }
    this.options.renderTarget.update(pDiv);
}

ContentList.prototype._renderInline = function()
{
    var pLen = this._availableItems.length;
    var pDiv = new Element('div', {style:'width:100%;padding:'+this.options.padding});
    if (pLen == 0) 
    {
        pDiv.update(this.options.noItems);
    }
    else
    {
        var pStart = (this.options.currentPageNumber -1) * this.options.itemsPerPage;
        var pMax = Math.min(pStart + this.options.itemsPerPage, pLen);
        
        if (pStart > pMax)
        {
            this.options.currentPageNumber = Math.ceil(pMax / this.options.itemsPerPage);
            pStart = (this.options.currentPageNumber -1) * this.options.itemsPerPage;
            pMax = Math.min(pStart + this.options.itemsPerPage, pLen);
        }
       
        if (this.options.itemsPerPage <= 0)
        {
            pStart = 0;
            pMax = pLen;
        }
        if (pStart > pMax) pStart = pMax;
        pStart = Math.max(0,pStart);
        for (var i = pStart; i < pMax; i++)
        {
            pDiv.insert(this._availableItems[i].getContentDomObj(this.options.targetClosure,null,this.options.mouseover));
        }
    }
    var pBottomBar = new Element('table',{'style':'width:100%'});
    var pBottomBarBody = new Element('tbody');
    var pBottomBarTr = new Element('tr');
    var pBottomBarTdLeft = new Element('td');
    var pBottomBarTdRight = new Element('td',{'style':'text-align:right'});

    if (this.options.displayTypeSelector)
    {
        pBottomBarTdLeft.update(this.getTypeSelector());
    }
    if ((this.options.itemsPerPage < pLen) && (this.options.itemsPerPage > 0))
    {
        pBottomBarTdRight.update(this.getPageChanger());
    }
    pBottomBarTr.insert(pBottomBarTdLeft);
    pBottomBarTr.insert(pBottomBarTdRight);
    pBottomBarBody.insert(pBottomBarTr);
    pBottomBar.insert(pBottomBarBody);
    pDiv.insert('<br class="clearBoth" />');
    pDiv.insert(pBottomBar);
    
    this.options.renderTarget.update(pDiv);    
}

ContentList.prototype.getStyleChanger = function()
{
    var pStyleChanger = new Element("div",{'style':'text-align:right'});    
    var pGrid = new Element('img',{
                    'src':(this.options.targetStyle==1)?'/images/layout_icon_grid_down.png' : '/images/layout_icon_grid.png',
                    'title':'show as grid',
                    'className':'threeStateButton',
                    'ripl:src':'/images/layout_icon_grid.png',
                    'ripl:hover':'/images/layout_icon_grid_hover.png',
                    'ripl:down':'/images/layout_icon_grid_down.png',
                    'ripl:value':1,
                    'ripl:state':(this.options.targetStyle==1) ? 'down' : 'up'
                });
    var pCard = new Element('img',{
        'src':(this.options.targetStyle==0) ? '/images/layout_icon_card_down.png' : '/images/layout_icon_card.png',
        'title':'show as grid',
        'className':'threeStateButton',
        'ripl:src':'/images/layout_icon_card.png',
        'ripl:hover':'/images/layout_icon_card_hover.png',
        'ripl:down':'/images/layout_icon_card_down.png',
        'ripl:value':0,
        'ripl:state':(this.options.targetStyle==0) ? 'down' : 'up'
            
    }); 
    var pText = new Element('img',{
        'src':(this.options.targetStyle==0) ? '/images/layout_icon_text_down.png' : '/images/layout_icon_text.png',
        'title':'show as grid',
        'className':'threeStateButton',
        'ripl:src':'/images/layout_icon_text.png',
        'ripl:hover':'/images/layout_icon_text_hover.png',
        'ripl:down':'/images/layout_icon_text_down.png',
        'ripl:value':2,
        'ripl:state':(this.options.targetStyle==2) ? 'down' : 'up'
    });    
    
    this._bindStyleChangerItem(pGrid);
    this._bindStyleChangerItem(pCard);
    this._bindStyleChangerItem(pText);
    pStyleChanger.update('display: ');
    pStyleChanger.insert(pGrid);
    pStyleChanger.insert(pCard);
    pStyleChanger.insert(pText);
    return pStyleChanger;
}

ContentList.prototype._bindStyleChangerItem = function(el)
{
    el.observe('mouseover',function()
        {
            if (this.readAttribute('ripl:state') == 'up')
            {
                this.src = this.readAttribute('ripl:hover');                    
            }        
        });
    el.observe('mouseover',function()
        {
            if (this.readAttribute('ripl:state') == 'up')
            {
                this.src = this.readAttribute('ripl:src');                    
            }        
        });
    el.observe('click',function()
        {
            var pElements = $$('.threeStateButton');
            for (var i = 0; i < pElements.length; i++)
            {
                pElements[i].src = pElements[i].readAttribute('ripl:src');
                pElements[i].writeAttribute('ripl:state', 'up');
            }
            this.writeAttribute('ripl:state','down');
            this.src = this.readAttribute('ripl:down');
        });
    Event.observe(el, 'click', this.setTargetStyle.bindAsEventListener(this, parseInt(el.readAttribute('ripl:value'),10),true));
}
ContentList.prototype.getTypeSelector = function()
{
    var pPagination = new Element("div",{'style':'font-size:x-small;line-height:20px; white-space: nowrap;padding-top:5px'}).update('content types: ');    
    var pVideoChk = new Element('input',{'id':'chkVideo','type':'checkbox','value':'Video','checked':'checked' })
    var pPhotoChk = new Element('input',{'id':'chkPhoto','type':'checkbox','value':'Photo','checked':'checked' })
    var pMusicChk = new Element('input',{'id':'chkMusic','type':'checkbox','value':'Music','checked':'checked' })
    var pBlogChk = new Element('input',{'id':'chkBlog','type':'checkbox','value':'Blog','checked':'checked' })

    var pVideoLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkVideo'}).insert('Video');
    var pPhotoLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkPhoto'}).insert('Photo');
    var pMusicLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkMusic'}).insert('Music');
    var pBlogLabel = new Element('label',{'style':'font-size:x-small,padding-left:8px','for':'chkBlog'}).insert('Blog &amp; Text');

    pPagination.insert(pVideoChk);
    pPagination.insert(pVideoLabel);
    pPagination.insert(pPhotoChk);
    pPagination.insert(pPhotoLabel);
    pPagination.insert(pMusicChk);
    pPagination.insert(pMusicLabel);
    pPagination.insert(pBlogChk); 
    pPagination.insert(pBlogLabel); 

    Event.observe(pVideoChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    Event.observe(pPhotoChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    Event.observe(pMusicChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    Event.observe(pBlogChk, 'click', this._typeSelectorChange.bindAsEventListener(this));
    
    pVideoChk.checked = this.options.typeFilters.inArray('Video');
    pPhotoChk.checked = this.options.typeFilters.inArray('Photo');
    pMusicChk.checked = this.options.typeFilters.inArray('Music');
    pBlogChk.checked = this.options.typeFilters.inArray('Blog');

    return pPagination;
}
ContentList.prototype._typeSelectorChange = function(e)
{
    var pChecked = e.element().checked;
    var pKey = e.element().value;
    var pFilters = [].concat(this.options.typeFilters);
    var pFound = false;
    for (var i =pFilters.length -1; i >=0; i--)
    {
        if (pFilters[i] == pKey)
        {
            pFound = true;
            if (!pChecked)
            {
                pFilters.splice(i,1);
            }
        }
    }
    if ((!pFound) && (pChecked))
    {
        pFilters.push(pKey);
    }
    this.setTypeFilters(pFilters,true);
}

ContentList.prototype.getPageChanger = _getGenericPageChanger;



function _getGenericPageChanger()
{
    if (this.options.currentPageNumber < 1) this.options.currentPageNumber = 1;
    
    var pPagination = new Element("div",{'style':'width:100%;height:24px;padding-top:4px;line-height:20px;text-align:right'});

    var totalPages = Math.ceil(this._availableItems.length/(this.options.itemsPerPage));
    var pageMax = (this.options.currentPageNumber < totalPages) ? false : true;
    var pageMin =(this.options.currentPageNumber != 1) ? false : true;
    var pString = ' page ' + this.options.currentPageNumber + ' of ' + totalPages;

    var pTable = new Element("table",{'style':'right:0'});
    var pTb = new Element("tbody");
    var pTr = new Element("tr");
    var pTdsp = new Element("td");        
    var pTd1 = new Element("td");
    var pTd2 = new Element("td");
    var pTd3 = new Element("td");
    var pTd4 = new Element("td");

    var pLeft;
    var pRight;
    if (!pageMin)
    {
        pLeft = new Element('img',{className:'prevStepper',src:'/images/blank.gif'});
        Event.observe(pLeft, 'click', this.goToPage.bindAsEventListener(this, (this.options.currentPageNumber -1)));
    }
    else
    {
        pLeft = new Element('img',{className:'prevStepper_disabled',src:'/images/blank.gif'})
    }

    if (!pageMax)
    {
        pRight = new Element('img',{className:'nextStepper',src:'/images/blank.gif'});
        Event.observe(pRight, 'click', this.goToPage.bindAsEventListener(this, (this.options.currentPageNumber +1)));
    }
    else
    {
        pRight = new Element('img',{className:'nextStepper_disabled',src:'/images/blank.gif'})
    }
    pPagination.update('&nbsp;page&nbsp;' + this.options.currentPageNumber + '&nbsp;of&nbsp;' + totalPages + '&nbsp;');
    pPagination.insert(pLeft);
    pPagination.insert(pRight);
    return pPagination;
}





// Yes, these are closures, but that seems the right thing to do for a singleton 'class'.
// Generally, having a few singletons at the top of the class is better than having N new functions at the top.  The way
// JavaScript searches for things, this should balance out speed-wise, or possibly be faster than keeping everything at the top.
/////////////////////////////////////////////////////////////////////////////////////////////
// CONTENTITEM FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////

function ContentItem(contentObj)
{
    this.pid = parseInt(contentObj.pid,10);
    this.base_type = contentObj['base_type'];
    this.chain = ContentChains.NOT_LOGGED;
    this.title = contentObj.title ? contentObj.title.replace(/\\/g,'') : 'Untitled';
    this.artist = (contentObj.artist != undefined) ?  contentObj.artist.replace(/\\/g,'') : '';
    this.album = (contentObj.album != undefined) ?  contentObj.album.replace(/\\/g,'') : '';
    this.description = (contentObj.description != undefined) ?  contentObj.description.replace(/\\/g,'') : '';
    this.thumbnail_image_url = (contentObj['thumbnail_image_url'] != undefined) ? contentObj['thumbnail_image_url'] : '/images/music/no_art.gif';
    
    this.preview_image_url = contentObj['preview_image_url'];
    this.provider_id = contentObj['provider_id'];
    
    this.foreign_provider_guid = contentObj['foreign_provider_guid'];
    this.content_location_url = contentObj['content_location_url'];
    this.owner_id = parseInt(contentObj['owner_id'],10);
    this.rating = (contentObj.rating!=null) ? parseFloat(contentObj.rating) : -1; 
    this.rank = (contentObj.rank != null) ? parseInt(contentObj.rank,10) : -1;
    if (contentObj.count)
    {
        this.count = parseInt(contentObj.count);
    }
    else
    {
        this.count = ContentItem.serial;
        ContentItem.serial++;
    }
    
    this.referer = this.owner_id;
    this.loc = 'content_detail';
    this.item_count = parseInt(contentObj['item_count'],10);
    this.domObj = null;
    this.last_update = contentObj['updated'];
    ContentItem.pidHash[this.pid] = this;
}
ContentItem.serial = 0;
ContentItem.pidHash = [];
ContentItem.getFromContentObj = function(contentObj)
{
    if (contentObj == null) return;
    if (ContentItem.pidHash[contentObj.pid])
    {
        return ContentItem.pidHash[contentObj.pid];
    }
    else
    {
        return new ContentItem(contentObj);
    }
}
ContentItem.getById = function(id)
{
    return ContentItem.pidHash[id];
}
ContentItem.prototype.clear = function()
{
    this.domObj = null;
}
ContentItem.prototype.getGenericLinkText = function()
{
    var pValue = 'view content item';
    switch (this.base_type)
    {
        case 'video':
            pValue = 'watch video';
            break;
    }
    return pValue;
}
ContentItem.prototype.getContentImage = function()
{
	if(!this) return '';
	return '<img class="'+$contentHelpers.getCSSClass(this)+'" src="'+$contentHelpers.getFrame(this)+'" style="background-image:url(\'' + this.thumbnail_image_url + '\')" />';
}
ContentItem.prototype.getContentDomObj = function(scriptName, scriptData, mouseover)
{
//    if (this.domObj != null) return this.domObj;

    var pImg = this.getContentImage();
    var pA = this.getAnchor(scriptName, scriptData,mouseover);
  
    pA.insert(pImg);
    this.domObj = pA;
    return pA;
};
ContentItem.prototype.getAnchor = function(scriptName, scriptData,mouseover)
{
    var pA;
    if ((scriptName) && (scriptName != 'undefined'))
    {
        pA = new Element('a',{
            href:'#',
            title:this.title
        });
        if ((!scriptData) || (scriptData == 'undefined')) scriptData = this.pid;
        if (scriptName) pA.observe('click',scriptName.bindAsEventListener(this,scriptData));
    }
    else
    {
        pA = new Element('a', {
            href:'/contentDetailView.php?contentid=' + this.pid + '&chain=' + this.chain + '&r=' + this.referer + '&loc=' + this.loc,
            title:this.title
        });
    }
    if (mouseover)
    {
        if ((!scriptData) || (scriptData == 'undefined')) scriptData = this.pid;
        pA.observe('mouseover',mouseover.bindAsEventListener(this,scriptData));
    }
    return pA;
}
ContentItem.prototype.getContentCard = function(scriptName, scriptData)
{
    var pDiv = new Element('div',{className:'CardBox'});
    pDiv.update(this.getContentDomObj(scriptName, scriptData));

    var pTextCell = new Element('div',{className:'CardInfo'});
    var pTitle = this.getAnchor(scriptName, scriptData);
    pTitle.className = 'CardTitle';
    pTitle.update(this.title);
    //var pTextCellData = '<span class="contentRowInfoTitle">' + this.title +'</span>';
    var pTextCellData = '';
    if (this.base_type == 'Music')
    {
        pTextCellData += '<br />';
        pTextCellData += this.artist;
        pTextCellData += '<br />';
        pTextCellData += this.album;
        pTextCellData += '<br />';
    }
    if (this.last_update != null) pTextCellData += '<div class="CardUpdated">added ' + new Date(this.last_update * 1000).format(Date.TIME_SINCE) + '</div>';
    if (this.provider_id != null && this.provider_id!='' && this.provider_id != 'Ripl'){ pTextCellData += 'through '+ this.provider_id;}
    pTextCell.update(pTitle);
    pTextCell.insert(pTextCellData);
    pDiv.insert(pTextCell);
    
    return pDiv;
};
ContentItem.prototype.toString = function()
{
    return this.title;
}
ContentItem.prototype.getFriendlyUpdateTime = function()
{
    return new Date(this.last_update * 1000).format(Date.TIME_SINCE);
}
ContentItem.prototype.getStandardUpdateTime = function()
{
    return new Date(this.last_update * 1000).format(Date.SIMPLETIME);
}
ContentItem.prototype.getContentText = function(scriptName, scriptData)
{
    var pDiv = new Element('div');
    var pTitle = this.getAnchor(scriptName, scriptData);
    pTitle.update(this.title);
    pDiv.update(pTitle);
    pTextCellData = ' <span class="contentRowUpdated">added ' + new Date(this.last_update * 1000).format(Date.TIME_SINCE);
    if (this.provider_id != 'Ripl'){ pTextCellData += ' (through '+ this.provider_id + ' )</span>';}
    pDiv.insert(pTextCellData);
    
    return pDiv;
}

var $contentHelpers = {};

$contentHelpers.outputFormats = {'CARDS':0, 'INLINE':1, 'TEXT':2, 'PROFILE_TEXT':3};
$contentHelpers.defualtPageBreakCounts = [16,24,32,5];
// Possibly dangerous to have the variable 'cssClass' at the same level as the providers, but it should work for now.
$contentHelpers.contentInfo = {'Photo':{'cssClass':'th_p','Flickr':'/images/picFrameFlickr.png', 'Facebook':'/images/picFrameFacebook.png', 'MySpace':'/images/picFrameMySpace.png','Picasa':'/images/picFrame_picasa.png' ,'default':'/images/picFrameRipl.png'},
                                 'Video':{'cssClass':'th_v','YouTube':'/images/videoFrame_youTube.png','MySpace':'/images/videoFrame_mySpace.png','Vimeo':'/images/videoFrame_vimeo.png','Hulu':'/images/videoFrame_hulu.png', 'default':'/images/videoFrame.png'},
                                'Music':{'cssClass':'th_m','default':'/images/musicFrame.png', 'no_art':'/images/music/no_art.gif'},
                                'PhotoAlbum':{'cssClass':'th_pa','default':'/images/musicFrame.png'}
                                 };
// This could be a prototype method of a content class if we need to make one.
$contentHelpers.getFrame = function contentHelpers_getFrame(contentObject)
{
    if (contentObject['base_type'] != 'PhotoAlbum')
    {
        var pCachedType = $contentHelpers.contentInfo[contentObject['base_type']];
        if (pCachedType != null)
        {
            if (pCachedType[contentObject['provider_id']] != null) return pCachedType[contentObject['provider_id']];
            else return pCachedType['default']; 
        }
        return ''; // We don't recognize this content item, so there's no default to fall back on. (yet)
    }
    else
    {
        var pConvertedCount = 1;
        if (contentObject.item_count <= 20)
        {
            pConvertedCount = contentObject.item_count;
        }
        else if (contentObject.item_count <= 50)
        {
            pConvertedCount = Math.floor(contentObject.item_count/10)*10 + '_plus';            
        }
        else if (contentObject.item_count < 100)
        {
            pConvertedCount = '50_plus';
        }
        else
        {
            pConvertedCount = '100_plus';
        }
        return '/images/cr/photoAlbum/' + pConvertedCount + '.png';
    }
};


//This could be a prototype method of a content class if we need to make one.
$contentHelpers.getCSSClass = function contentHelpers_getCSSClass(contentObject)
{
    var pCachedType = $contentHelpers.contentInfo[contentObject['base_type']];
    if (pCachedType != null)
    {
        return (pCachedType['cssClass'] != null) ? pCachedType['cssClass'] : '';
    }
    return ''; // We don't recognize this content item, so there's no default to fall back on. (yet)
};

$contentHelpers.getContentItemPreview = function contentHelpers_getContentItemPreview(contentItem, scriptName, scriptData, cachePreview)
{
    var pArr = [ '<a href="',
                 ((scriptName != null) ? ('#" onclick="'+scriptName + '(') : '/contentDetailView.php?contentid='), 
                 ((scriptData != null) ? (scriptData +')"') : ((scriptName != null) ? contentItem['pid'] + ')': contentItem['pid'])),
                 '" title="', contentItem["title"], 
                 '"><img border="0" class="',
                 $contentHelpers.getCSSClass(contentItem),
                 '" style="background-image:url(\'',
                 contentItem["thumbnail_image_url"],
                 '\')" src="', 
                 $contentHelpers.getFrame(contentItem), 
                 '"></a>' ];
    var pOut = pArr.join('');
    if (cachePreview) contentItem.previewHTML = pOut;
    return pOut;
};

$contentHelpers.write = function(contentList, outputLocationName, format,pageNumber,scriptName,forceNew)
{
    if (format == null) format = 'INLINE';
    if (pageNumber == null) pageNumber = 1;
    switch (format)
    {
//        case $contentHelpers.outputFormats.GRID_6_ACROSS:
//            $contentHelpers._writeGrid(contentList, outputLocationName, 6,scriptName,forceNew);
//            break;
        case $contentHelpers.outputFormats.INLINE:
            $contentHelpers._writeInline(contentList, outputLocationName,pageNumber,scriptName,forceNew);
            break;
        case $contentHelpers.outputFormats.CARDS:
            $contentHelpers._writeCards(contentList, outputLocationName,pageNumber,scriptName,forceNew);
            break;
        case $contentHelpers.outputFormats.TEXT:
            $contentHelpers._writeText(contentList, outputLocationName,pageNumber,scriptName,forceNew);
            break;
            
//        case $contentHelpers.outputFormats.ROWS:
//            $contentHelpers._writeRows(contentList, outputLocationName,scriptName,forceNew);
//            break;
        default:
//            alert($contentHelpers.outputFormats.ROWS);
    }
};

$contentHelpers._writeText = function(contentList, outputLocation,pageNumber,scriptName,forceNew)
{
    var outArr = [];
    var pLen = contentList.length;
    var pDiv = new Element('div', {style:'width:100%'});
    for (var i = 0; i < pLen; i++)
    {
        pDiv.insert(ContentItem.getFromContentObj(contentList[i]).getContentText(scriptName));
    }
    $(outputLocation).update(pDiv);
}

$contentHelpers._writeCards = function(contentList, outputLocation,pageNumber,scriptName,forceNew)
{
    var outArr = [];
    var pLen = contentList.length;
    var pDiv = new Element('div', {style:'width:100%'});
    for (var i = 0; i < pLen; i++)
    {
        pDiv.insert(ContentItem.getFromContentObj(contentList[i]).getContentCard(scriptName));
    }
    $(outputLocation).update(pDiv);
}

$contentHelpers._writeInline = function(contentList, outputLocation,pageNumber,scriptName,forceNew)
{
    var outArr = [];
    var pLen = contentList.length;
    var pDiv = new Element('div', {style:'width:100%'});
    var pMax = Math.min($contentHelpers.defualtPageBreakCounts[1] * pageNumber, pLen);
    var pStart = (pageNumber -1) * $contentHelpers.defualtPageBreakCounts[1];
    
    pDiv.insert($contentHelpers.getPaginationDiv(pLen,pageNumber));

    for (var i = pStart; i < pMax; i++)
    {
        try
        {
            pDiv.insert(ContentItem.getFromContentObj(contentList[i]).getContentDomObj(scriptName));
        } catch (e){}
    }
    if ($contentHelpers.defualtPageBreakCounts[1] < pLen)
    {
        pDiv.insert($contentHelpers.getPaginationDiv(pLen,pageNumber));
    }
    
    $(outputLocation).update(pDiv);
};

$contentHelpers.getPaginationDiv = function(pLen,pageNumber){
	var pPagination = new Element("div",{'style':'text-align:right'});
    var totalPages = Math.ceil(pLen/($contentHelpers.defualtPageBreakCounts[1]));
    var pageMax = (pageNumber < totalPages) ? false : true;
    var pageMin =(pageNumber != 1) ? false : true;
    var pString = '<br style="clear:both" /> page ' + pageNumber + ' of ' + totalPages;
    if (!pageMin) pString += ' <a style="cursor:pointer;cursor:hand;" onclick="_jumpPage('+ (pageNumber -1) +')">&lt; prev</a> ';
    if (!pageMin && !pageMax) pString += ' | '
    if (!pageMax) pString += ' <a style="cursor:pointer;cursor:hand;" onclick="_jumpPage('+ (pageNumber +1) +')">next &gt;</a> ';
    pPagination.update(pString);
    return pPagination;
};
$contentHelpers.sortListByAge = function(contentList)
{
    return contentList.sort($contentHelpers._ageSort);
};

$contentHelpers._ageSort = function(a, b)
{
    return parseInt(b['pid'],10) - parseInt(a['pid'],10);
};


function MixedList(inOptions)
{
    this._rawContent = new ContentList();
    this._rawUsers = new UserList();
    
    this._rawItems = [];
    
    this.options = Object.extend({
       renderTarget:null,
       chain:ContentChains.NOT_LOGGED,
       mouseover:null,
       showFollow:true,       
       referer:-1
    },inOptions || {})      
    
}

MixedList.prototype.addItem = function(item)
{
    this._rawItems.push(item);    
}


MixedList.prototype.addContentObjects = function(inObjects)
{
    this._rawContent.referer = this.options.referer;
    this._rawContent.addObjects(inObjects);
}
MixedList.prototype.addUserObjects = function(inObjects)
{
    this._rawUsers.addObjects(inObjects);
}
MixedList.prototype.renderTo = function(target)
{
    this.options.renderTarget = $(target);
    this.render();
}
//Temporary simple rendering
MixedList.prototype.render = function()
{
    if (this.options.renderTarget == null) return;
    this._rawContent.options.showFollow = this.options.showFollow;
    var pDiv = new Element('div', {style:'width:100%'});
    var i = 0;
    var pOutArr = [];
    for (i=0; i < this._rawContent._rawItems.length; i++)
    {
        var pItem = this._rawContent._rawItems[i];
        pItem.chain = this.options.chain;
        pOutArr.push(pItem.getContentDomObj())
    }
    for (i=0; i < this._rawUsers._rawItems.length; i++)
    {
        var pItem = this._rawUsers._rawItems[i];
        pOutArr.push(pItem.getUserDomObj(null,null,null,this.options.showFollow));
    }    
    
    for (var i = pOutArr.length-1; i>=0; i--)
    {
        var pRand = Math.floor(Math.random() * i);
        pDiv.insert(pOutArr.splice(pRand,1)[0]);
    }
    this.options.renderTarget.update(pDiv);
}
MixedList.prototype.renderEx = function()
{
    if (this.options.renderTarget == null) return;
    this._rawContent.options.showFollow = this.options.showFollow;
    var pDiv = new Element('div', {style:'width:100%'});
    var i = 0;
    var pOutArr = [];
    for (i =0; i < this._rawItems.length; i++)
    {
        if (this._rawItems[i].pid)
        {
            var pItem = this._rawItems[i];
            pItem.chain = this.options.chain;
            pDiv.insert(pItem.getContentDomObj())
        }
        else
        {
            var pItem = this._rawItems[i];
            pItem.chain = this.options.chain;
            pDiv.insert(pItem.getUserDomObj(null,null,null,this.options.showFollow))
        }
    }

    this.options.renderTarget.update(pDiv);
}

function FetchObject(evtThis, evtKind, evtParameters)
{
    this.relItem = evtThis;
    this.kind = evtKind;
    this.parameters = evtParameters;
}

function ListFactory()
{
    this.eventListeners = [];
    this._caches = {};
}
ListFactory.EVENT_CHANGECURRENT = 'listfactory_changeCurrent';


ListFactory.EVENT_TYPE_FEATURED_CONTENT ='featuredContent';
ListFactory.EVENT_TYPE_RECOMMENDED_CONTENT ='recommendedContent';
ListFactory.EVENT_TYPE_TAGSEARCH = 'tagSearch';

ListFactory.EVENT_TYPE_FEATURED_MIXED ='featuredMixed';

ListFactory.EVENT_TYPE_SUPERFANS ='superFans';

ListFactory.EVENT_TYPE_SUBSCRIBED_TO ='subscribedTo';
ListFactory.EVENT_TYPE_SUBSCRIBED_BY ='subscribedBy';
ListFactory.EVENT_TYPE_MAY_KNOW ='mayKnow';
ListFactory.EVENT_TYPE_NAME ='byName';
ListFactory.EVENT_TYPE_USERNAME ='byUsername';
ListFactory.EVENT_TYPE_DISPLAYNAME ='byDisplayName';
ListFactory.EVENT_TYPE_EMAIL = 'email';
ListFactory.EVENT_TYPE_DISTANCE ='distance';
ListFactory.EVENT_CHANNEL = 'dynamicChannel';
ListFactory.EVENT_TYPE_OWNEDCONTENT = 'ownedContent';
ListFactory.EVENT_TYPE_CONTENTFAVORITED = 'contentFavorited';
ListFactory.EVENT_TYPE_RECENTLYVIEWED = 'recentlyViewed';
ListFactory.EVENT_TYPE_ALSOLIKED = 'alsoLiked';

ListFactory.prototype._checkCache = function(key,params)
{
    var pFetchObject = this._caches[key];
    if (pFetchObject)
    {
        if (pFetchObject.data == null) return false;
        var pEquiv = true;
        try
        {
            for (var pKey in pFetchObject.parameters)
            {
                if ((params[pKey]) && (params[pKey].toString() != pFetchObject.parameters[pKey].toString()))
                {
                    pEquiv = false;
                }
            }
        }
        catch (e)
        {
            pEquiv = false;
        }
        pFetchObject.data.render();
        if (!pEquiv) return false;
        this.checkEventListeners(ListFactory.EVENT_CHANGECURRENT, pFetchObject);    
    }
    return pFetchObject;
}

ListFactory.prototype.fetchFavorited = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_CONTENTFAVORITED;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/content/getFavorited.php', fetchObject);
}
ListFactory.prototype.fetchAlsoLiked = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_ALSOLIKED;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxContent('ajax/content/getAlsoLiked.php', fetchObject);
}

ListFactory.prototype.fetchSuperFans = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_SUPERFANS;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxSuperfans('ajax/user/getSuperFans.php', fetchObject);
}
ListFactory.prototype.fetchOwnedContent = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_OWNEDCONTENT;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxContent('ajax/user/getContent.php', fetchObject);
}

ListFactory.prototype.fetchByUsername = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_USERNAME;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    
    this._ajaxUser('ajax/people/findByUsername.php', fetchObject);
};
ListFactory.prototype.fetchByDisplayName = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_DISPLAYNAME;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    
    this._ajaxUser('ajax/people/findByDisplayName.php', fetchObject);
};
ListFactory.prototype.fetchByName = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_NAME;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    
    this._ajaxUser('ajax/people/findByName.php', fetchObject);
}


ListFactory.prototype.fetchSubscribedTo = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_SUBSCRIBED_TO;
    
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;

    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/user/getSubscriptions.php', fetchObject);
}

ListFactory.prototype.fetchRecentlyViewed = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_RECENTLYVIEWED;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;
    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/content/getRecentlyViewed.php', fetchObject);    
}

ListFactory.prototype.fetchSubscribedBy = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_SUBSCRIBED_BY;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;
    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/user/getSubscribedBy.php', fetchObject);    
}

ListFactory.prototype.fetchMayKnow = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_MAY_KNOW;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;
    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/user/getMayKnow.php', fetchObject);
}

ListFactory.prototype.fetchByEmail = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_EMAIL;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;
    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/people/findByEmail.php', fetchObject);
}

ListFactory.prototype.fetchByDistance = function(settings)
{
    var pKey = ListFactory.EVENT_TYPE_DISTANCE;
    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;
    var fetchObject = new FetchObject(this,pKey, settings);
    this._ajaxUser('ajax/people/findByDistance.php', fetchObject);
}


ListFactory.prototype.getChannel = function(settings)
{
    //uid,feedObject,forceNew
    var pKey = ListFactory.EVENT_CHANNEL;
//    if ((!settings.forceNew) && (this._checkCache(pKey,settings))) return;
    var fetchObject = new FetchObject(this,pKey,settings);  
    
    this._ajaxChannel('feeds/dynamicFeed.php', fetchObject);
    
}


// getFeatured does not cache by default
ListFactory.prototype.getFeatured = function(settings)
{
    var fetchObject = new FetchObject(this,ListFactory.EVENT_TYPE_FEATURED_CONTENT, settings);
    this._ajaxContent('ajax/featured/getFeatured.php', fetchObject);
}

function printObj(obj)
{
    var pRetval ='';
    for (var i in obj)
    {
        pRetval = pRetval + i + ":" + obj[i] + '|\n';
    }
    return pRetval;
}


//getRecommended does not cache by default
ListFactory.prototype.getRecommended = function(settings)
{
    var fetchObject = new FetchObject(this,ListFactory.EVENT_TYPE_RECOMMENDED_CONTENT, settings);
    this._ajaxContent('ajax/content/getRecommended.php', fetchObject);
}

ListFactory.prototype.tagSearch = function(settings)
{
    var fetchObject = new FetchObject(this,ListFactory.EVENT_TYPE_RECOMMENDED_CONTENT, settings);
    this._ajaxContent('ajax/content/getRecommended.php', fetchObject);
}

ListFactory.prototype.getFeaturedContentAndUsers = function(settings)
{
    var fetchObject = new FetchObject(this,ListFactory.EVENT_TYPE_FEATURED_MIXED, settings);
    this._ajaxMixed('ajax/featured/getFeatured.php', fetchObject);
}

ListFactory.prototype.parseMixedList = function(responseData)
{
    var pObj = this.parameters.options ? this.parameters.options : {};
    
    var pData = responseData.responseText.evalJSON();
    var pList = new MixedList(pObj);
    if (this['r'] >= 1) pList.referer = this['r'];
    pList.addContentObjects(pData['content']);
    pList.addUserObjects(pData['users']);
    this.data = pList;
    this.relItem._caches[this.kind] = this;
    this.relItem.checkEventListeners(ListFactory.EVENT_CHANGECURRENT, this);
    if (this.parameters.options.renderTarget)
    {
        pList.render();
    }      
}

ListFactory.prototype.parseSuperfans = function(responseData)
{
    var pObj = this.parameters.options ? this.parameters.options : {};

    var pUserList = new UserList(pObj);

//    pUserList.superfanMode = true;
    pUserList.setSortKey('fanindex');
    pUserList.addObjects(responseData.responseText.evalJSON());
    this.data = pUserList;
    this.relItem._caches[this.kind] = this;
    if (this.parameters.options.renderTarget)
    {
        pUserList.render();
    }    
    this.relItem.checkEventListeners(ListFactory.EVENT_TYPE_SUPERFANS, this);
}

ListFactory.prototype.parseUserList = function(responseData)
{
    var pObj = this.parameters.options ? this.parameters.options : {};
    var pUserList = new UserList(pObj);
    pUserList.addObjects(responseData.responseText.evalJSON());
    this.data = pUserList;
    this.relItem._caches[this.kind] = this;
    this.relItem.checkEventListeners(ListFactory.EVENT_CHANGECURRENT, this);

    if (this.parameters.options.renderTarget)
    {
        pUserList.render();
    }
}
ListFactory.prototype.parseContentList = function(responseData)
{
    var pObj = this.parameters.options ? this.parameters.options : {};
    var pContentList = new ContentList(pObj);
    pContentList.addObjects(responseData.responseText.evalJSON());
    this.data = pContentList;
    this.relItem._caches[this.kind] = this;    
    this.relItem.checkEventListeners(ListFactory.EVENT_CHANGECURRENT, this);
    if (this.parameters.options.renderTarget)
    {
        pContentList.render();
    }    
}
ListFactory.prototype.parseFeedList = function(responseData)
{
    var pObj = this.parameters.options ? this.parameters.options : {};

    var pFeedList = new FeedList(pObj);
    pFeedList.addRawData(responseData.responseText.evalJSON());
    this.data = pFeedList;
    this.relItem._caches[this.kind] = this;    
    this.relItem.checkEventListeners(ListFactory.EVENT_CHANGECURRENT, this);
    if (pObj.renderTarget)
    {
        pFeedList.render();
    }    
}




ListFactory.prototype._ajaxMixed = function(url, fetchObject)
{
	fetchObject.parameters.cachebust = new Date().getTime();
    new Ajax.Request(url, 
            {
                method:'get',
                requestHeaders: {Accept: 'application/json'},
                parameters:fetchObject.parameters,
                onSuccess: this.parseMixedList.bind(fetchObject)
            });    
}
ListFactory.prototype._ajaxSuperfans = function(url, fetchObject)
{
	fetchObject.parameters.cachebust = new Date().getTime();
    new Ajax.Request(url, 
            {
                method:'get',
                requestHeaders: {Accept: 'application/json'},
                parameters:fetchObject.parameters,
                onSuccess: this.parseSuperfans.bind(fetchObject)
            });    
}
ListFactory.prototype._ajaxUser = function(url, fetchObject)
{
	fetchObject.parameters.cachebust = new Date().getTime();
    new Ajax.Request(url, 
            {
                method:'get',
                requestHeaders: {Accept: 'application/json'},
                parameters:fetchObject.parameters,
                onSuccess: this.parseUserList.bind(fetchObject)
            });    
}
ListFactory.prototype._ajaxContent = function(url, fetchObject)
{
	fetchObject.parameters.cachebust = new Date().getTime();
    new Ajax.Request(url, 
            {
                method:'get',
                requestHeaders: {Accept: 'application/json'},
                parameters:fetchObject.parameters,
                onSuccess: this.parseContentList.bind(fetchObject)
            });    
}
ListFactory.prototype._ajaxChannel = function(url, fetchObject)
{
	fetchObject.parameters.parameters.cachebust = new Date().getTime();
    new Ajax.Request(url, 
            {
                method:'get',
                requestHeaders: {Accept: 'application/json'},
                parameters:fetchObject.parameters.parameters,
                onSuccess: this.parseFeedList.bind(fetchObject)
            });    
}

ListFactory.prototype.addEventListener = EventHandler.addEventListener;
ListFactory.prototype.removeEventListener = EventHandler.removeEventListener;
ListFactory.prototype.checkEventListeners = EventHandler.checkEventListeners;


function UserList(inOptions)
{
    this._rawItems = [];
    this._availableItems = [];
    this.eventListeners = [];

    
    this.dirty = true;
    this.sortDirty = true;
    
    this.options = Object.extend({
        renderTarget:null,
        itemsPerPage:12,
        showNames:false,
        showFollow:true,
        sortKey:'age',
        sortReverse:false,
        currentPageNumber:1,
        targetStyle:null,
        targetClosure:null,
        targetDataKey:null,
        renderDisabledTarget:null,
        noItems:'No items were found',
        padding:'0px 15px'
    },inOptions || {})        
    
//    this.superfanMode = false;
}

UserList.prototype.addEventListener = EventHandler.addEventListener;
UserList.prototype.removeEventListener = EventHandler.removeEventListener;
UserList.prototype.checkEventListeners = EventHandler.checkEventListeners;


UserList.prototype.getCount = function()
{
    return this._rawItems.length;
}
UserList.prototype.getAvailableCount = function()
{
    return this._availableItems.length;
}
UserList.prototype.getIdsAsArray = function()
{
    var pRetVal = [];
    for (var i = 0; i < this._rawItems.length;i++)
    {
        pRetVal.push(this._rawItems[i].uid);
    }
    return pRetVal;
}
UserList.prototype.clear = function(renderNow)
{
    this.dirty = true;
    this._rawItems = [];
    if (renderNow) this.render();
}

UserList.prototype.getItemById = function(itemId)
{
    for (var i = 0; i < this._rawItems.length; i++)
    {
        if (this._rawItems[i].uid == itemId)
        {
            return this._rawItems[i];
        }
    }
    return false;
}

UserList._rankSort = function(a,b)
{
    var pRetVal = 0;
    a = a.rank;
    b = b.rank;
    if (a>b) pRetVal = 1;
    if (a <b) pRetVal = -1;
    return pRetVal;      
}

UserList._ageSort = function(a,b)
{
    var pRetVal = 0;
    return parseInt(b['uid'],10) - parseInt(a['uid'],10);
    return pRetVal;
}
UserList._alphaTitle = function(a,b)
{
    var pRetVal = 0;
    a = a.displayName.toLowerCase(); 
    b = b.displayName.toLowerCase();
    if (a>b) pRetVal = 1;
    if (a <b) pRetVal = -1;
    return pRetVal;    
}

UserList._fanindexSort = function(a,b)
{
    var pRetVal = 0;
    a = a.fanindex;
    b = b.fanindex;
    if (a>b) pRetVal = 1;
    if (a <b) pRetVal = -1;
    return pRetVal;    
    
}


UserList.prototype.setSortKey = function(sortKey, renderNow)
{
    this.options.sortKey = sortKey;
    this.sortDirty = true;
    if (renderNow) this.render();
}
UserList.prototype.setSortReverse = function(sortReverse, renderNow)
{
    this.options.sortReverse = sortReverse;
    this.sortDirty = true;
    if (renderNow) this.render();
}
UserList.prototype.toggleSortOrder = function(renderNow)
{
    this.options.sortReverse = !this.options.sortReverse;
    this.sortDirty = true;
    if (renderNow) this.render();
}

UserList.prototype.setTargetStyle = function(e,newStyle,renderNow)
{
    this.options.targetStyle = newStyle;
    if (renderNow) this.render();
    this.checkEventListeners('targetStyle_change');
}

UserList.prototype._sort = function()
{
    var pSortFunction;
    switch (this.options.sortKey)
    {
        case 'title':
            pSortFunction = UserList._alphaTitle;
            break;
        case 'age':
            pSortFunction = UserList._ageSort;
            break;
        case 'rank':
            pSortFunction = UserList._rankSort;
            break;
        case 'fanindex':
            pSortFunction = UserList._fanindexSort;
            break;
        default: // explicit fall-through
    }
    if (pSortFunction)
    {
        this._availableItems = this._availableItems.sort(pSortFunction);
        if (this.options.sortReverse) this._availableItems.reverse();
    }
    this.dirty = false;    
}


UserList.prototype.addObject = function(userObject,index)
{
    var pItem = new User(userObject);
    this.addItem(pItem,index);
}
UserList.prototype.addObjects = function(userArr)
{
    for (var i = 0; i < userArr.length; i++)
    {
        this.addObject(userArr[i],i);
    }
}
UserList.prototype.addItem = function(user,index)
{
    this.dirty = true;
//    user.chain = this.chain;
    if (!this._rawItems.ripl_InArrayKey(user, 'uid'))
    {
        this._rawItems.push(user);
    }
}
UserList.prototype.addItems = function(userItemArr)
{
    for (var i = 0; i < userItemArr.length; i++)
    {
        this.addItem(userItemArr[i],i);
    }
}
/*
UserList.prototype.disableItemById = function(index)
{
    this.dirty = true;
    for (var i = this._availableItems.length - 1; i >=0; i--)
    {
        if (this._availableItems[i].uid == index)
        {
            this._availableItems.splice(index,1);
            return true;
        }
    }
    return false;
}
UserList.prototype.enableItemById = function(index)
{
    this.dirty = true;
    this.disableElementById(index);

    for (var i = this._rawItems.length - 1; i >=0; i--)
    {
        if (this._rawItems[i].uid == index)
        {
            this._availableItems.push(this._rawItems[i]);
            return true;
        }
    }
    return false;
}
UserList.prototype.removeItemById = function(index)
{
    this.dirty = true;
    for (var i = this._rawItems.length - 1; i >=0; i--)
    {
        if (this._rawItems[i].uid == index)
        {
            return this._rawItems.splice(i,1)[0];
        }
    }
    return false;
}
*/
UserList.prototype.renderTo = function(inLocation, inStyle, inClosure, inDataKey)
{
    this.options.renderTarget = $(inLocation);
    if (inStyle) this.options.targetStyle = inStyle;
    if (inClosure) this.options.targetClosure = inClosure;
    if (inDataKey) this.options.targetDataKey = inDataKey;
    this.render();
}

UserList.prototype.goToPage = function(e,pageNumber)
{
    this.options.currentPageNumber = pageNumber;
    this.render();
}
UserList.prototype._filterList= function()
{
    this._availableItems = this._rawItems;
    this._sort();
}

UserList.prototype.render = function()
{
    if (this.dirty)
    {
        this._filterList();
    }
    else if (this.sortDirty)
    {
        this._sort();
    }
    switch (this.options.targetStyle)
    {
        case $contentHelpers.outputFormats.INLINE:
            this._renderInline();
            break;
        case $contentHelpers.outputFormats.CARDS:
            this._renderCards();
            break;
        case $contentHelpers.outputFormats.TEXT:
            this._renderText();
            break;
        default:
            this._renderInline();
    }
}
UserList.prototype._renderTiles = function()
{
    var pLen = this._availableItems.length;
    var pDiv = new Element('div', {style:'width:100%'});
    if (pLen == 0) 
    {
        pDiv.update(this.options.noItems);
    }    
    else
    {
        for (var i = 0; i < plen; i++)
        {
            pDiv.insert(this._availableItems[i].getTile(this.options.targetClosure));
        }
    }
    this.options.renderTarget.update(pDiv);
}

UserList.prototype._renderInline = function()
{
    var pLen = this._availableItems.length;
    var pDiv = new Element('div', {style:'padding:'+this.options.padding});
    if (pLen == 0) 
    {
        pDiv.update(this.options.noItems);
    }
    else
    {
        var pStart = (this.options.currentPageNumber -1) * this.options.itemsPerPage;
        var pMax = Math.min(pStart + this.options.itemsPerPage, pLen);
        
        if (pStart > pMax)
        {
            this.options.currentPageNumber = Math.ceil(pMax / this.options.itemsPerPage);
            pStart = (this.options.currentPageNumber -1) * this.options.itemsPerPage;
            pMax = Math.min(pStart + this.options.itemsPerPage, pLen);
        }
        
        if (this.options.itemsPerPage <= 0)
        {
            pStart = 0;
            pMax = pLen;
        }
        if (pStart > pMax) pStart = pMax;
        
        
        for (var i = pStart; i < pMax; i++)
        {
            try
            {
                pDiv.insert(this._availableItems[i].getUserDomObj(this.options.showNames,this.options.targetClosure,null,this.options.showFollow));
            } catch (e){}
        }
        var pBottomBar = new Element('table',{'style':'width:100%'});
        var pBottomBarBody = new Element('tbody');
        var pBottomBarTr = new Element('tr');
        var pBottomBarTdLeft = new Element('td');
        var pBottomBarTdRight = new Element('td',{'style':'text-align:right'});

        if ((this.options.itemsPerPage < pLen) && (this.options.itemsPerPage > 0))
        {
            pBottomBarTdRight.update(this.getPageChanger());
        }
        pBottomBarTr.insert(pBottomBarTdLeft);
        pBottomBarTr.insert(pBottomBarTdRight);
        pBottomBarBody.insert(pBottomBarTr);
        pBottomBar.insert(pBottomBarBody);
        pDiv.insert('<br class="clearBoth" />');
    }
    pDiv.insert(pBottomBar);    
    
    
    this.options.renderTarget.update(pDiv);    
}

UserList.prototype.getPageChanger = _getGenericPageChanger;



/////////////////////////////////////////////////////////////////////////////////////////////
// USER FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////
function User(userObj)
{
    this.uid = parseInt(userObj.uid,10);
    this.login = userObj.login;
    this.displayName = (userObj.displayName) ? userObj.displayName : '';
    this.avatarurl = userObj.avatarurl;
    this.following = userObj.following;
    this.isCurrent = userObj.isCurrent;
    this.userType = (userObj.userType) ? userObj.userType : 'normal'
    this.fanindex = (userObj.fanindex != null) ? parseInt(userObj.fanindex,10) : -1
    this.rank= (userObj.rank != null) ? parseInt(userObj.rank,10) : -1
    this.referralCount = -1;
    this.domObj = null;
    User.uidHash[userObj.uid] = this;
}
User.uidHash = [];
User.getUserFromObj = function(userObj)
{
    if (User.uidHash[userObj.uid])
    {
        return User.uidHash[userObj.uid];
    }
    else
    {
        return new User(userObj);
    }
}
User.getById = function(id)
{
    return User.uidHash[id];
}

User.createUsersFromArray = function(inArr)
{
    var retArr = [];
    for (var i =0; i < inArr.length; i++)
    {
        retArr.push(new User(inArr[i]));
    }
    return retArr;
}

User.prototype.toggleFollow = function()
{
	
	var post_auth = {"action":"follow","data":{"userid":this.uid}};
	if (!isAuthed(false,post_auth)) return;
	
    var method = 'unsubscribe.php';
    var pClassName = 'btnFollow';
    var pOldClassName = 'btnUnFollow';

    this.following = !this.following;

    if(this.following)
    {
    	method = 'subscribe.php';
    	pClassName = 'btnUnFollow';
        pOldClassName = 'btnFollow';
    }
    
    var pEls = $$('.toggleFollow_'+this.uid);
    pEls.each(function(el){el.removeClassName(pOldClassName);el.addClassName(pClassName);});
    
    new Ajax.Request('/ajax/user/'+method,
    	{
    	  parameters: {'userid':this.uid, cachebust:new Date().getTime() }
    	}
    );
};

User.prototype.clear = function()
{
    this.domObj = null;
};

User.prototype.getAnchor = function(scriptName, scriptData)
{
    var pA;
    var aClass = 'avatarLink' + ((this.userType == 'artist') ? 'artistFrame' : 'userFrame');
    if ((scriptName) && (scriptName != 'undefined'))
    {
        pA = new Element('a',{
            href:'#',
            title:this.displayName,
            className: aClass
        });
        if ((!scriptData) || (scriptData == 'undefined')) scriptData = this.uid;        
        pA.observe('click',scriptName.bindAsEventListener(this,scriptData));
    }
    else
    {
        pA = new Element('a', {
            href:'/' + this.login,
            title:this.displayName,
            className: aClass
        });
    }
    return pA;
}
User.prototype.getGenericLinkText = function()
{
    var pValue = 'visit user profile';
    if (this.userType == 'artist') pValue = 'visit artist profile';
    return pValue;
}


User.prototype.getTile = function(scriptName, scriptData)
{
        var pCell = new Element('td');
        var pRow = new Element('tr');
        var pTable = new Element('table').insert(pRow);
        pRow.insert(pCell);
        pCell.insert(this.getUserDomObj(null,scriptName,null));

        var pCell2 = new Element('td',{className:'th_userTileText'});
        pCell2.insert(userObject.displayName);
        pRow.insert(pCell2);
        return pTable;
}

User.prototype.getUserDomObj = function(showName,scriptName,scriptData,showFollow)
{
    var pHref1, pHref2, pName, pImageRef;
    
    pHref1 = this.getAnchor(scriptName, scriptData);
    pHref2 = this.getAnchor(scriptName, scriptData);
    
    /*
     *<a href="/juanune" title="" class="avatarLink" style="display: block; background-image: url(images/userFrame_ripl.png);"><div style="background-image: url(http://beta.ripl.com/riplContent//juanune/46fb4ea7-b9b0-c1ff-c539-d20d3a332458.jpg);" class="th_user"/></a>
     */
    switch (this.userType)
    {
        case 'artist':
            pImageRef = '/images/userFrames/userFrame_artist.png';
            break;
        case 'system':
            pImageRef = '/images/userFrames/ripl_content.png';
            break;
        default:
            pImageRef = '/images/userFrames/userFrame_ripl.png'
    }
    
    if (this.fanindex > -1)
    {
        pImageRef = '/images/userFrames/superfan_' + (this.fanindex +1);
    }
    pHref1.insert('<img class="th_user" style="background-image: url(\'' + this.avatarurl + '\')" src="'+pImageRef+'" />');
    //return pHref1;
    
    var nameDisplay = 'none';
    if (showName == true)	nameDisplay = 'block';
    
    var pDiv = new Element('div',{style:'width:89px; float:left'});
    pDiv.insert(pHref1);
    
    if(showFollow!=false){
	    var followClass = 'btnFollow';
	    if(this.following==true)
        {
	        followClass = 'btnUnFollow';
        }
	    if(this.isCurrent)	followClass = 'btnFollowSpacer';
        var pFollow = new Element('div',{className:followClass});
	    pFollow.addClassName('toggleFollow_'+this.uid);
	    
	    if(!this.isCurrent) Event.observe(pFollow,'click',this.toggleFollow.bindAsEventListener(this));
	    pDiv.insert(pFollow);
    }
    pDiv.insert(pHref2);
    
    pHref2.insert('<span class="displayName" style="display:'+nameDisplay+'">'+this.displayName+'</span>');
    this.domObj = pDiv;
    return pDiv;
}

$userHelpers = {};
$userHelpers.outputFormats = {'GRID_6_ACROSS':0, 'INLINE':1, 'ROWS':2,'INLINE_SHOWNAME':3};

$userHelpers.userInfo = {
		'default':{'frame':'/images/userFrame_ripl.png', 'cssClass':'th_user'}
};
//This could a prototype method of a user class.
$userHelpers.getFrame = function(userObject)
{ 
    //Temporary.
    return $userHelpers.userInfo['default']['frame'];
};

// This could a prototype method of a user class.
$userHelpers.getCSSClass = function(userObject)
{
    var pCachedUserType = $userHelpers.userInfo['default']; // Just use default for now.  
                                                          // When the user object contains 'account_provider', need to update this.
    if ((pCachedUserType != null) && (pCachedUserType['cssClass'] != null))
    {
        return pCachedUserType['cssClass'];
    }
    else
    {
        return $userHelpers.userInfo['default']['cssClass'];
    }
};

$userHelpers.getUserTile = function(userObject, scriptName,scriptData,cacheData)
{
    var pCell = new Element('td');
    var pRow = new Element('tr');
    var pBody = new Element('tbody');
    pBody.insert(pRow);
    var pTable = new Element('table').insert(pBody);
    pRow.insert(pCell);
    pCell.insert(User.getUserFromObj(userObject).getUserDomObj(null,scriptName,null));

    var pCell2 = new Element('td',{className:'th_userTileText'});
    pCell2.insert(userObject['displayName']);
    pRow.insert(pCell2);
    return pTable;
};

//$userHelpers.getUserTile = function(userObject, scriptName,scriptData,cacheData)
//{
//    return '<div>'+User.getUserFromObj(userObject).getUserDomObj(null,scriptName,null)+'</div><div class="th_userTileText">'+userObject['displayName']+'</div>';
//};

$userHelpers.getHtml = function(userList, format,scriptName)
{
    if (format == null) format = 1;
    switch (format)
    {
        case $userHelpers.outputFormats.GRID_6_ACROSS:
            return $userHelpers._writeGrid(userList, 6,scriptName);
            break;
        case $userHelpers.outputFormats.INLINE:
            return $userHelpers._writeInline(userList,scriptName);
            break;
        case $userHelpers.outputFormats.ROWS:
            return $userHelpers._writeRows(userList,scriptName);
            break;
        case $userHelpers.outputFormats.INLINE_SHOWNAME:
            return $userHelpers._writeInline(userList,scriptName,true);            
            break;
    }    
};

$userHelpers.write = function(userList, outputLocationName, format,scriptName)
{
//    alert($userHelpers.getHtml(userList,format,scriptName).innerHTML);
    $(outputLocationName).update($userHelpers.getHtml(userList,format,scriptName));
};

$userHelpers._writeRows = function(userList,scriptName)
{
    var outArr = [];
    var pLen = userList.length;
    for ( var i = 0; i < pLen; i++)
    {
        outArr.push($userHelpers.getUserTile(userList[i],scriptName));
        outArr.push('<br />');
    }
    return outArr.join('');
};

$userHelpers._writeInline = function(userList,scriptName,showName)
{
    var pDiv = new Element('div',{style:'width:100%'});
    var pLen = userList.length;
    for ( var i = 0; i < pLen; i++)
    {
        pDiv.insert(User.getUserFromObj(userList[i]).getUserDomObj(showName,scriptName,null));
    }    
    return pDiv;
};
$userHelpers._writeGrid = function(userList, rowLength,scriptName)
{
    var pLen = userList.length;
    var pTable = new Element("table");
    var currentTr;
    for ( var i = 0; i < pLen; i++)
    {
        var currentTd = new Element('td');
        if (i % rowLength == 0)
        {
            currentTr = new Element('tr');
            pTable.insert(currentTr);
        }
        currentTd.insert();
        currentTr.insert(currentTd.insert(User.getUserFromObj(userList[i]).getUserDomObj(null,scriptName,null)))
    }    
    return pTable;
};