// 

function $ (data)
{
	if (typeof(data) == 'object')
	{
		obj = data;
	}
	else if (typeof(data) == 'string')
	{
		if (m = data.match(/^(\+)(\w+)$/))
		{
			obj = document.createElement(m[2]);
		}
		else
		{
			obj = document.getElementById(data);
		}
	}
	if (navigator.userAgent.search(/MSIE/) != -1)
	{
		for (prop in Element.prototype)
		{
			if (obj[prop] == undefined)
			{
				obj[prop] = Element.prototype[prop];
			}
		}
	}
	return obj;
}

function str (path, value)
{
	this.Get = function (path)
	{
		var nodes = path.split('.');
		var cur = window.lng;
		//alert(window.lng.cart);
		for (var i=0; i<nodes.length; i++)
		{//alert('window.lng.'+nodes[i]+'='+cur[nodes[i]]);
			cur = cur[nodes[i]];
			if (typeof(cur) != 'object')
			{
				break;
			}
		}
		return cur;
	}
	
	this.Set = function (path, value)
	{
		var nodes = path.split('.');
		if (window.lng == undefined) window.lng = {};
		var cur_path = [];
		for (var i=0; i<nodes.length; i++)
		{
			cur_path.push(nodes[i]);
			full_path = 'window.lng.'+cur_path.join('.');
			eval('if ('+full_path+' == undefined) '+full_path+' = {};');
		}
		eval(full_path+' = value;');
	}
	
	return (value != undefined) ? this.Set(path,value) : this.Get(path);
}

if (navigator.userAgent.search(/MSIE/) != -1)
{
	var Element = {};
	Element.prototype = {};
}

Element.prototype.addClass = function (name)
{
	this.removeClass(name); // prevent dupes
	this.className += ' '+name;
}

Element.prototype.getCSS = function (property)
{
	if (this.currentStyle)
	{
		return this.currentStyle[property];
	}
	else if (window.getComputedStyle)
	{
		return document.defaultView.getComputedStyle(this,null).getPropertyValue(property);
	}
};

Element.prototype.getOffsetLeft = function ()
{
	return (this.offsetParent ? $(this.offsetParent).getOffsetLeft() : 0)+this.offsetLeft;
}

Element.prototype.getOffsetTop = function ()
{
	return (this.offsetParent ? $(this.offsetParent).getOffsetTop() : 0)+this.offsetTop;
}

Element.prototype.getPoint = function (i)
{
	x = this.getOffsetLeft();
	y = this.getOffsetTop();
	w = this.offsetWidth;
	h = this.offsetHeight;
	switch (i)
	{
		case 1: return [x,y];
		case 2: return [x+w,y];
		case 3: return [x+w,y+h];
		case 4: return [x,y+h];
	}
}

Element.prototype.hide = function ()
{
	this.style.display = 'none';
}

Element.prototype.on = function (event, handler)
{
	if (this.addEventListener)
	{
		this.addEventListener(event,handler,false);
	}
	else
	{
		this['on'+event] = handler;
	}
}

Element.prototype.parentTag = function (name)
{
	name = name.toUpperCase();
	var cur = this;
	while (cur.parentNode)
	{
		if (cur.tagName == name)
		{
			return cur;
		}
		cur = cur.parentNode;
	}
}

Element.prototype.load = function (uri, callback)
{
	this.ds_callback = function (data) { this.innerHTML = data; }
	this.ds = new DataSource('raw',uri,new Callback(this,'ds_callback'));
	this.ds.Get();
}

Element.prototype.removeClass = function (name)
{
	this.className = this.className.replace(new RegExp('(^|\s)'+name+'(\s|$)','i'),'');
}

Element.prototype.show = function (point)
{
	this.style.display = 'block';
	if (point != undefined)
	{
		this.style.left = point[0]+'px';
		this.style.top = point[1]+'px';
	}
}

Math.rand = function (min, max)
{
	return this.round(min+(max-min)*this.random());
};

String.prototype.rxval = function (rx, i)
{
	return (m = this.match(rx)) ? m[i] : '';
};

