pwUser = {

    getUser:    function (callback, uid, targetUid) {
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(new UserKey(uid));
        if ((uid || uid === '') && Number(targetUid) && targetUid != uid) {
            requestBatch.AddToRequest(new UserKey(targetUid));
        }
        requestBatch.BeginRequest(pwUser.community.sitelifeServerURL, callback);
    },

    drawUser:    function (responseBatch) {
        if (responseBatch.Responses.length === 0) {
            gSiteLife.InnerHtmlWrite("utilityWelcomeMessage", "SiteLife Error");
        } else {
            //pwUser.messaging.details(responseBatch);
            var curUser = responseBatch.Responses[0].User;
            pwUser.pluckUser = curUser;
            if (curUser.UserKey && curUser.UserKey.Key != 'anonymous') {
                pwUser.uid = curUser.ExtendedProfile.u;
            }

            var personaUser = responseBatch.Responses[1];
            if (personaUser && personaUser.User && personaUser.User.ExtendedProfile
                    && personaUser.User.ExtendedProfile.u && Number(personaUser.User.ExtendedProfile.u)) {
                personaUser = Number(personaUser.User.ExtendedProfile.u);
            } else {
                personaUser = pwUser.uid;
            }
            pwUser.personaTarget = {uid: personaUser};
            $("PWUserName").fire('pw:pluck:persona:uid',
            {personaUid: pwUser.personaTarget.uid, internal: 'drawUser'});

            var avatarImg = $("PWUserAvatarImg");
            if (avatarImg) {
                avatarImg.src = curUser.AvatarPhotoUrl;
            }
            var personaLink = function(linkId, linkee) {
                var linker = $(linkId);
                linker.href = curUser.PersonaUrl;
                if (linkee) {
                    linker.appendChild($(linkee).remove());
                }
            };

            if (pwUser.uid) {
                $("PWUserName").update(', <a id="PWUserNameLink" href="">' + curUser.DisplayName + '</a>');
                if (avatarImg) {
                    personaLink("PWUserAvatarLink", "PWUserAvatar");
                }
                personaLink("PWUserNameLink");
                $("login-link").hide();
                $("logout-link").show();
                $("register-link").hide().insert({after: '| <a id="my-profile-link">My Profile</a>'});
                personaLink("my-profile-link");
            } else { // not logged in
                $("PWUserName").update('!');
                $("logout-link").hide();
                $("login-link").show();
            }
        }
    },

    showUser:    function () {
        if (arguments.length && pwUser.lookup && arguments[0].result) {
            pwUser.lookup.result = arguments[0].result;
            document.cookie = pwUser.lookup.result;
        }
        pwUser.getUser(pwUser.drawUser, '', gSiteLife.GetParameter('uid'));
    },

    conceal: function(x) {x.addClassName('hidden');},
    reveal: function(x) {x.removeClassName('hidden');},

    community: {
        sitelifeServerURL: pwSitelifePrefix + "/ver1.0/Direct/Process",
        sitelifeVideoUploadURL: pwSitelifePrefix + "/ver1.0/Video/Upload",
        NumberPerPage: 10,
        pageNum : 1
    }

};

//function searchUser() {
//  var requestBatch = new RequestBatch();
//  requestBatch.AddToRequest(new UserKey());
//	requestBatch.BeginRequest(pwSitelifePrefix + "/ver1.0/Direct/Process", drawUser);
//}

pwUser.messaging = {
    warning: (typeof console === 'object' && typeof console.log === 'function') ? console.log : function() {},
    exception: (typeof console === 'object' && typeof console.log === 'function') ? console.log : function() {},
    detail: (typeof console === 'object' && typeof console.dir === 'function') ? console.dir : function() {}
};

