/*
Adapted from https://github.com/No9/localstorage-down
963999
function AsyncStorageCore(dbname, opts = DEFAULT_OPTS) {
  this._prefix = createPrefix(dbname);
  this._asyncStorageImpl = opts.AsyncStorage
}
490807
function (key) {
      if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
        if (!browserSupportsLocalStorage) {
          $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        }

        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
        }
        return removeFromCookies(key);
      }

      try {
        webStorage.removeItem(deriveQualifiedKey(key));
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: self.storageType});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return removeFromCookies(key);
      }
      return true;
    }
1374620
function save(storage, name, value) {
      try {
        var key = propsPrefix + name;
        if (value == null) value = '';
        storage[key] = value;
      } catch (err) {
        console.log('Cannot access local/session storage:', err);
      }
    }
391355
function _initStorage$2(options) {
    var self = this;
    var dbInfo = {};
    if (options) {
        for (var i in options) {
            dbInfo[i] = options[i];
        }
    }

    dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);

    if (!_isLocalStorageUsable()) {
        return Promise$1.reject();
    }

    self._dbInfo = dbInfo;
    dbInfo.serializer = localforageSerializer;

    return Promise$1.resolve();
}
777578
function LocalStore (options) {
  options = options || {};

  options.max = Number(options.max);
  if (isNaN(options.max)) options.max = DEFAULT_MAX;
  this._max = options.max;

  options.gcProbability = Number(options.gcProbability);
  if (isNaN(options.gcProbability)) options.gcProbability = DEFAULT_PROBABILITY;
  this._gcProbability = options.gcProbability;

  options.path = options.path || DEFAULT_PATH;
  this._path = options.path;

  options.type = options.type || DEFAULT_TYPE;
  this._type = options.type;
  this._storage = getStorage(this._type, this._path);

  options.prefix = options.prefix || DEFAULT_PREFIX;
  this._prefix = options.prefix;

  debug('init: type=%s, prefix=%s, path=%s, max=%s, gcProbability=%s', this._type, this._prefix, this._path, this._max, this._gcProbability);

  this._setKeyTotal(this._itemLength());
  debug('keyTotal=%s', this._getKeyTotal());

  return this;
}
652709
function LacesLocalModel(key) {

    var data = localStorage.getItem(key);
    var object = data && JSON.parse(data) || {};

    Laces.Model.call(this, object);

    this.bind("change", function() { localStorage.setItem(key, JSON.stringify(this)); });
}
466320
function microStorage ( namespace ) {

    list[namespace] = list[namespace] || {};
    localStorage.setItem(packageName, JSON.stringify(list));

    /**
    * Get or set value from storage
    * @param {String} name key
    * @param {AnyType} value value
    * @return {AnyType} value
    */
    function storage ( name, value ) {
        if (arguments.length == 0) {
            return;
        }
        if (arguments.length == 1) {
            let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`));
            return result ? result.$ : result;
        }
        localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value }));
        list[namespace][name] = '';
        localStorage.setItem(packageName, JSON.stringify(list));
        return value;
    };

    /**
    * Remove value from storage
    * @param {String} name key
    */
    storage.remove = function ( name ) {
        localStorage.removeItem(`${ namespace }.${ name }`);
        delete list[namespace][name];
        localStorage.setItem(packageName, JSON.stringify(list));
    };

    /**
     * Return value list of storage
     * @return {Array} list list of storage
     */
    storage.list = function () {
        return Object.keys(list[namespace]);
    };

    /**
     * Clear all value from storage
     */
    storage.clear = function () {
        this.list().forEach(( name ) => {
            this.remove(name);
        });
    };

    return storage;
}
875175
function(obj) {
        if (window.localStorage) {
            var tile = obj.tile;
            try {
                var canvasContext = tile.getCanvasContext();
                if (canvasContext) {
                    var urlMap = OpenLayers.Control.CacheWrite.urlMap;
                    var url = urlMap[tile.url] || tile.url;
                    window.localStorage.setItem(
                        "olCache_" + url,
                        canvasContext.canvas.toDataURL(this.imageFormat)
                    );
                }
            } catch(e) {
                // local storage full or CORS violation
                var reason = e.name || e.message;
                if (reason && this.quotaRegEx.test(reason)) {
                    this.events.triggerEvent("cachefull", {tile: tile});
                } else {
                    OpenLayers.Console.error(e.toString());
                }
            }
        }
    }
1117516
function getStoredToken (storageLocation) {
	var token = readCookie(storageLocation);
	if (!token && (window && window.localStorage || window.sessionStorage)) {
		token = window.sessionStorage.getItem(storageLocation) || window.localStorage.getItem(storageLocation);
	}
	return token;
}
669483
function overwriteBrowserStorage(){
    if((browser && store) || storageMock){
      var db = cache;
      try {
        db = JSON.stringify(db);
        store.setItem(storageKey, db);
      } catch (err) { /* Do nothing */ }
    }
  }
1368309
function (key, value) {

      // If this browser does not support local storage use cookies
      if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
        if (!browserSupportsLocalStorage) {
            $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        }

        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
        }
        return addToCookies(key, value);
      }

      // Let's convert undefined values to null to get the value consistent
      if (typeof value === "undefined") {
        value = null;
      }

      try {
        if (angular.isObject(value) || angular.isArray(value)) {
          value = angular.toJson(value);
        }
        if (webStorage) {webStorage.setItem(deriveQualifiedKey(key), value)};
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: self.storageType});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return addToCookies(key, value);
      }
      return true;
    }
917352
function() {
			localStorage.removeItem(constants.LOCAL_STORAGE_TEMP_RULES_KEY);
			localStorage.removeItem(constants.LOCAL_STORAGE_SELECTED_RULES_KEY);
			localStorage.removeItem(constants.LOCAL_STORAGE_SELECTED_CONTEXT_KEY);
			localStorage.removeItem(constants.LOCAL_STORAGE_SELECTED_CONTEXT_COMPONENT_KEY);
			localStorage.removeItem(constants.LOCAL_STORAGE_SELECTED_VISIBLE_COLUMN_KEY);
			localStorage.removeItem(constants.LOCAL_STORAGE_SELECTION_PRESETS_KEY);
			localStorage.removeItem(constants.LOCAL_STORAGE_CUSTOM_PRESETS_KEY);
		}
1028462
function LacesLocalArray(key) {

    var data = localStorage.getItem(key);
    var elements = data && JSON.parse(data) || [];

    var array = Laces.Array.call(this);
    for (var i = 0, length = elements.length; i < length; i++) {
        array.push(elements[i]);
    }

    array.bind("change", function() { localStorage.setItem(key, JSON.stringify(this)); });

    return array;
}
733256
function setUserCache(key, value) {
    var userCode = this.getEnvironment().usercode;
    if (!userCode) return;
    localStorage.setItem(userCode + key, value);
}
947781
function(localStorage,paths,namespace) {

	var pathGraph = '',
		nodeGraph = '',
		rootNodeGraph = '',
		i = 0,
		l = 0;
	
	var toIdentifier = function(src) {
		if (src.match(/\:/)) {
			var x = src.split(':');
			return x[0].replace(/[^0-9a-zA-Z]/g,'_')+':'+x[1];
		}
		return src.replace(/[^0-9a-zA-Z]/g,'_');
	};

	var toNode = function(src) {
		var kr = '',
			r = [];
			var getInnerRec = function(item) {
				var r = [],
					k = '';
				for (k in item) {
					if (item.hasOwnProperty(k)) {
						r.push(''+k+':'+JSON.stringify(item[k])
							.replace(/"/g,'\\"')
							.replace(/\{/g,'\\{')
							.replace(/\}/g,'\\}')
							.replace(/\|/g,'|')
							.replace(/\(/g,'(')
							.replace(/\)/g,')')
						);
					}
				}
				return r.join('|');
			};
		var item = JSON.parse(localStorage.getItem(namespace + '.'+src.replace(/\:.*/,'')));
		if (src.match(/\:/)) {
			for (kr in item) {
				if (item.hasOwnProperty(kr)) {
					r.push(
						(r.length ? '' : src.replace(/\:.*/,'') + '|') +
						'{ <'+kr+"> "+kr+" |{"+getInnerRec(item[kr])+'}}'
					);
				}
			}
			return toIdentifier(src) + ' [label="'+r.join('|')+'"];';
		}
		return toIdentifier(src) + ' [label="'+src+'|'+getInnerRec(item)+'"]' + ";\n";
	};
	
	for (i=0, l=paths.length; i<l; i++) {
		if (paths[i].from.match(/\:/)) {
			rootNodeGraph = rootNodeGraph + toNode(paths[i].from);
		} else {
			nodeGraph = nodeGraph + toNode(paths[i].from);
		}
		if (paths[i].to) {
			var tmp = paths[i].from.split(/[\.\:]/);
			nodeGraph = nodeGraph + toNode(tmp[0]+'.'+tmp[1]+'.'+paths[i].to);
			pathGraph = pathGraph + 
				toIdentifier(paths[i].from) + 
				' -> ' +
				toIdentifier(tmp[0]+'.'+tmp[1]+'.'+paths[i].to) +
				(paths[i].hasOwnProperty('via') ? '[label="'+paths[i].via+'"]' : '') +
				";\n";
		}
	}

	var str = 'digraph { graph [ dpi = 50 ]; rankdir="LR"; node[shape=record]; % }';
	str = str.replace('%','subgraph clusterStore { label=Roots; '+rootNodeGraph+' } %');
	str = str.replace('%',nodeGraph+' %');
	str = str.replace('%',pathGraph+' ');

	return str;
}
464113
function LocalStorageKeyEnvironment(key) {
  this.key = key;
  var store = this.onStorage = this.onStorage.bind(this);
  var storage;

  try {
    storage = window.localStorage;
    storage.setItem(key, storage.getItem(key));
  } catch (e) {
    storage = null;
  }

  this.storage = storage || {
    data: {},
    getItem: function(itemKey) {return this.data[itemKey]; },
    setItem: function(itemKey, val) {
      this.data[itemKey] = val;
      clearTimeout(this.storeEvent);
      this.storeEvent = setTimeout(store, 1);
    }
  };

  Environment.call(this);
}
48159
function() {
            var loadedList = localStorage.getItem(localStorageKey);
            if (!loadedList) {
                // If no list is in localstorage, start out with a default one
                this.list = [{
                    key: todoCounter++,
                    created: new Date(),
                    isComplete: false,
                    label: 'Rule the web'
                }];
            } else {
                this.list = _.map(JSON.parse(loadedList), function(item) {
                    // just resetting the key property for each todo item
                    item.key = todoCounter++;
                    return item;
                });
            }
            // Subscribe to RemoteDev
            RemoteDev.subscribe(state => {
                this.updateList(state);
            });
            RemoteDev.init(this.list);
            return this.list;
        }