String.prototype.template = function (values)
{
	var str = this;
	for (key in values)
	{
		str = str.replace(new RegExp('\{'+key+'\}','gi'),values[key]);
	}
	return str;
};

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,'');
}

// ============================================================================

document.cookies = new Object();
document.cookies.get = function (name)
{
	var arr = document.cookie.split(';');
	var item;
	for (var i=0; i<arr.length; i++)
	{
		item = arr[i].split('=',2);
		if (item[0].trim() == name)
		{
			return item[1];
		}
	}
	return '';
};

document.cookies.set = function (name, value, expires)
{
	var str = name+'='+value;
	if (expires)
	{
		var date = new Date();
		date.setTime(date.getTime()+(expires*1000));
		str += '; expires='+date.toGMTString();
	}
	str += '; path=/';
	document.cookie = str;
};

// ============================================================================

function Callback (object, method)
{
	this.__construct = function (object, method)
	{
		this.object = object;
		this.method = eval('object.'+method);
	}
	
	this.call = function (args)
	{
		args = (args != undefined) ? args : [];
		this.method.apply(this.object,args);
	}
	
	this.__construct(object, method);
}

// ============================================================================

function DataSource (type, uri, callback)
{
	this.__construct = function (type, uri, callback)
	{
		this.type = type;
		this.baseurl = ((m = document.location.toString().match(/^\w+\:\/\/[^\/]+/)) ? m[0] : document.location.toString());
		this.uri = uri;
		this.callback = callback;
		this.http = new XMLHttpRequest();
		this.http.owner = this;
	}
	
	this.Get = function ()
	{
		this.http.open('GET',this.baseurl+this.uri,true);
		this.http.onreadystatechange = function () { if ((this.readyState == 4) && (this.status == 200)) this.owner.OnData(this.responseText); }
		this.http.send(null);
	}
	
	this.OnData = function (raw)
	{
		var data;
		//$('debug').value = raw;
		if (this.type == 'json')
		{
			eval('data = '+raw+';');
		}
		else
		{
			data = raw;
		}
		this.callback.call([data]);
	}
	
	this.Post = function (data)
	{
		var buf = '';
		for (var key in data)
		{
			buf += '&'+key+'='+encodeURIComponent(data[key]);
		}
		data = buf.substr(1);
		this.http.open('POST',this.baseurl+uri,true);
		this.http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=Windows-1251'); // ; charset=Windows-1251
		this.http.setRequestHeader('Content-Length',data.length);
		this.http.setRequestHeader('Connection','close');
		this.http.onreadystatechange = function () { if ((this.readyState == 4) && (this.status == 200)) this.owner.OnData(this.responseText); }
		this.http.send(data);
	}
	
	this.__construct(type, uri, callback);
}

// ============================================================================