pwUser.community.startUserSearch = function() {
	try {
		   $('resultsTotalCnt').update('');
		   pwUser.community.userlist.update('');
		   var buttons = ['All'].concat($A($R('A', 'Z')));
		   $('pluckbrowseindex').update('<ul id="pluckbrowseindexul" class="search-index"></ul>');
		   $('pluckbrowseindexul').insert({bottom: buttons.inject([], function(array, value, index){
			    array.push( '<li id="' + value + '">' + value + '</li>');
			    return array;
			    }).join('')
	   		});
		   buttons.each(function(value){
			   $(value).observe('click', pwUser.community.renderLastInitial);
		    });
		   pwUser.community.userlist.insert({bottom: buttons.inject([], function(array, value, index){
			   array.push('<li id="list' + value + '" class="letter-start" />');
			   return array;
			   }).join('')
		    });
		   $('All').style.width = '20px';
		var searchTextValue=$('browsequery').value.strip();
		if (searchTextValue==='') {searchTextValue = 'Public';}
		pwUser.community.searchPage({SearchString: searchTextValue + '*', OnPage: 0});
	} catch(e) {
		pwUser.messaging.exception(e,' in pennwell_user.js','pwUser.community.startUserSearch');
	}

	if (searchTextValue && $('browsequery').value && searchTextValue.length >=3) {
		new Ajax.Request( document.location.pathname.replace(/\.html$/, '.userlookup.html?') + new Date().getTime(), {
	        method : 'post',
	        parameters : {
	            act: 'search',
	            q: searchTextValue
	        },
	        onSuccess : function( transport ) {
	            var json = transport.responseText.evalJSON( true );
	            if ( json != null && json.result && json.result.length && json.result.length > 0) {
//	            	pwUser.messaging.detail(json);
	            	pwUser.community.userlookup = json.result;
	            	pwUser.community.confirmUsers(0);
	            }
	        }
		});
    }

};

pwUser.community.confirmUsers = function(offset) {
	try {
    var requestBatch = new RequestBatch();
	for (var i = 0; (i < 20) && (i + offset < pwUser.community.userlookup.length); i++) {
		requestBatch.AddToRequest(new UserKey(pwUser.community.userlookup[i + offset] + ""));
	}
//	pwUser.messaging.detail(requestBatch);
	requestBatch.BeginRequest(pwUser.community.sitelifeServerURL, function(responseBatch) {
		pwUser.community.renderUserList(responseBatch, offset);
		});
	} catch (e) {
		pwUser.messaging.exception(e,' in pennwell_user.js','pwUser.community.confirmUsers');
	}
};

pwUser.community.searchPage = function(searchResult) {
	try {
		var pageNum = Number(searchResult.OnPage) + 1;
		var requestBatch=new RequestBatch();
		requestBatch.AddToRequest(new SearchAction("user", searchResult.SearchString,
				pwUser.community.NumberPerPage, pageNum));
//    	pwUser.messaging.details(requestBatch);
        requestBatch.BeginRequest(pwUser.community.sitelifeServerURL, pwUser.community.renderUserList);}
	catch(e){pwUser.messaging.exception(e,' in pennwell_user.js','pwUser.community.searchPage');}
};

pwUser.community.renderUserList = function(responseBatch, offset) {
//	pwUser.messaging.details(responseBatch);
	try{
		if(responseBatch===undefined||responseBatch===null||responseBatch.Responses===undefined||responseBatch.Messages[0].Message==="Down"){
			var mainContent=$('mainBucket');
			mainContent.innerHTML="<h3>Community features and content are unavailable at this time. We apologize for the inconvenience. Please try this page later.</h3>";
			$('#main_sidebar').hide();
			return;
		}
		if (responseBatch.Responses.length >= 1) {
			var searchResult=responseBatch.Responses[0].SearchResult;
			var done=false, i;
//			if(searchResult.NumberOfSearchResults==="0"){
//				htmlResults='<p class="error">We didn\'t find any people that matched your search.</p>';
//			}
//			else{
			if (searchResult) {
//				pwUser.community.searchResults = {response: responseBatch};
				for(i=0;i<searchResult.SearchResults.length;i++) {
					if (pwUser.community.insertUserWithoutSorting(searchResult.SearchResults[i]) >= pwUser.community.maxCount) {
						done = true;
						break;
					}
				}
				var totalResults = searchResult.NumberOfSearchResults;
				var totalPages=Math.ceil(totalResults/pwUser.community.NumberPerPage);
				pwUser.community.totalPages = totalPages;
				if(!done && searchResult.OnPage < totalPages){
					pwUser.community.searchPage(searchResult);
				}
			} else if (responseBatch.Responses[0].User) {
//				pwUser.community.userResult = responseBatch;
				for (i=0; i<responseBatch.Responses.length; i++) {
					if (responseBatch.Responses[i].User.UserKey.Key != pwUser.community.userlookup[i + offset]) {
						continue;
					}
					if (pwUser.community.insertUserWithoutSorting(responseBatch.Responses[i].User) >= pwUser.community.maxCount) {
						done = true;
						break;
					}
				}
				if (!done && responseBatch.Responses.length + offset < pwUser.community.userlookup.length - 1) {
					pwUser.community.confirmUsers(offset + responseBatch.Responses.length);
				}
			}
//			$$(".searchresults")[0].update(htmlResults);
//			pwUser.community.renderPageNav(searchResult.NumberOfSearchResults);
		}
		else{
			pwUser.messaging.warning(responseBatch.Responses.length+' results returned','pwUser.community.renderUserList');
		}
        pwUser.community.renderLastInitial('All');
	}catch(e){
		pwUser.messaging.exception(e,' in pennwell_user.js','pwUser.community.renderUserList');
	}
};

