/webroot/js/cookie.js
[return to app]1
/**
2 * Simplifies working with cookies
3 * @author Eric David Benari
4 * @link http://www.Vork.us
5 */
6 var cookie = function() {}
7
8 /**
9 * Sets a cookie
10 *
11 * @param string name
12 * @param string value
13 * @param mixed expires Optional Can be an int (number of days) or smart string eg.: 3 hours, 6 weeks, 1 year,
etc.
14 * @param obj args Optional, a JavaScript object with keys for any or all of: domain, host or (Boolean) secure
15 */
16 cookie.write = function(name, value, expires, args) {
17 var cookie = name + '=' + escape(value);
18 if (typeof expires != 'undefined') {
19 var increment = (24 * 60 * 60 * 1000); //days
20 if (typeof expires == 'string') {
21 if (expires.indexOf('minute') != -1) {
22 increment = 60000;
23 } else if (expires.indexOf('hour') != -1) {
24 increment /= 24;
25 } else if (expires.indexOf('week') != -1) {
26 increment *= 7;
27 } else if (expires.indexOf('month') != -1) {
28 increment *= 30;
29 } else if (expires.indexOf('year') != -1) {
30 increment *= 365;
31 }
32 expires = parseInt(expires);
33 }
34 var date = new Date();
35 date.setTime(date.getTime() + (expires * increment));
36 cookie += '; expires=' + date.toGMTString();
37 }
38 if (typeof args != 'undefined') {
39 var argTypes = ['path', 'domain']
40 for (argType in argTypes) {
41 if (typeof args[argTypes[argType]] != 'undefined') {
42 cookie += '; ' + argTypes[argType] + '=' + args[argTypes[argType]];
43 }
44 }
45 if (typeof args['secure'] != 'undefined') {
46 cookie += '; secure';
47 }
48 }
49 document.cookie = cookie;
50 }
51
52 /**
53 * Reads a cookie
54 *
55 * @param string name
56 * @return mixed Returns the cookie string; if the cookie is not set it returns null
57 */
58 cookie.read = function(name) {
59 if (document.cookie.length > 0) {
60 var start = document.cookie.indexOf(name + '=');
61 if (start != -1) {
62 start += name.length + 1;
63 var end = document.cookie.indexOf(';', start);
64 if (end == -1) {
65 end = document.cookie.length;
66 }
67 return unescape(document.cookie.substring(start, end));
68 }
69 }
70 return null;
71 }
72
73 /**
74 * Removes a cookie
75 *
76 * @param string name
77 */
78 cookie.unset = function(name) {
79 cookie.write(name, null, -1);
80 }