/*function DateInput (name, value, args)
{
	this.__construct = function (name, value, args)
	{
		this.name = name;
		this.args = args;
		this.box = $(name+'_box');
		
		var onchange = function () { this.control.Update(); }
		
		// input
		this.input = document.createElement('input');
		this.input.setAttribute('type','hidden');
		this.input.setAttribute('name',name);
		this.input.setAttribute('value',value);
		this.box.appendChild(this.input);
		
		// day
		this.day = document.createElement('select');
		if (this.args.optional)
		{
			this.day.appendChild(this.createOptionElement(0,''));
		}
		for (var i=1; i<=31; i++)
		{
			this.day.appendChild(this.createOptionElement(i,i));
		}
		this.box.appendChild(this.day);
		this.day.control = this;
		this.day.onchange = onchange;
		
		// month
		var strmonths = ['','января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'];
		this.month = document.createElement('select');
		if (this.args.optional)
		{
			this.month.appendChild(this.createOptionElement(0,''));
		}
		for (var i=1; i<=12; i++)
		{
			this.month.appendChild(this.createOptionElement(i,strmonths[i]));
		}
		this.box.appendChild(this.month);
		this.month.control = this;
		this.month.onchange = onchange;
		
		// year
		this.year = document.createElement('select');
		if (this.args.optional)
		{
			this.year.appendChild(this.createOptionElement(0,''));
		}
		for (var i=this.args.min_year; i<=this.args.max_year; i++)
		{
			this.year.appendChild(this.createOptionElement(i,i));
		}
		this.box.appendChild(this.year);
		this.year.control = this;
		this.year.onchange = onchange;
		
		// time
		if (this.args.time)
		{
			this.box.appendChild(document.createTextNode(' Время: '));
			this.time = document.createElement('a');
			this.time.className = 'primary';
			this.time.setAttribute('href','javascript:void(0);');
			this.box.appendChild(this.time);
			this.time.control = this;
			this.time.onclick = function () { if (m = window.prompt('Часы:Минуты').match(/(\d{1,2})\:(\d{1,2})/)) { this.control.time.innerHTML = m[1]+':'+m[2]; this.control.Update(); } };
			this.time.innerHTML = this.args.time;
		}
		
		this.Set(value);
	}
	
	this.createOptionElement = function (value, title)
	{
		var elem = document.createElement('option');
		elem.setAttribute('value',value);
		elem.appendChild(document.createTextNode(title));
		return elem;
	}
	
	this.Set = function (unixtime)
	{
		if (unixtime)
		{
			date = new Date(unixtime*1000);
			
			this.day.value = date.getDate();
			this.month.value = date.getMonth()+1;
			this.year.value = date.getFullYear();
			if (this.args.time)
			{
				this.time.innerHTML = date.getHours()+':'+('0'+date.getMinutes()).replace(/.*(\d{2})$/,'$1');
			}
			
			this.input.value = Math.round(date.getTime()/1000);
		}
		else
		{
			//this.day.value = 0;
			//this.month.value = 0;
			//this.year.value = 0;
			
			this.input.value = 0;
		}
	}
	
	this.Update = function ()
	{
		if ((this.day.value != 0) && (this.month.value != 0) && (this.year.value != 0))
		{
			date = new Date();
			date.setDate(this.day.value);
			date.setMonth(this.month.value-1);
			date.setFullYear(this.year.value);
			if (this.args.time && (m = this.time.innerHTML.match(/(\d+)\:(\d+)/)))
			{
				date.setHours(m[1]);
				date.setMinutes(m[2]);
			}
			this.Set(Math.round(date.getTime()/1000));
		}
		else
		{
			this.Set(0);
		}
	}
		
	this.__construct(name,value,args);
}*/

// Дата для форм

