var appHistory = (function() {
	function _pad(num) {
		return num < 10 ? '0' + num : num;
	}
	
	function _getTimeStr(date) {
		var date = date ? new Date(date) : new Date();
		var dateStr = [];
		dateStr.push(_("appcenter.history.date", [_pad(date.getFullYear()), _pad(date.getMonth() + 1), _pad(date.getDate())]) + " ");
		dateStr.push(_pad(date.getHours()));
		dateStr.push(':');
		dateStr.push(_pad(date.getMinutes()));
		return dateStr.join('');
	}
	
	function _createItem(app) {
		var div = document.createElement('div');
		div.id = 'opened-app-item-' + app.uid;
		div.className = 'opened-app-item div-table full-size';
		
		var html = [];
		html.push('<div>')
		html.push('	<div>');
		html.push('		<div class="app-icon-box">');
		html.push('			<div>');
		var iconUrl = app.icon_data_url && app.icon_data_url.indexOf("data:image") == 0 ?
							app.icon_data_url : app.icon_url;
		// Resource page have no priority to access favicon url
		// Data migrated from livemargins could be favicon url, so strip the prefix.
		iconUrl = iconUrl.replace(/moz-anno:favicon:/i, "");
		var iconClassName = "";
		if (iconUrl && iconUrl.indexOf("http") == 0) {
			iconClassName = "app-icon-todataurl";
		}
		html.push('				<img class="' + iconClassName + '" src="' + iconUrl + '"/>')
		html.push('			</div>');
		html.push('		</div>');
		html.push('	</div>');
		html.push('	<div>');
		html.push('		<div class="app-name text-ellipsis"> ' + xmlFilter(app.name) + '</div>');
		html.push('		<div class="last-opened-time text-ellipsis"> ' + _getTimeStr(app.last_opened) + '</div>');
		html.push('	</div>');
		html.push('	<div class="ops">');
		html.push('		<button class="addon-control opt-btn-open">' + _("appcenter.history.open") + '</button>');
		html.push('		<button class="addon-control opt-btn-remove">' + _("appcenter.history.remove") + '</button>');
		if (app.bookmark == 1) {
			html.push('	<button class="ops-bookmark addon-control" style="display: none;">' + _("appcenter.history.bookmark") + '</button>');
		} else {
			html.push('	<button class="ops-bookmark addon-control">' + _("appcenter.history.bookmark") + '</button>');
		}
		html.push('	</div>');
		html.push('</div>');
		div.innerHTML = html.join('');
		
		_addListeners(div, app);
		
		return div;
	}
	
	function _addListeners(aDiv, app) {
		$(".opt-btn-open", aDiv).click(function(event) {
			_appHistory.openApp(app.uid);
		});
		$(".opt-btn-remove", aDiv).click(function(event) {
			_appHistory.clearItem(app.uid);
			_$t.track(_$t.app.type, _$t.app.actions.REMOVE_HISTORY, app.uid);	
		});
		$(".ops-bookmark", aDiv).click(function(event) {
			_appHistory.bookmarkApp(app.uid);
		});
		$("img.app-icon-todataurl", aDiv).bind("load", function(event) {
			_appHistory.onAppIconLoaded(this, app.uid);
		});
	}
	
	var _startIdx = 0;
	var _size = 20;
	function _fillWithAppList() {
		var apps = contentAPI.appCenterDAO.getRecentApps(_startIdx, _size);
		_startIdx += apps.length;
		apps.forEach(function(app) {
			if (!_$('opened-app-item-' + app.uid)) {
				_$('history_box').appendChild(_createItem(app));
			}
		});
		_checkIfEmpty();
		return apps.length;
	}
	
	function _autoFillWithApp() {
		function checkScrollbar() {
			// Only do checking when apps-history-box is shown.
			if ($("#apps-history-box").css("display") == "none") {
				return;
			}
			
			var box = $("#apps-history-box")[0];
			var total = contentAPI.appCenterDAO.getRecentAppsCount();
			var current = $("#history_box > div.opened-app-item").length;
			if (total == current) {
				return;
			}
			
			// Show more history when scrollbar is not shown.
			if (box.clientHeight == box.scrollHeight) {
				_fillWithAppList();
				return;
			}
			
			// Show more history when scrollbar is scrolled to bottom.
			if (box.clientHeight + box.scrollTop > box.scrollHeight - 10) {
				_fillWithAppList();
				return;
			}
		}
		checkScrollbar();
		window.setInterval(function() {
			checkScrollbar();
		}, 500);		
	}
	
	function _initAppList() {
		_$('history_box').innerHTML = '';
		_startIdx = 0;
		_autoFillWithApp();
		_checkIfEmpty();
	}
	
	function onUnbookmarkApp(uid) {
		var div = _$('opened-app-item-' + uid);
		if (!div) {
			return;
		}
		$(div).find('div.ops > button.ops-bookmark')[0].style.display = '';
	}
	
	function onBookmarkApp(uid) {
		var div = _$('opened-app-item-' + uid);
		if (!div) {
			return;
		}
		$(div).find('div.ops > button.ops-bookmark')[0].style.display = 'none';
	}
	
	function onOpenApp(uid) {
		var div = _$('opened-app-item-' + uid);
		if (div) {
			_$('history_box').insertBefore(div, _$('history_box').childNodes[0]);
			return;
		}
		
		div = _createItem(contentAPI.appCenterDAO.getAppByUID(uid));
		if (_$('history_box').childNodes.length > 0) {
			_$('history_box').insertBefore(div, _$('history_box').childNodes[0]);
		} else {
			_$('history_box').appendChild(div);
		}
		_checkIfEmpty();
	}
	
	function onChangeAppName(uid) {
		if (!_$('opened-app-item-' + uid)) {
			return;
		}
		
		// reload app name from database.
		var div = $('#opened-app-item-' + uid).find('div.app-name')[0];
		var newDiv = document.createElement(div.tagName);
		newDiv.className = div.className;
		newDiv.textContent = contentAPI.appCenterDAO.getAppName(uid);
		div.parentNode.insertBefore(newDiv, div);
		$(div).remove();
	}
	
	function bookmarkApp(uid) {
		contentAPI.appCenter.bookmarkApp(uid, true);
		onBookmarkApp(uid);
		contentAPI.appCenter.appPref.updatePref('bookmark', uid, _observer);
	}
	
	var _observer = {
		onChangeName: function(uid) {
			onChangeAppName(uid);
		}, 
		
		onUnbookmark: function(uid) {
			onUnbookmarkApp(uid);
		},
		
		onBookmark: function(uid) {
			onBookmarkApp(uid);
		},
		
		onOpenApp: function(uid) {
			onOpenApp(uid);
		},
		
		onClearHistory: function(uid) {
			if (uid) {
				if (_$('opened-app-item-' + uid)) {
					$('#opened-app-item-' + uid).remove();
				}
			} else {
				_initAppList();
			}
			_checkIfEmpty();
		}
	};
	
	function _checkIfEmpty() {
		if ($("#history_box > div.opened-app-item").length == 0) {
			$("#apps-history-box").addClass("empty");
		} else {
			$("#apps-history-box").removeClass("empty");
		}
	}
	
	var _initialized = false;	
	var _appHistory = {
		init: function() {
			if (_initialized) {
				return;
			}
			_initialized = true;
			appHistory.initAppList();	
		},
		
		initAppList: function() {
			_initAppList();
		},
		
		bookmarkApp: function(uid) {
			bookmarkApp(uid);
		},
		
		openApp: function(uid) {
			// do not update opened time.
			contentAPI.appCenter.openApp(uid, false);
		},
		
		addObserver: function() {
			contentAPI.appCenter.appPref.addObserver(_observer);
		},
		
		removeObserver: function() {
			contentAPI.appCenter.appPref.removeObserver(_observer);
		},
		
		clearItem: function(uid) {
			contentAPI.appCenterDAO.resetOpenedTimeByUID(uid);
			contentAPI.appCenter.appPref.updatePref('clearhistory', uid, _observer);
		},
		
		clearHistory: function() {
			// Only reset opened time here
			// Make sure that the opening app window is working after clearing history.
			// Delete unbookmarked app when firefox is restarted.
			contentAPI.appCenterDAO.resetAppOpenedTime();
			contentAPI.appCenter.appPref.updatePref('clearhistory', '', _observer);
			_$t.track(_$t.app.type, _$t.app.actions.CLEAR_HISTORY, 0);	
		},
		
		resizeHistoryBox: function(event) {
			var height = document.body.clientHeight - document.body.querySelectorAll('#layout > div')[0].clientHeight - 2;
			_$('apps-history-box').style.height = height + 'px';
		},
		
		onAppIconLoaded: function(img, uid) {
			// FIXME this is hard code to set styles for image
			// make sure get larger image data url.
			img.setAttribute("style", "max-height: 64px !important; max-width: 64px !important;");
			contentAPI.appCenterDAO.updateIconDataUrl(uid, contentAPI.getImageDataURL(img));
			img.setAttribute("style", "");
		}
	};
	
	return _appHistory;
})();

registerInitListener(function(event) {
	try {
		contentAPI.appCenter.removeUntrackedApps();
	} catch (e) {
		// alert(e);
	}
	
	appHistory.addObserver();
	appHistory.resizeHistoryBox(event);
});

window.addEventListener('resize', appHistory.resizeHistoryBox, false);

window.addEventListener('unload', function() {
	appHistory.removeObserver();
}, false);
