/*****************************************************
* @desc RefSpy v1.0 (1000)
* @author Field of View, www.fov.ru
*****************************************************/

function RefSpy ()
{
	this.token = 'ref';
	this.divider = '<D>';
	this.localDomains = 'intimshop.ru,new.intimshop.ru,intim-shop.ru,sex-shop.ru,vibrator.ru';
	this.expires = 30;
	
	this.Launch = function ()
	{
		//alert('incoming: '+this.IsIncoming()+'; haverecord:'+this.HaveRecord());
		if (this.IsIncoming() && !this.HaveRecord())
		{
			//alert('set record');
			this.SetRecord();
		}
	};
	
	this.IsIncoming = function ()
	{
		//alert('ref: '+document.referrer);
		if (document.referrer)
		{
			var refSite = this.GetDomain(document.referrer);
			//alert('refsite: '+refSite);
			if (refSite.length)
			{
				//alert('in local?: '+this.localDomains.search(new RegExp('(^|\,)'+this.RxQuote(refSite)+'(\,|$)')));
				return (this.localDomains.search(new RegExp('(^|\,)'+this.RxQuote(refSite)+'(\,|$)')) == -1);
			}
		}
	};
	
	this.GetDomain = function (url)
	{
		var m = url.match(/^\w+\:\/\/.*?(?:www\.)?((?:[a-z0-9\-]+\.)*[a-z]+)(?:\:\d+)?\//i);
		return m ? m[1] : false;
	};
	
	this.HaveRecord = function ()
	{
		return this.GetCookie(this.token) ? true : false;
	};
	
	this.MakeRecord = function ()
	{
		var now = new Date();
		return document.referrer+this.divider+Math.round(now.getTime()/1000);
	};
	
	this.SetRecord = function ()
	{
		this.SetCookie(this.token,this.MakeRecord(),this.expires);
	};

	/*****************************************************
	* @desc Get cookie value
	*/
	this.GetCookie = function (name)
	{
		var m = document.cookie.match(new RegExp(name+'=([^;]+)'));
		return m ? m[1] : null;
	};
	
	/*****************************************************
	* @desc Set cookie value
	*/
	this.SetCookie = function (name, value, expires)
	{
		var str = name+'='+escape(value);
		if (expires > 0)
		{
			var dateNow = new Date();
			var dateExp = new Date(dateNow.getTime()+(expires*86400000));
			str += ';expires='+dateExp.toUTCString();
		}
		//alert('cookie: '+str);
		document.cookie = str;
	};
	
	this.RxQuote = function (str)
	{
		return str.replace(/[^\w]/g,"\\$&");
	};

}
