﻿// Library of cookie handlers.
// Let's you read, write and delete cookies.
// $Header: /WebSites/library/javascript/general/cookies.js 1     2/29/08 11:32a Bpena $

    //Function getCookie
    //Retrieves the value of a cookie from the user's local machine
    //-----------------------------------------
    //param name: cookie name
	function getCookie(name) {
		var cookiename = name + "=";
		var dc = document.cookie;
		var begin, end;
		if (dc.length > 0){
			begin = dc.indexOf(cookiename);
			if (begin != -1) {
				begin += cookiename.length;
				end = dc.indexOf(";" , begin);
				if (end == -1) {
					end = dc.length;
				}
				var needle = /[<>\'\"\{\}\(\)]/g;   
                var haystack = unescape(dc.substring(begin, end));
                if ( haystack.match(needle) ) { 
                    return "";
                } 
                else {
                    return haystack;
                }
			}
		}
		return null;
	}	
	
	
	//Function setCookie
	//Create a cookie on the user's local machine
	//-----------------------------------------
	//Param name: cookie name
	//Param value: cookie value
	//Param expires: [optional] number of days before cookie should expire
	//Param path: [optional]  the top-level directory from which a cookie can be read
	//Param domain: [optional] the domain from which a cookie can be read
	//Param secure: [optional] if set to any value, cookie will be readable only from secure environments
	function setCookie(name, value, expires, path, domain, secure) {
        var today = new Date();
        today.setTime( today.getTime() );

        if ( expires ) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        
        var expirationDate = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expirationDate.toGMTString() : "" ) + 
        ( ( path ) ? ";path=" + path : "" ) + 
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
    }
    
    
    //Function deleteCookie
    //Expires, and therefore, deletes a cookie from the user's local machine
    //--------------------------------------------
    //Param name: cookie name
    //Param path: the path set in the cookie
    //Param domain: the domain set in the cookie
    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";
        }
    }