// Инициализируем таблицу перевода

var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
  trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё

// Сохраняем стандартную функцию escape()
var escapeOrig = window.escape;

// Переопределяем функцию escape()
window.esc = function(str)
{
  var ret = [];
  // Составляем массив кодов символов, попутно переводим кириллицу
  for (var i = 0; i < str.length; i++)
  {
    var n = str.charCodeAt(i);
    if (typeof trans[n] != 'undefined')
      n = trans[n];
    if (n <= 0xFF)
      ret.push(n);
  }
  return escapeOrig(String.fromCharCode.apply(null, ret));
}


var ARWM_ga = {
		code: '',
		
		//купон	значение по умолчанию			
		token: 'ot',
		
		//описание
		text:	'',
		
		//куки								
		cookie:			' ',
		
		//источник перехода
		src:		' ' + document.referrer,
		//document.referrer,			
	
		//настройка языка
		language:			'en',
		
		//язык по умолчанию
		default_language: 	'en',
		
		//последний визит
		lastvisit: 			null,
										
		//
		//метки контекста, русская версия (при вкл. language: 'ru')
		ru: 		   {
						'yd':'ЯД',
						'yn':'ЯН',
						'yo':'ЯО',
						'gn':'ГН',
						'go':'ГО',
						'ti':'ТИ',
						'ot':'ОТ',
						'ro':'РО',
						'bg':'БГ',
						'bn':'БН',
						'oo':'дп',
						'gc':'ГК'
						},
		
		//ошибка
		error:			null,
		
		//органики
		organic:		{
						 'google'	 :'go',
						 'rambler.ru':'ro',
						 'yandex'	 :'yo',
						 'mail.ru'	 :'mo',
						 'begun'	 :'bo',
						 'rambler.ru':'ro'
						},
		
		//реферал без метки
		refferer:		{
						 'sti-club.su':'SC',
						 'ad.adriver.ru':'AD'
						},				
		
		//реферал с меткой
		custom_refferer:{
						 'adv':'AD'
						},
		//реферал с меткой
		custom_refferer:{
						},
		
						//переход с других сайтов
		sideref:		false,


		//данные из аналитики
		utmcsr: 		null,
		utmccn: 		null,
		utmcmd: 		null,
		utmctr: 		null,
		utmcct: 		null,	
		utmgclid: 		null,	
		
		//тестовый режим
		testmode:		false,

		//инициализация
		init: function(){
				this.log('init()');
				this.cookie = ' ' + document.cookie;
				this.lastvisit = this.getCookie('arwm_lastvisit');
				
				// регулярные выражения для переменных utmz аналитики [имя переменной, регулярка]
				var utmreg = [];
				utmreg.push(['utmcsr',/utmcsr=(.*)/i]);
				utmreg.push(['utmccn',/utmccn=(.*)/i]);
				utmreg.push(['utmcmd',/utmcmd=(.*)/i]);
				utmreg.push(['utmcct',/utmcct=(.*)/i]);
				utmreg.push(['utmgclid',/utmgclid=(.*)/i]);

				
				//регулярное выражение для  строки utmz
				var reg			= /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\.(.*)/i;									
				var utmz 		= this.getCookie('__utmz');
				
				//проверка входных данных
				if (utmz == null){
					this.error = '';							
					return null;
				}						
				
				var tokens 		= reg.exec(utmz);						
				tokens 			= tokens[1].split('|');
				c 				= tokens.length;
				k				= utmreg.length;
				
				for (i=0;i<c;i++)
				{
					for(m=0;m<k;m++)
					{
						cc = tokens[i];						
						if (utmreg[m][1].test(cc))
						{
							reg 	= utmreg[m][1];
							data 	= reg.exec(cc);
							this.log("this."+utmreg[m][0]+"= '"+data[1]+"'");
							eval("this."+utmreg[m][0]+"= '"+data[1]+"'");
						}
					}										
				}
				},	
		
		//получение переменной из кук по названию переменой 
		getCookie:	function (name){
		this.log('getCookie()');
			var cookie = this.cookie;
			var search = " " + name + "=";
			var setStr = null;
			var offset = 0;
			var end = 0;
			if (cookie.length > 0) {
				offset = cookie.indexOf(search);
				if (offset != -1) {
					offset += search.length;
					end = cookie.indexOf(";", offset)
					if (end == -1) {
						end = cookie.length;
					}
					setStr = unescape(cookie.substring(offset, end));
				}
			}
			this.log(setStr);
			return(setStr);			
		},
		
		//установка cookie
		setCookie: function (name, value, expiredays, path, domain, secure) {
			   if (expiredays) {
				      var exdate=new Date();
				      exdate.setDate(exdate.getDate()+expiredays);
				      var expires = exdate.toGMTString();
				   }
				   document.cookie = name + "=" + escape(value) +
				   ((expiredays) ? "; expires=" + expires : "") +
				   ((path) ? "; path=" + path : "") +
				   ((domain) ? "; domain=" + domain : "") +
				   ((secure) ? "; secure" : "");
				},

		//копирование свойств объектов
		copy:function(dst, src){
			var tobj = {}
			for(var x in src)
			{
				// копируем в dst свойства src, кроме тех, которые унаследованы от Object
				if((typeof tobj[x] == undefined) || (tobj[x] != src[x]))
				{
					dst[x] = src[x];
				}
			}
			// В IE пользовательский метод toString отсутствует в for..in
			if(document.all && !document.isOpera){
				var p = src.toString;
				if(typeof p == "function" && p != dst.toString && p != tobj.toString &&
				 p != "\nfunction toString() {\n    [native code]\n}\n"){
					dst.toString = src.toString;
				}
			}				
		},
		
		//настройки купона
		set: function(obj){
			this.log('set()');
							
			for (var key in obj)
			{			
				type = typeof this[key];			
				if(type == 'string')
					this[key] = obj[key];							
				else if (type == 'object')
					this.copy(this[key], obj[key]);												
			}
		},				
		
		
		//вывод значения купона с описанием
		go: function(){		
			this.log('go()');	
			
			if (this.utmcmd == 'cpc' || this.utmcmd == 'not%20set' || this.utmcmd == '(not set)' || this.utmcmd == 'context' )
			{	
			
				if (this.utmccn == '(not set)' && this.utmcmd == '(not set)' /*&& this.utmgclid == null*/)
					{
						/*	* * * с левого сайта с меткой	* * * */
						this.log('custom refferer');
						
							if (this.utmcsr != null)
							{
								cref = this.custom_refferer[this.utmcsr.toLowerCase()];
								if (cref != undefined)
								{
									this.token = cref;
								}
								else
								{
									this.error = "метка не определена";
									this.token = '#4';										
								}																		
							}
						if (this.utmgclid  == null){
								this.sideref = true;
								return;								
						}				
					}
				
				/* * * * контекст * * * */
				this.log('контекст');							
					
					var str = this.src;
					this.log(document.referrer);
					if (this.utmcsr == 'YD' || this.utmcsr == 'yd' || this.utmcsr == 'yandex' || this.utmcsr == 'YANDEX' || this.utmcsr == 'Yandex') 
					{		
						if (str.indexOf('yandex.ru')+1) 
							this.token = 'yd';
						else 
							this.token = 'yn';
					}							
					
					
					if (this.utmgclid != null)
					{
						this.log('gclid != null');
						
						if(str.indexOf('google')+1 || str.indexOf('mail.ru')+1)
							this.token = 'gc';
						else	
							this.token = 'gn';						
					}else{
						this.log('gclid = null');
						if (this.utmcsr == 'GA' || this.utmcsr == 'google' || this.utmcsr == 'ga' || this.utmcsr == 'GOOGLE' || this.utmcsr == 'Google'){
							if(str.indexOf('google')+1)
								this.token = 'gc';
							else	
								this.token = 'gn';
						}						
					}
					
					
					if (this.utmcsr == 'begun' || this.utmcsr == 'BEGUN' || this.utmcsr == 'BG' || this.utmcsr == 'bg') 
					{		
						if ((str.indexOf('rambler.ru')+1) || (str.indexOf('begun.ru')+1)) 
							this.token = 'bg';
						else 
							this.token = 'bn';
					}					
										
				return;											
			}
			
			
			if (this.utmccn == '(referral)' || this.utmcmd == 'referral')
				{
					/* * * *  c левого сайта без метки * * * */
					this.log('referral=' + this.utmcsr);
					this.sideref = true;
					
					if (this.utmcsr != null)
						{
							ref = this.refferer[this.utmcsr.toLowerCase()];
							if (ref != undefined)
							{
								this.token = ref;
							}
							else
							{
								this.error = "метка не определена";
								this.token = 'ot';										
							}																		
						}
						else
						{
							this.error = "переменная utmcsr не определена в cookie";
							this.token = '#3';
						}
					return;						
					
				}			
			
			/* * * *  поисковые системы * * * */
			
			if (this.utmcmd == 'organic')
			{
				this.log('organic');
				if (this.utmcsr != '') {
					org = this.organic[this.utmcsr.toLowerCase()];
					if (org == undefined) {
						this.token = 'oo';
					}
					else {
						this.token = org;
					}
				}
				else
				{
					this.error = 'переменнная utmcsr не определена в cookie';
					this.token = '#2';
				}							
				return;
			}							
			
			/* * * *  прямой ввод * * * */					
			
			if (this.utmcmd == '(none)')
			{
				this.log('type in');
				this.token = 'ti';
				return;						
			}
			
			/* * * *  не определенный источник   * * * */					
			this.log('ot');				
		},
		
		//вызов купона		
		coupon:function(){
		this.log('coupon');
			this.go();
			
			this.code = this.token;

			//перевод на соответствующий текущим настройкам язык
			if (this.language != this.default_language)
			{
				translate 	=  	this[this.language];
				str			= 	this.token;
				token 		=  	translate[str.toLowerCase()];
				
				
				if (token == undefined)
					this.error = 'перевод отсутствует';
				else
					this.token = token;						 
				
			}
			
			//проверка системной cookie купона
			if (this.lastvisit == null){
				//первый заход
				this.log('первый заход');
				this.setCookie("arwm_lastvisit", this.token,"150", "/");
			}else{
				//повторный заход или переход с других сайтов 
				this.log('повторный заход');
				this.log(this.sideref);
				if (this.src.length == '1' || this.sideref == true)
					//ручной ввод
					this.token = this.getCookie("arwm_lastvisit");					
				else{
					//по ссылке
					
					this.setCookie("arwm_lastvisit", this.token,"150","/");
					
				}
				
			}
			return this.text+this.token;//.toUpperCase();					
		},
		
		//консоль firebug
		log: function(str){
			if (this.testmode)
				try{console.log(str)}catch(e){}					
		}			
}


