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