﻿function eraseCookie(name) {
    try {
        document.cookie = name + '=; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/'
    }
    catch (e) { createCookie(name, "", -1); }
}
function createCookie(name, value) {
    ToDay = new Date();
    ToDay.setTime(Expires = (24 * 60 * 60 * 1000 * 365) + ToDay.getTime());
    Expires = (ToDay.toGMTString());
    document.cookie = name + "=" + value + "; path=/;EXPIRES=" + Expires;
}
function eraseCookiePath(name, path) {
    createCookiePath(name, "", -1, "");
}
function createCookiePath(name, value, date, path) {
    document.cookie = name + "=" + value + "; path=/" + path + ";EXPIRES=" + date;
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function check_cookie() {
    if (document.cookie == '')
        document.getElementById('content').innerHTML = 'wlacz obsluge cookie';
}

function SaveDataToCookie(cookieName, selector)
{
    var cookieKey = "";
    $(selector).each( function(index) {
        if (this.type == "text")
        {
            cookieKey += this.value;
        }
        else if (this.type == "checkbox" || this.type == "radiobutton")
        {
            cookieKey += this.checked;
        }
        else if (this.type == "select-one")
        {
            cookieKey += this.selectedIndex;
        }
        
        cookieKey += "||";
        
        });
        
    eraseCookie(cookieName);
    createCookie(cookieName, cookieKey);
}

function SetControlsFromCookie(cookieName, selector)
{
    var cookieData = readCookie(cookieName);
    if (cookieData != null)
    {
        var cookieArray = cookieData.split("||");
        
        $(selector).each( function(index) {
            if (this.type == "text")
            {
                this.value = cookieArray[index];
            }
            else if (this.type == "checkbox" || this.type == "radiobutton")
            {
                this.checked = cookieArray[index] == "true" ? true : false;
            }
            else if (this.type == "select-one")
            {
                if(this.length > parseFloat(cookieArray[index]))
                {
                    this.selectedIndex = parseFloat(cookieArray[index]);
                }
            }
        });

    }
}