/**
 * Author: Dmitry Khavilo  
 * Version: 1.2.0
 * Originally created for Repka.tv and me2.ua
 * Copyright 2008-2009 Dmitry Khavilo
 **/

var Cache = function()
{
	this.length = 0;
	this.data = {};
	this.permanent = {};
	this.maxRecords = 50;
	
	this.set = function (name, value, permanent)
	{
		if ( !this.isset(name) && !permanent )
			this.length++;
		else
			delete(this.data[name]); /* Touching  cache */
		
	  if (permanent)
	    this.permanent[name] = true;
		this.data[name] = value;
		this.cleanup();
	};
	
	this.get = function (name)
	{
		if ( !this.isset(name) )
			return null;
			
		/* "Touching cache" */	
		var tmp = this.data[name];
		delete this.data[name];
		this.data[name] = tmp;
		delete tmp;
		
		return this.data[name];
	};
	
	this.cleanup = function()
	{
		if ( this.length > this.maxRecords )
		{
			for ( var name in this.data )
			  if ( !this.permanent[name] )
  			{
  				delete this.data[name];
  				delete name;
  				this.length--;
  				return;
  			}
		}
	};
	
	this.isset = function (name)
	{
		return name in this.data;
	};
	
	this._merge = function(content, newContent)
	{
	  for ( var key in newContent )
      if ( (typeof content[key] == 'object') && (typeof newContent[key] == 'object')  )
        content[key] = this._merge(content[key], newContent[key]);
      else
        content[key] = newContent[key];
	  
	  return content;
	};
	
	this.merge = function (name, content, permanent)
	{
	  var newContent = this.isset(name) ? this.get(name) : {};
	  
	  this._merge(newContent, content);
	  
	  this.set(name, newContent, permanent);
	};
	
};

$CACHE = new Cache();