define(['cla_angular'], function (angular) {
	var moduleName = 'cla.core.breadcrumb';
	try {
		var module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	// Manual singleton as the .service() appears to return multiple instances across Angular apps
	var serviceFunc = null;

	if (serviceFunc === null)
		serviceFunc = breadcrumb_service();

	module.service('breadcrumb.service', function(){return serviceFunc});

	function breadcrumb_service() {
		var service_funcs =
		{
			registerCallback: registerCallback,
			getCrumbs: getCrumbs,
			setCrumbs: setCrumbs,
			lock: lock,
			unlock: unlock
		};

		var crumbs =
		[
			{
				'url': '/',
				'name': 'Home',
				isPages: false
			}
		];

		// Sometimes it might be necessary for a nested app to stop the inner one from changing the breadcrumb
		var locked = false;

		var callback = null;

		return service_funcs;

		function registerCallback(newCallback)
		{
			callback = newCallback;
			if (callback !== null)
				callback();
		}

		function getCrumbs()
		{
			return crumbs;
		}

		function setCrumbs(newCrumbs)
		{
			if (locked)
				return;
			crumbs = angular.extend(newCrumbs, true);
			if (callback !== null)
				callback();
		}

		function lock()
		{
			locked = true;
		}

		function unlock()
		{
			locked = false;
		}
	}
});
