﻿// Functions for working with cookies.
// Author: Alexey Alexandrov 
// Modified for work with multivalued cookies by: Maxim Mayorov

var caution = false;

// Set the value of the cookie
// Parameters:
//   name - the cookie name
//   value - the cookie value
//   [expires] - date then the cookie is expires (default - expires at the end of the session)
//   [path] - cookie path 
//   [domain] - cookie domain
//   [secure] - boolean, indicates what the cookie must be encrypted
function setCookie(name, value, expires, path, domain, secure) {
    var xvalue;
    if (typeof (value) === "string") {
        xvalue = escape(value);
    }
    else if (value !== null && typeof (value) === "object") {
        xvalue = "";
        for (var key in value) {
            xvalue += "&" + escape(key) + "=" + escape(value[key]);
        }
        if (xvalue.length > 0)
            xvalue = xvalue.substring(1);
    }
    else throw "setCookie: Value must be a string or an object";
    
        var curCookie = name + "=" + xvalue +
                ((expires) ? "; expires=" + expires.toGMTString() : "") +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "")
        if (!caution || (name + "=" + xvalue).length <= 4000)
                document.cookie = curCookie
        else
                if (confirm("Cookie exceeds 4KB limit and will be cutted!"))
                        document.cookie = curCookie
}

// Get the value of the cookie
// Parameters:
//   name - the cookie name
function getCookie(name) {
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        if (cookieStartIndex == -1)
                return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

// Delete cookie from the document cookies
// Parameters:
//   name - the cookie name
//   [path] - cookie path 
//   [domain] - cookie domain
function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" + 
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-1970 00:00:01 GMT"
        }
}        