pwUser.community.insertUser = function(user) {
	var lastInitial = user.ExtendedProfile.l;
	if (lastInitial) lastInitial = lastInitial.slice(0,1).toUpperCase();
	if (!lastInitial) {
		return;
	}
	var ul = pwUser.community.userlist;
	var id = lastInitial + user.ExtendedProfile.u;
	if (ul.select("#" + id)[0]) {
		return; //duplicate
	}
	var totalCnt = Number($('resultsTotalCnt').collectTextNodes());
	if (totalCnt >= pwUser.community.maxCount) {
		return totalCnt;
	}
	var loc = ul.select("#list" + lastInitial)[0];
	if (loc) {
		var sortKey = (user.ExtendedProfile.l.strip() + '.' + user.ExtendedProfile.f.strip()).toLowerCase();
		var htmlResult = pwUser.community.getUserSearchResultAsHTML(user, {id: id, sortKey: sortKey});
		var curlist = ul.select('li[id^="' + lastInitial + '"]');
		for (var i=0; i < curlist.length && sortKey > curlist[i].getAttribute('pw-sort-key'); i++) {
			loc = curlist[i];
		}
		loc.insert({after: htmlResult});
		var nodeRef = $(id);
		if (nodeRef) {
			$(lastInitial).title = Number($(lastInitial).title) + 1;
			totalCnt++;
			$('resultsTotalCnt').update(totalCnt);
			if (totalCnt > pwUser.community.showCount) {
				pwUser.conceal(nodeRef);
			}
		}
	}
	return totalCnt;
};

pwUser.community.insertUserWithoutSorting = function(user) {
	var lastInitial = user.ExtendedProfile.l;
	if (lastInitial) lastInitial = lastInitial.slice(0,1).toUpperCase();
	if (!lastInitial) {
		return;
	}
	var ul = pwUser.community.userlist;
	var id = lastInitial + user.ExtendedProfile.u;
	if (ul.select("#" + id)[0]) {
		return; //duplicate
	}
	var totalCnt = Number($('resultsTotalCnt').collectTextNodes());
	if (totalCnt >= pwUser.community.maxCount) {
		return totalCnt;
	}
	var loc = ul.select("#list" + lastInitial)[0];
	if (loc) {	
		var htmlResult = pwUser.community.getUserSearchResultAsHTML(user, {id: id});
		ul.insert({bottom: htmlResult});
		var nodeRef = $(id);
		if (nodeRef) {
			$(lastInitial).title = Number($(lastInitial).title) + 1;
			totalCnt++;
			$('resultsTotalCnt').update(totalCnt);
			if (totalCnt > pwUser.community.showCount) {
				pwUser.conceal(nodeRef);
			}
		}
	}
	return totalCnt;
};

