1 /**
  2  * Store
  3  *
  4  * Wrapper for local / sessionstorage
  5  */
  6 (function (undefined){
  7 
  8 	"use strict";
  9 
 10 	//No support for localstorage? Bail out early
 11 	if(localStorage === undefined || JSON === undefined)
 12 	{
 13 		return null;
 14 	}
 15 
 16 	//Shortcuts for wrapper
 17 	var l = localStorage,
 18 		s = sessionStorage;
 19 
 20 	/**
 21 	 * Wrapper for localstorage / sessionstorage data serialization.
 22 	 * Each method has a boolean parameter, that when set as true switches the method
 23 	 * to use sessionStorage rather than the default localStorage.
 24 	 *
 25 	 * @name store
 26 	 * @namespace
 27 	 * @memberOf $_
 28 	 */
 29 	var store = {
 30 		/**
 31 		 * Retrieves and deserializes a value from localstorage,
 32 		 * based on the specified key
 33 		 *
 34 		 * @param string key
 35 		 * @param bool session
 36 		 * @name get
 37 		 * @memberOf $_.store
 38 		 * @function
 39 		 * @return object
 40 		 * @type object
 41 		 */
 42 		get: function (key, sess)
 43 		{
 44 			var val = (sess) ? s.getItem(key) : l.getItem(key);
 45 
 46 			return JSON.parse(val);
 47 		},
 48 		/**
 49 		 * Puts a value into localstorage at the specified key,
 50 		 * and JSON-encodes the value if not a string
 51 		 *
 52 		 * @param string key
 53 		 * @param mixed value
 54 		 * @param bool session
 55 		 * @name set
 56 		 * @memberOf $_.store
 57 		 * @function
 58 		 */
 59 		set: function (key, value, sess)
 60 		{
 61 			// Localstorage generally only accepts strings
 62 			value = JSON.stringify(value);
 63 
 64 			(sess) ? s.setItem(key, value) : l.setItem(key, value);
 65 		},
 66 		/**
 67 		 * Removes the specified item from storage
 68 		 *
 69 		 * @param string key
 70 		 * @param bool session
 71 		 * @name remove
 72 		 * @memberOf $_.store
 73 		 * @function
 74 		 */
 75 		remove: function (key, sess)
 76 		{
 77 			(sess) ? s.removeItem(key) : l.removeItem(key);
 78 		},
 79 		/**
 80 		 * Returns an object of all the raw values in storage
 81 		 *
 82 		 * @param bool session
 83 		 * @name getAll
 84 		 * @memberOf $_.store
 85 		 * @function
 86 		 * @return object
 87 		 * @type object
 88 		 */
 89 		getAll: function (sess)
 90 		{
 91 			var i,
 92 				len,
 93 				data = {},
 94 				k,
 95 				o;
 96 
 97 			//Reference to session/localstorage
 98 			o = (sess) ? l : s;
 99 
100 			len = o.length;
101 
102 			for (i = 0; i < len; i++)
103 			{
104 				k = o.key(i);
105 				data[k] = o.getItem(k);
106 			}
107 
108 			return data;
109 		},
110 		/**
111 		 * Removes all values from the same domain storage
112 		 *
113 		 * @param bool session
114 		 * @name clear
115 		 * @memberOf $_.store
116 		 * @function
117 		 */
118 		clear: function(sess)
119 		{
120 			(sess) ? s.clear() : l.clear();
121 		}
122 	};
123 
124 	$_.ext('store', store);
125 }());