//(c) Polezhaev, 2006
//cookie format: name=value; [expires=date; [path=path; [domain=domain; [secure;]]]]
//important: if expiration date is not set, cookies are valid through the current browser session only.
//expiration date must be defined as GMT datetime (i.e converted using toGMTString())


//class Pair definition
function Pair(name, value)
{
	this.Name = name;
	this.Value = value;	
}

//class PairCollection definition
function PairCollection()
{
	this.Array = new Array();
	this.Add = _add;
	this.Find = _find;
	this.Count = _count;
}

//pair count
function _count()
{
	return this.Array.length;	
}

//find pair
function _find(name)
{
	var pair;
	for (var i=0; i<this.Array.length; i++)
	{
		pair = this.Array[i];		
		if (pair.Name == name)
			return pair;	
	}
	return null;
}

//add pair
function _add(name, value)
{
	this.Array[this.Array.length] = new Pair(name, value);
}

//class Cookie definition
function Cookie(path, domain) 
{	
	this.Collection = _update();
	this.Expires = null;
	this.Read = _read;
	this.Write = _write;
	this.ToString = _toString;
	this.Update = _update;	
	this.Path = path;
	this.Domain = domain;	
}

//returns cookies string
function _toString() 
{
	return document.cookie;
}

//initialize/update
function _update() 
{
	var result = new PairCollection();			
	var pairs = document.cookie.split("; ");	
	var pair;
	for (var i=0; i<pairs.length; i++) 
	{
		pair = pairs[i].split("=");		
		result.Add(unescape(pair[0]), unescape(pair[1]));								
	}
	return result;
}

//read cookie
function _read(name) 
{
	var pair = this.Collection.Find(name);
	if (pair != null)
		return pair.Value;
	return null;
}

//write cookie
function _write(name, value) 
{	
	var cookies = ""
	if (name!=null && value!=null)
	{	
		cookies += name + "=" + value + "; ";
		if (this.Expires!=null) 
			cookies += "expires=" + this.Expires.toGMTString() + "; ";
		if (this.Path!=null) 
			cookies += "path=" + this.Path + "; ";
		if (this.Domain!=null) 
			cookies += "domain=" + this.Domain + "; ";
		document.cookie = cookies;
		this.Collection = this.Update();
	}
	return document.cookie;		
}