﻿// 

/*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);
		}
	}
	return obj;
}*/

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 extend (a)
{
	for (var i=1; i<arguments.length; i++)
	{
		eval('b = new '+arguments[i]+'();'); //b = arguments[i];
		for (property in b)
		{
			a[property] = b[property];
		}
	}
}

if (navigator.userAgent.search(/MSIE/) != -1)
{
	var Element = {};
	Element.prototype = {};
}

Array.prototype.intersect = function (b)
{
	var a = this;
	var c = [];
	for (var i=0; i<a.length; i++)
	{
		if (b.search(a[i]) !== -1)
		{
			c.push(a[i]);
		}
	}
	return c;
}

Array.prototype.search = function (arg)
{
	for (var i=0; i<this.length; i++)
	{
		if (this[i] == arg)
		{
			return i;
		}
	}
	return -1;
}

Math.rand = function (min, max)
{
	return this.round(min+(max-min)*this.random());
};

String.prototype.html = function ()
{
	return this.replace(/\&/g,'&amp;').replace(/\"/,'&quot;').replace(/\</,'&lt;').replace(/\>/,'&gt;');
}

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,'');
}

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.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;
	}
}

//

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.ready = true;
		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 ()
	{
		if (this.ready)
		{
			this.ready = false;
			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 = 'data = '+raw+';';
		if (this.type == 'json')
		{
			eval('data = '+raw+';');
		}
		else
		{
			data = raw;
		}
		this.callback.call([data]);
		this.ready = true;
	}
	
	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');
		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');
			}
			//alert(date.toUTCString()+' | '+date.toLocaleString()+' | '+(date.getTime()/1000));
			//this.input.value = (date.getTime() + (date.getTimezoneOffset()*60000))/1000;
			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);
			date.setHours(this.args.time ? this.hours.value : 0);
			date.setMinutes(this.args.time ? this.minutes.value : 0);
			date.setSeconds(1); // avoid unixtime=0
			this.Set(Math.round(date.getTime()/1000));*/
			datestr = this.month.value+'/'+this.day.value+'/'+this.year.value;
			if (this.args.time) datestr += ' '+this.hours.value+':'+this.minutes.value+':00';
			//alert(datestr+'||'+Date.parse(datestr));
			unixtime = Date.parse(datestr)/1000;
			if (this.year.value < 1980) unixtime += 3600; // это пиздец, но зато быстро
			this.Set(unixtime);
		}
		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);
}

// Класс для ajax

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,true);
		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;
		if (this.OnUpdateDone)
		{
			this.OnUpdateDone();
		}
	}
	
	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();
		this.Update();
		
		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(this.args.address_field || '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','+1');
		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 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;
}

// костыли

HTMLElement.prototype.click = function()
{
	var evt = this.ownerDocument.createEvent('MouseEvents');
	evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	this.dispatchEvent(evt);
}