function DateInput (name, value, args)
{
	this.__construct = function (name, value, args)
	{
		this.name = name;
		this.args = args;
		this.box = $(name+'_box');
		
		var onchange = function () { this.control.Update(); }
		
		// input
		this.input = document.createElement('input');
		this.input.setAttribute('type','hidden');
		this.input.setAttribute('name',name);
		this.input.setAttribute('value',value);
		this.box.appendChild(this.input);
		
		// day
		this.day = document.createElement('select');
		this.day.appendChild(this.createOptionElement(0,''));
		for (var i=1; i<=31; i++)
		{
			this.day.appendChild(this.createOptionElement(i,i));
		}
		this.box.appendChild(this.day);
		this.day.control = this;
		this.day.onchange = onchange;
		
		// month
		var strmonths = ['','января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'];
		this.month = document.createElement('select');
		this.month.appendChild(this.createOptionElement(0,''));
		for (var i=1; i<=12; i++)
		{
			this.month.appendChild(this.createOptionElement(i,strmonths[i]));
		}
		this.box.appendChild(this.month);
		this.month.control = this;
		this.month.onchange = onchange;
		
		// year
		this.year = document.createElement('select');
		this.year.appendChild(this.createOptionElement(0,''));
		for (var i=this.args.max_year; i>=this.args.min_year; i--)
		{
			this.year.appendChild(this.createOptionElement(i,i));
		}
		this.box.appendChild(this.year);
		this.year.control = this;
		this.year.onchange = onchange;
		
		// time
		if (this.args.time)
		{
			this.box.appendChild(document.createTextNode(' Время: '));
			/*this.time = document.createElement('a');
			this.time.className = 'primary';
			this.time.setAttribute('href','javascript:void(0);');
			this.box.appendChild(this.time);
			this.time.control = this;
			this.time.onclick = function () { if (m = window.prompt('Часы:Минуты').match(/(\d{1,2})\:(\d{1,2})/)) { this.control.time.innerHTML = m[1]+':'+m[2]; this.control.Update(); } };
			this.time.innerHTML = this.args.time;*/
			
			// hours
			this.hours = document.createElement('select');
			for (var i=0; i<=23; i++)
			{
				this.hours.appendChild(this.createOptionElement(i,i.toString().replace(/^(\d)$/,'0$1')));
			}
			this.box.appendChild(this.hours);
			this.hours.control = this;
			this.hours.onchange = onchange;
			
			// div
			this.box.appendChild(document.createTextNode(':'));
			
			// minutes
			this.minutes = document.createElement('select');
			for (var i=0; i<=45; i+=15)
			{
				this.minutes.appendChild(this.createOptionElement(i,i.toString().replace(/^(\d)$/,'0$1')));
			}
			this.box.appendChild(this.minutes);
			this.minutes.control = this;
			this.minutes.onchange = onchange;
			
		}
		
		this.Set(value);
	}
	
	this.createOptionElement = function (value, title)
	{
		var elem = document.createElement('option');
		elem.setAttribute('value',value);
		elem.appendChild(document.createTextNode(title));
		return elem;
	}
	
	this.Set = function (unixtime)
	{
		if (unixtime)
		{
			date = new Date(unixtime*1000);
			
			this.day.value = date.getDate();
			this.month.value = date.getMonth()+1;
			this.year.value = date.getFullYear();
			if (this.args.time)
			{
				this.hours.value = date.getHours();
				this.minutes.value = date.getMinutes();
				//this.time.innerHTML = date.getHours()+':'+('0'+date.getMinutes()).replace(/.*(\d{2})$/,'$1');
			}
			
			this.input.value = Math.round(date.getTime()/1000);
		}
		else
		{
			//this.day.value = 0;
			//this.month.value = 0;
			//this.year.value = 0;
			
			this.input.value = 0;
		}
	}
	
	this.Update = function ()
	{
		if ((this.day.value != 0) && (this.month.value != 0) && (this.year.value != 0))
		{
			date = new Date();
			date.setDate(this.day.value);
			date.setMonth(this.month.value-1);
			date.setFullYear(this.year.value);
			if (this.args.time)
			{//alert(this.hours.value+':'+this.minutes.value);
				date.setHours(this.hours.value);
				date.setMinutes(this.minutes.value);
			}
			this.Set(Math.round(date.getTime()/1000));
		}
		else
		{
			this.Set(0);
		}
	}
		
	this.__construct(name,value,args);
}

// ============================================================================
// День для форм (value: "0324")

function DayInput (name, value)
{
	this.__construct = function (name, value)
	{
		this.box = $(name+'_box');
		this.date = {month: parseInt(value.toString().substr(0,2)), day: parseInt(value.toString().toString().substr(2,2))};
		
		// input
		this.input = document.createElement('input');
		this.input.setAttribute('type','hidden');
		this.input.setAttribute('name',name);
		this.input.setAttribute('value',value);
		this.box.appendChild(this.input);
		
		// day
		this.day = document.createElement('select');
		for (var i=1; i<=31; i++)
		{
			this.day.appendChild(this.createOptionElement(i,i));
		}
		this.box.appendChild(this.day);
		this.day.control = this;
		this.day.onchange = function () { this.control.date.day = this.value; this.control.Update(); }
		
		// month
		var strmonths = ['','января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'];
		this.month = document.createElement('select');
		for (var i=1; i<=12; i++)
		{
			this.month.appendChild(this.createOptionElement(i,strmonths[i]));
		}
		this.box.appendChild(this.month);
		this.month.control = this;
		this.month.onchange = function () { this.control.date.month = this.value; this.control.Update(); }
		
		this.Update();
	}
	
	this.createOptionElement = function (value, title)
	{
		var elem = document.createElement('option');
		elem.setAttribute('value',value);
		elem.appendChild(document.createTextNode(title));
		return elem;
	}
	
	this.Update = function ()
	{
		this.day.value = this.date.day;
		this.month.value = this.date.month;
		this.input.value = (this.date.month<10?'0':'')+this.date.month+(this.date.day<10?'0':'')+this.date.day;
	}
		
	this.__construct(name,value);
}

