/* Copyright (c) 2006-2007, Apple Inc. All rights reserved. */
var SidebarUpdater = Class.create();
SidebarUpdater.prototype = {
	mRefreshTimeout: 30000, // refresh every 30 seconds
	enabled:true,
	initialize: function() {
		this.mPageListingElm = $('page_listing');
		if($('HotList')) Element.cleanWhitespace('HotList'); // ##5389056
		this.buildIndexFromPage();
		publisher().subscribe(this.handleAuthenticated.bind(this), 'AUTHENTICATED');
		// populate asynchronously so Safari's progress bar finishes
		var callback = function() {
			if (!this.enabled) return false;
			serverui().ensureLogin(this.getSidebarContents.bind(this), 'read', true);
		};
		this.mTimer = setTimeout(callback.bind(this), 10);
	},
	buildIndexFromPage: function() {
		this.mIndex = {};
		$$('#page_listing li.EntryListItem').each(function(li) {
			var parentKey = li.up().id;
			if (!this.mIndex[parentKey]) this.mIndex[parentKey] = {};
			var uid = li.down('a').getAttribute('href').replace(/^(https?:\/\/[^\/]+\/|\/)/, '').replace(/(\/|\/[^\/]+.html)$/, '');
			this.mIndex[parentKey][uid] = {mElement:li};
		}.bind(this));
	},
	getSidebarContents: function() {
		if (this.mTimer) {
			clearTimeout(this.mTimer);
			delete this.mTimer;
		}
		server().wiki.getSidebarEntries([this.gotSidebarContents.bind(this), invalidate], uid().mBasePath);
	},
	gotSidebarContents: function(inRequestObj, inResponseObj) {
		$H(inResponseObj).each(function(parent) {
			if (!this.mIndex[parent.key]) this.mIndex[parent.key] = {};
			
			var syncStatus = Array.syncKeyedArrayWithRows(this.mIndex[parent.key], parent.value);
			// add new rows
			syncStatus.addedRows.each(function(item) {
				// create DOM stuff
				var href = item.url;
				var subDate = createDateObjFromISO8601(item.subtitle);
				var li = Builder.node('li', {className:'EntryListItem', style:'display:none'}, [
					Builder.node('a', {href:href}, [item.title]),
					' ', /* space for printing */
					Builder.node('span', {className:'snippet'}, [subDate ? Loc.getLongDateString(subDate) : item.subtitle])
				]);
				// add item to the index
				this.mIndex[parent.key][item.uid]['mElement'] = li;
				// add the element to the parent list
				insertAtBeginning(li, $(parent.key));
				if (this.mAnimate) var effect = new Effect.BlindDown(li, {duration:0.2, scaleContent:false});
				else Element.show(li);
			}.bind(this));
			// remove deleted rows
			syncStatus.deletedRows.each(function(item) {
				gTooltipManager.stopObserving(item.mElement.firstChild);
				var removeAfterFinish = function(inEffect) {
					Element.remove(inEffect.element);
				};
				var effect = new Effect.BlindUp(item.mElement, {duration:0.2, afterFinish:removeAfterFinish});
			});
		}.bind(this));
		// look for new link preview tooltips
		gLinkPreviewGenerator.scan();
		// force reflow in Tiger Safari
		if (SafariFixes.isTigerSafari) d.getElementsByClassName('endmain').each(function(forceElm) {Element.forceReflow(forceElm)});
		// turn on animation in other browsers
		else this.mAnimate = true;
		// reset the timer
		if (this.mTimer) {
			clearTimeout(this.mTimer);
			delete this.mTimer;
		}
		this.mTimer = setTimeout(this.getSidebarContents.bind(this), this.mRefreshTimeout);
		if (window.unitTestHandler) unitTestHandler.messageFromJS_('gotSidebarContents');
	},
	startEdit: function() {
		this.mPageListingElm.style.opacity = '0.4';
		$A(this.mPageListingElm.getElementsByTagName('a')).each(function(elm) {
			elm.target = '_blank';
		});
	},
	endEdit: function() {
		this.mPageListingElm.style.opacity = '';
		$A(this.mPageListingElm.getElementsByTagName('a')).each(function(elm) {
			elm.target = '';
		});
	},
	handleAuthenticated: function(inMessage, inObject, inUserInfo) {
		// shut down the refresh timer
		if (this.mTimer) {
			clearTimeout(this.mTimer);
			delete this.mTimer;
		}
		// callback happens when content is reloaded (or fails... no real need to draw a distinction here)
		var callback = function(inSuccess) {
			// rebuild the index
			this.buildIndexFromPage();
			// restart the refresh timer
			this.getSidebarContents();
		}
		Element.reload('page_listing', callback.bind(this));
	}
}

if (window.loaded) loaded('grouphome.js');