pwUser.community.getUserSearchResultAsHTML=function(userSearchResult, opt){
	try{
		if(userSearchResult.IsBlocked==="True" && userSearchResult.UserKey.Key != pwUser.uid){
			return'<!-- Blocked user -->';
		}
		//following line is used for displaying sorted results...
		//var userhtml='<li id="' + opt.id + '" pw-sort-key="' + opt.sortKey + '">';
		
		//sorting causes pop-in effect, remove sorting for now...
		var userhtml='<li id="' + opt.id + '">';
		var usersProfilePage = pwUser.community.profilePage+'?uid='+userSearchResult.UserKey.Key;
		userhtml+='<a href="' + usersProfilePage + '">';
		userhtml+='<img src="'+userSearchResult.AvatarPhotoUrl+'" alt="'+userSearchResult.DisplayName+'" height="30" width="30" />';
		userhtml+='</a>';
		userhtml+='<p class="user">';
		userhtml+='<a href="' + usersProfilePage + '">';
		userhtml+=userSearchResult.DisplayName;
		userhtml+='</a>';
		if(userSearchResult.UserTier==='Staff'||userSearchResult.UserTier==='Editor'){
			if(userSearchResult.ExtendedProfile.StaffTitle!==undefined&&userSearchResult.ExtendedProfile.StaffTitle!==null){
				userhtml+='<br><span class="staffhdr">PennWell STAFF:</span> '+userSearchResult.ExtendedProfile.StaffTitle;
			}
			else{
				userhtml+='<br><span class="staffhdr">PennWell STAFF</span> ';
			}
		}
		else{
			if(userSearchResult.Location!==undefined&&userSearchResult.Location.length>0){
				userhtml+='<br>&nbsp;'+userSearchResult.Location;
			}
		}
		userhtml+='</p>';
		userhtml+='<div class="spacer">&nbsp;</div>';
		userhtml+='</li>';
		return userhtml;
	}catch(e){
		pwUser.messaging.exception(e,' in pennwell_user.js','pwUser.community.getUserSearchResultAsHTML');
	}
	return '';
};

pwUser.community.renderPageNav=function(totalResults){
    var resultsPerPage = pwUser.community.showCount;
    try{
		var totalPages=Math.ceil(totalResults/resultsPerPage);
		if(totalPages===1){
			$('pagenav').hide();
			return;
		} else {
			$('pagenav').show();
		}
	} finally {
	}

	var firstPageInNav=(Math.floor((pwUser.community.pageNum-1)/resultsPerPage)*resultsPerPage)+1;
	var lastPageInNav=Math.min(totalPages,(firstPageInNav+10));        // TODO atom for max number of nav links?
	var html="";
	if(pwUser.community.pageNum>1){
		var previousPage=pwUser.community.pageNum-1;
		html+='<li><a href="#" onclick="pwUser.community.showpage('+previousPage+');return false;">Previous</a></li>';
	}
	for(var p=firstPageInNav;p<=lastPageInNav;p++){
		if(p===pwUser.community.pageNum){
			html+='<li><strong>'+p+'</strong></li>';
		}
		else{
			html+='<li><a href="#" onclick="pwUser.community.showpage('+p+');return false;">'+p+'</a></li>';
		}
	}
	if(pwUser.community.pageNum < lastPageInNav){
		var nextPage=pwUser.community.pageNum+1;
		html+='<li><a href="#" onclick="pwUser.community.showpage('+nextPage+');return false;">Next</a></li>';
	}
	$('pagenav').innerHTML = html;
};

pwUser.community.showpage = function(pageNumber) {
    pwUser.community.pageNum = pageNumber;

    var excluded = $$('li.currentExcludedResults');
    var included = $$('li.currentIncludedResults');

    excluded.each(pwUser.conceal);
    included.eachSlice(pwUser.community.showCount, function(pageOfProfiles, index) {
    	pageOfProfiles.each(index + 1 === pageNumber ? pwUser.reveal : pwUser.conceal);
    });
    pwUser.community.renderPageNav(included.size());
    if (included.size() > 0) {
        $('pluckbrowsenoresults').hide();
    } else {
        $('pluckbrowsenoresults').show();
    }

};

pwUser.community.renderLastInitial = function(event) {
    $$('ul#pluckbrowseindexul li.global-nav-highlighted-bg').invoke('removeClassName', 'global-nav-highlighted-bg');
    var element=typeof event === 'string' ? $(event) : event.element();
	element.addClassName('global-nav-highlighted-bg');
    var lastInitial = element.identify();
	var children = pwUser.community.userlist.childElements();
	for (var i=0; i<children.length; i++) {
        var id = children[i].identify();
        if ((lastInitial === 'All' && !id.startsWith('list')) || id.startsWith(lastInitial.toUpperCase())) {
            children[i].addClassName("currentIncludedResults");
            children[i].removeClassName("currentExcludedResults");
		} else {
            children[i].addClassName("currentExcludedResults");
            children[i].removeClassName("currentIncludedResults");
		}
	}
    pwUser.community.showpage(1);
};