// ============================================================================
// Flags Manager

function FlagsInput (id, flags)
{
	this.__construct = function (id, flags)
	{
		this.object = $(id);
		this.flags = flags;
		this.items = {};
		
		//var onchange = function () { this.control.Update(); }
		
		// container
		this.Deploy();
		this.Parse();
	}
	
	this.Deploy = function ()
	{
		this.container = document.createElement('div');
		this.container.className = 'flags_input';
		this.object.parentNode.insertBefore(this.container,this.object);
		this.object.style.display = 'none';
		
		for (var key in this.flags)
		{
			this.AddFlag(key,this.flags[key]);
		}
	}
	
	this.AddFlag = function (key, title)
	{
		var id = this.object.name+'_'+key;
		
		// box
		var item = document.createElement('input');
		item.setAttribute('type','checkbox');
		item.setAttribute('id',id);
		item.control = this;
		this.container.appendChild(item);
		item.on('change',function () { this.cheked = true; this.control.Update(); });
		
		// label
		var label = document.createElement('label');
		label.setAttribute('for',id);
		label.appendChild(document.createTextNode(title));
		this.container.appendChild(label);
		
		this.items[key] = { item: item, label: label };
		
		//this.Update();
	}
	
	this.Parse = function ()
	{
		var selected = this.object.value.split(',');
		for (var i=0; i<selected.length; i++)
		{
			if (this.items[selected[i]])
			{
				this.items[selected[i]].item.checked = true;
			}
		}
	}
	
	this.Update = function ()
	{
		var selected = [];
		for (var key in this.flags)
		{
			if (this.items[key] && this.items[key].item.checked)
			{
				selected.push(key);
			}
		}
		this.object.value = selected.join(',');
	}
	
	this.__construct(id, flags);
}

// ============================================================================

function LiveBox (id)
{
	this.__construct = function (id)
	{
		this.baseurl = ((m = document.location.toString().match(/^\w+\:\/\/[^\/]+/)) ? m[0] : document.location.toString());
		this.target = $(id);
		this.http = new XMLHttpRequest();
		this.http.owner = this;
	}
	
	this.Update = function (uri)
	{
		this.http.open('GET',this.baseurl+uri,false);
		this.http.onreadystatechange = function () { if ((this.readyState == 4) && (this.status == 200)) this.owner.OnUpdate(this.responseText); }
		this.http.send(null);
	}
	
	this.OnUpdate = function (text)
	{
		this.target.innerHTML = text;
	}
	
	this.__construct(id);
}

// ============================================================================
// Класс для списка получателей

function ReceiversInput (id, args)
{
	this.__construct = function (id, args)
	{
		this.object = $(id);
		this.args = args;
		this.items = {};
		this.i = 0;
		
		this.Deploy();
		this.Parse();
		
		if (this.args.required && (this.GetItemsCount() == 0))
		{
			this.AppendItem();
		}
	}
	
	this.AppendItem = function ()
	{
		var i = this.i++;
		this.items[i] = new ReceiversInputItem(this);
		this.Update();
		return this.items[i];
	}
	
	this.Deploy = function ()
	{
		this.object.style.display = 'none';
		
		// container
		this.container = document.createElement('div');
		this.container.className = 'receivers_input';
		this.object.parentNode.insertBefore(this.container,this.object);
		
		// head
		this.head = document.createElement('div');
		this.head.className = 'head';
		this.head_1 = document.createElement('div');
		this.head_1.className = 'address';
		this.head_1.appendChild(document.createTextNode('E-mail'));
		this.head.appendChild(this.head_1);
		this.head_2 = document.createElement('div');
		this.head_2.className = 'ident';
		this.head_2.appendChild(document.createTextNode('Имя'));
		this.head.appendChild(this.head_2);
		this.container.appendChild(this.head);
		
		// itemsbox
		this.itemsbox = document.createElement('div');
		this.container.appendChild(this.itemsbox);
		
		// append button
		this.append = document.createElement('input');
		this.append.control = this;
		this.append.className = 'button small add';
		this.append.setAttribute('type','button');
		this.append.setAttribute('value','Добавить');
		this.container.appendChild(this.append);
		this.append.onclick = function () { this.control.AppendItem(); };
	}
	
	this.DropItem = function (i)
	{
		this.items[i].Drop();
		this.items[i] = null;
	}
	
	this.GetItemsCount = function ()
	{
		return this.itemsbox.childNodes.length;
	}
	
	this.Parse = function ()
	{
		var s = this.object.value.replace(/\r/g,'').split("\n");
		for (var i=0; i<s.length; i++)
		{
			if (m = s[i].match(/^(.+?)\s(\S+)$/))
			{
				this.AppendItem().Set(m[2],m[1]);
			}
		}
	}
	
	this.Update = function ()
	{
		out = '';
		for (i in this.items)
		{
			if (this.items[i].address.value.length)
			{
				out += this.items[i].Release()+"\n";
			}
		}
		this.object.value = out;
		this.head.style.display = (this.GetItemsCount() > 0) ? 'block' : 'none';
	}
	
	this.__construct(id, args);
}

// ============================================================================

function ReceiversInputItem (list)
{
	this.__construct = function (list)
	{
		this.list = list;
		this.parent = list.itemsbox;
		
		this.Deploy();
	}
	
	this.Deploy = function ()
	{
		// container
		this.container = document.createElement('div');
		this.container.className = 'item';
		this.parent.appendChild(this.container);
		
		// address
		this.address = document.createElement('input');
		this.address.control = this;
		this.address.className = 'address';
		this.container.appendChild(this.address);
		this.address.onchange = function () { this.control.list.Update(); };
		
		// title
		this.title = document.createElement('input');
		this.title.control = this;
		this.title.className = 'title';
		this.container.appendChild(this.title);
		this.title.onchange = function () { this.control.list.Update(); };
		
		// drop
		this.drop = document.createElement('input');
		this.drop.control = this;
		this.drop.className = 'button small delete';
		this.drop.setAttribute('type','button');
		this.drop.setAttribute('value','Удалить');
		this.container.appendChild(this.drop);
		this.drop.onclick = function () { this.control.Drop(); }
	}
	
	this.Drop = function ()
	{
		this.Set('','');
		this.parent.removeChild(this.container);
		this.list.Update();
	}
	
	this.Release = function ()
	{
		return this.title.value+' '+this.address.value;
	}
	
	this.Set = function (address, title)
	{
		this.address.value = address;
		this.title.value = title;
	}
	
	this.__construct(list);
}

// ============================================================================

function ServiceFunction (callback, interval)
{
	this.__construct = function (callback, interval)
	{
		this.id = 'iterator_'+Math.round(Math.random()*1000000);
		this.callback = callback;
		this.interval = interval;
		window[this.id] = this;
		this.Next();
		this.Start();
	}
	
	this.Start = function ()
	{
		if (!this.timer)
		{
			this.timer = window.setInterval(new Function('','window.'+this.id+'.Next();'),this.interval);
		}
	}
	
	this.Stop = function ()
	{
		if (this.timer)
		{
			window.clearInterval(this.timer);
		}
	}
	
	this.Next = function ()
	{
		this.callback.call();
	}
	
	this.__construct(callback, interval);
}

// ============================================================================

function AddOptionToSelect (id)
{
	var sel, title, option;
	sel = $(id);
	if (title = window.prompt('Название'))
	{
		option = document.createElement('option');
		option.text = title;
		option.value = title;
		try
		{
			sel.add(option, null);
		}
		catch (e)
		{
			sel.add(option);
		}
		sel.selectedIndex = sel.length-1;
	}
}

// ============================================================================