window.addEvent('domready', function() {

	// определяем домен 3 уровня
	var d3 = document.domain.split('.');
	d3 = d3[0];

	// создание объекта Notimoo
	var notimooManager = new Notimoo({
		visibleTime: '4000',
		notificationOpacity: '0.9'
	});

	// tabs
	if ($('tabs') && $('home'))
	{
		var si = $('urid').value == 1 ?  1 : 0;
		var tabs = new MGFX.Tabs('.tab','.feature',{
			autoplay: false,
			transitionDuration: 500,
			startIndex: si,
			hover: true
		});
		$$('.feature').setStyle('display', 'block');
	}

	// multibox
	new MultiBox('a[rel=mbox]', {
		useOverlay: true,
		path: '/themes/_' + d3 + '/swf/',
		of: 'из'
	});
	new MultiBox('a[rel=mboxc]', {
		useOverlay: true,
		path: '/themes/_' + d3 + '/swf/',
		of: 'из'
	});
	new MultiBox('a[rel=mboxf]', {
		useOverlay: true,
		path: '/themes/_' + d3 + '/swf/',
		of: 'из'
	});
	new MultiBox('a[rel=mboxs]', {
		useOverlay: true,
		path: '/themes/_' + d3 + '/swf/',
		of: 'из'
	});

	// форма вопроса
	if ($('toggle_questions_form'))
	{
		$('toggle_questions_form').addEvent('click', function(){
			if ($('questions_form').getStyle('display') == 'none')
			{
				$('questions_form').setStyle('display', 'block');
			}
			else
			{
				$('questions_form').setStyle('display', 'none');
			}
			return false;
		});
	}

	// ajax поиск по вопросам
	if ($('q_search_form'))
	{
		$('q_search_form').addEvent('submit', function(e){
			e.stop();
			window.location = "/questions" + ($('groupid').value ? "/" + $('groupid').value : "") + ($('q_search').value ? "/search/" + encodeURIComponent($('q_search').value) : "");
		});
	}

	// подписка
	if ($('subscribe_a'))
	{
		$('subscribe_a').addEvent('click', function(){
			if ($('subscribe_form').getStyle('display') == 'none')
			{
				$('subscribe_form').setStyle('display', 'block');
			}
			else
			{
				$('subscribe_form').setStyle('display', 'none');
			}
			return false;
		});
		if ($('subscribe_form')){
			$('subscribe_form').addEvent('submit', function(e) {
				e.stop();
				var log1 = $('log_res4').setStyle('display', 'block').empty().addClass('ajax-loading');
				this.set('send', {onComplete: function(response) {
					log1.removeClass('ajax-loading');
					if (response == 2)
					{
						log1.set('html', 'Введены не все данные');
					}
					else if (response == 3)
					{
						log1.set('html', 'Не верно указанн адрес электронной почты');
					}
					else if (response == 4)
					{
						log1.set('html', 'Вы уже подписанны на рассылку новостей');
					}
					else
					{
						log1.set('html', '<span style="color: green;">Вы подписанны на рассылку новостей</span>');
					}
				}});
				this.send();
			});
		};
	}

	// управление формой личного кабинета
	if ($('login-form'))
	{
		var lfeff = new Fx.Morph($('login-form'), {duration: 500});
		$('lk').addEvent('click', function(){
			lfeff.cancel();
			if ($('login-form').getStyle('top') == '-300px') lfeff.start({'top': 46}); else lfeff.start({'top': -300});
			return false;
		});
		$$('#login-form .close').addEvent('click', function(){lfeff.start({'top': -300});});
	}

	// slideitmoo
	if ($('SlideItMoo_outer')){
		new SlideItMoo({
			overallContainer: 'SlideItMoo_outer',
			elementScrolled: 'SlideItMoo_inner',
			thumbsContainer: 'SlideItMoo_items',
			itemsVisible:1,
			itemsSelector: '.SlideItMoo_element',
			itemWidth: 270
		});
	};

	// Menu
	$(document.body).getElements('li.menu').each(function(elem){
		var list = elem.getElement('ul');
		list.setStyle('display','block');
		var h = list.offsetHeight;
		var myFx = new Fx.Morph(list, {duration: '400'}).set({'height': 0});
		elem.addEvents({
			'mouseenter' : function(){
				myFx.cancel();
				myFx.start({'height': h});
			},
			'mouseleave' : function(){
				myFx.cancel();
				myFx.start({'height': 0});
			}
		});
	});

	// City
	$(document.body).getElements('ul.citys').each(function(elem){
		elem.setStyle('display','block');
		var h = elem.offsetHeight;
		var myFx = new Fx.Morph(elem, {duration: '300'}).set({'height': 0});
		$$('a.city').addEvents({
			'click' : function(){
				myFx.cancel();
				if (elem.getStyle('height').toInt() == 0)
				{
					myFx.start({'height': h});
				}
				else
				{
					myFx.start({'height': 0});
				}
				return false;
			}
		});
	});

	// ajax - проверка дисконтной карты
	var cardscheck = new Request.HTML({
		url: '',
		onSuccess: function(html){
			$('cardsmoney').set('text', '');
			$('cardsmoney').adopt(html);
		},
		onFailure: function(){
			$('cardsmoney').set('text', 'Error');
		}
	});

	// проверка дисконтной карты
	if ($('cardssend')){
		$('cardssend').addEvent('click', function(e) {
			var id = $('card').get('value').toInt();
			if (id)
			{
				cardscheck.send({url: '/?catalog=checkcard&id='+id});
			}
			else
			{
				notimooManager.show({
					title: 'Дисконтная карта',
					message: 'Произошла ошибка. Не указан номер дисконтной карты'
				});
			}
		});
	}

	// ajax - выбор шага + выбор способа доставки + выбор способа оплаты
	var set_step = new Request({
		url: '',
		onSuccess: function(html){
			window.location = "/order";
		}
	});

	// изменить шаг на 1
	if ($('step1')){
		$('step1').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=1'});
		});
	}

	// изменить шаг на 2
	if ($('step2')){
		$('step2').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=2'});
		});
	}

	// изменить шаг на 3
	if ($('step3')){
		$('step3').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=3'});
		});
	}

	// изменить шаг на 1
	if ($('step1go1')){
		$('step1go1').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=1'});
		});
	}

	// изменить шаг на 1
	if ($('step1go2')){
		$('step1go2').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=1'});
		});
	}

	// изменить шаг на 2
	if ($('step2go')){
		$('step2go').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=2'});
		});
	}

	// изменить шаг на 3
	if ($('step3go')){
		$('step3go').addEvent('click', function(e) {
			set_step.send({url: '/?catalog=setstep&id=3'});
		});
	}

	// выбор способа доставки
	if ($('deliverySend')){
		$('deliverySend').addEvent('click', function(e) {
			el = $(document.body).getElements('input.delivery');
			if ($('delivery_razgr').get('checked'))
			{
				var r = "&delivery_razgr=1";
			}
			if ($('delivery_podem').get('checked'))
			{
				var p = "&delivery_podem=1";
			}
			if (el[0].get('checked'))
			{
				set_step.send({url: '/?catalog=setdelivery&id=1'});
			}
			else if (el[1].get('checked'))
			{
				set_step.send({url: '/?catalog=setdelivery&id=2'+r+p});
			}
			else
			{
				notimooManager.show({
					title: 'Способ доставки',
					message: 'Произошла ошибка. Не указан способ доставки'
				});
			}
		});
	}

	// контактные данные - физик
	if ($('orderForm1')){
		$('orderForm1').addEvent('submit', function(e) {
			e.stop();
			this.set('send', {onComplete: function(response) {
				if (response == "1")
				{
					window.location = "/order";
				}
				else
				{
					notimooManager.show({
						title: 'Контактные данные',
						message: response
					});
				}
			}});
			this.send();
		});
	};

	// контактные данные - юрик
	if ($('orderForm2')){
		$('orderForm2').addEvent('submit', function(e) {
			e.stop();
			this.set('send', {onComplete: function(response) {
				if (response == "1")
				{
					window.location = "/order";
				}
				else
				{
					notimooManager.show({
						title: 'Контактные данные',
						message: response
					});
				}
			}});
			this.send();
		});
	};

	// выбор способа оплаты
	if ($('oplata')){
		$('oplata').addEvent('click', function(e) {
			el = $(document.body).getElements('input.order_oplata');
			if (el[0].get('checked'))
			{
				set_step.send({url: '/?catalog=setoplata&id=1'});
			}
			else if (el[1].get('checked'))
			{
				set_step.send({url: '/?catalog=setoplata&id=2'});
			}
			/*
			else if (el[2].get('checked'))
			{
				set_step.send({url: '/?catalog=setoplata&id=3'});
			}
			*/
			else
			{
				notimooManager.show({
					title: 'Способ оплаты',
					message: 'Произошла ошибка. Не указан способ оплаты'
				});
			}
		});
	}

	// подтверждение заказа
	if ($('confirm')){
		$('confirm').addEvent('click', function(e) {
			document.location = '/?catalog=ordered';
		});
	}

	// ajax - добавление товара в корзину
	var req_add = new Request.HTML({
		url: '',
		onSuccess: function(html){
			$('cart_1').set('text', '');
			$('cart_1').adopt(html);
			notimooManager.show({
				title: 'Добавление товара в корзину',
				message: 'Товар успешно добавлен в вашу корзину'
			});
		},
		onFailure: function(){
			notimooManager.show({
				title: 'Добавление товара в корзину',
				message: 'Произошла ошибка. Товар не был добавлен в вашу корзину'
			});
		}
	});

	// ajax - изменение количества товаров в корзине
	var req_change = new Request.HTML({
		url: '',
		onSuccess: function(html){
			$('cart_1').set('text', '');
			$('cart_1').adopt(html);
			notimooManager.show({
				title: 'Изменение товара в корзине',
				message: 'Количество товара в корзине успешно изменено'
			});
		},
		onFailure: function(){
			notimooManager.show({
				title: 'Изменение товара в корзине',
				message: 'Произошла ошибка. Количество товара не было изменено'
			});
		}
	});

	// ajax (в корзине)
	var req_plaska = new Request.HTML({
		url: '',
		onSuccess: function(html){
			$('cart_2').set('text', '');
			$('cart_2').adopt(html);
		},
		onFailure: function(){
		}
	});

	// уменьшение количества товаров
	$(document.body).getElements('div.minus_list').each(function(elem){
		var cnt = elem.getNext().getElement('input');
		elem.addEvents({
			'click' : function(){
				if (cnt.get('value').toInt() == 1)
				{
				}
				else if (cnt.get('value').toInt() > 1)
				{
					cnt.set('value', cnt.get('value').toInt()-1);
				}
				else
				{
					cnt.set('value', 1);
				}
			}
		});
	});

	// увеличение количества товаров
	$(document.body).getElements('div.plus_list').each(function(elem){
		var cnt = elem.getPrevious().getElement('input');
		elem.addEvents({
			'click' : function(){
				if (cnt.get('value').toInt() > 0)
				{
					cnt.set('value', cnt.get('value').toInt()+1);
				}
				else
				{
					cnt.set('value', 1);
				}
			}
		});
	});

	// положить товар в корзину
	$(document.body).getElements('div.myform_submit').each(function(elem){
		elem.addEvents({
			'click' : function(){
				var id = elem.getPrevious().getPrevious().getPrevious().getPrevious().get('value');
				var cnt = elem.getPrevious().getPrevious().getElement('input').get('value').toInt();
				if (cnt && cnt > 0)
				{
					elem.getPrevious().getPrevious().getElement('input').set('value', cnt);
					req_add.send({url: '/?catalog=addtocart&id='+id+'&cnt='+cnt});
				}
				else
				{
					notimooManager.show({
						title: 'Добавление товара в корзину',
						message: 'Произошла ошибка. Количество товара должно быть числом'
					});
				}
			}
		});
	});

	// изменить количество товаров в корзине
	$(document.body).getElements('div.myform_submit_update').each(function(elem){
		elem.addEvents({
			'click' : function(){
				var id = elem.getPrevious().getPrevious().getPrevious().getPrevious().get('value');
				var cnt = elem.getPrevious().getPrevious().getElement('input').get('value').toInt();
				if (cnt && cnt > 0)
				{
					elem.getPrevious().getPrevious().getElement('input').set('value', cnt);
					req_change.send({url: '/?catalog=changecart&id='+id+'&cnt='+cnt});
					req_plaska.send({url: '/?catalog=changecart&id='+id+'&cnt='+cnt+'&itog=1'});
				}
				else
				{
					notimooManager.show({
						title: 'Изменение товара в корзине',
						message: 'Произошла ошибка. Количество товара должно быть числом'
					});
				}
			}
		});
	});

	// оформление покупки
	if ($('order'))
	{
		$('order').addEvents({
			'click' : function(){
				window.location = "/order";
			}
		});
	}

	// регистрация и логинизация
	if ($('ajaxForm')){
		$('ajaxForm').addEvent('submit', function(e) {
			e.stop();
			var log1 = $('log_res1').setStyle('display', 'block').empty().addClass('ajax-loading');
			this.set('send', {onComplete: function(response) {
				log1.removeClass('ajax-loading');
				log1.set('html', response);
			}});
			this.send();
		});
	};
	if ($('loginForm')){
		$('loginForm').addEvent('submit', function(e) {
			e.stop();
			var log3 = $('log_res3').setStyle('display', 'block').empty().addClass('ajax-loading');
			this.set('send', {onComplete: function(response) {
				log3.removeClass('ajax-loading');
				if (response == "logined")
				{
					window.location = "/users/lk";
				}
				else
				{
					log3.set('html', response);
				}
			}});
			this.send();
		});
	};

	ch = function(clr, tclr, fclr)
	{
		el3 = $(tclr+'d');
		el4 = $(tclr+'s');
		$('coler-div').setStyle('background', '#'+clr);
		if ($('coler-div-input').get('value'))
		{
			el5 = $($('coler-div-input').get('value')+"d");
			el5.setStyle('width', '39px');
			el5.setStyle('height', '15px');
			el5.setStyle('border', '0px solid #333333');

			el6 = $($('coler-div-input').get('value')+"s");
			el6.setStyle('width', '39px');
			el6.setStyle('height', '15px');
			el6.setStyle('border', '0px solid #333333');
		}

		el3.setStyle('width', '37px');
		el3.setStyle('height', '13px');
		el3.setStyle('border', '1px solid #333333');

		el4.setStyle('width', '34px');
		el4.setStyle('height', '11px');
		el4.setStyle('border', '1px solid #FFFFFF');

		if (fclr)
		{
			$('coler-div').setStyle('color', '#4c4c4c');
			$('coler-div-input').setStyle('color', '#333333');
		}
		else
		{
			$('coler-div').setStyle('color', '#FFFFFF');
			$('coler-div-input').setStyle('color', '#FFFFFF');
		}
		$('coler-div-input').value = tclr;
	};

	// всплывашка с опросом
	if ($('interview-button'))
	{
		$('interview-form').setStyle('height', $(document.body).getScrollSize().y);
		var OFx = new Fx.Morph($('interview-form'), {duration: 150});
		$('interview-button').addEvents({
			'click' : function(elem){
				OFx.start({
					display: 'block',
					opacity: [0, 1]
					});
			}
		});
		// ajax - кнопка отмена
		var cancelInterview = new Request({
			url: '',
			onSuccess: function(text){},
			onFailure: function(){}
		});
		$('interview-cancel').addEvents({
			'click' : function(){
				$('interview-form').setStyles({'display': 'none', 'opacity': '0'});
				cancelInterview.send({url: '/?interview=setcancel'});
			}
		});
		// ajax - отправка данных
		var sendInterview = new Request({
			url: '',
			onSuccess: function(text){
				if (text == 1)
				{
					$('interview-form').setStyles({'display': 'none', 'opacity': '0'});
					$('interview-button').setStyles({'display': 'none'});
					notimooManager.show({
						title: 'Опросник',
						message: 'Ваши ответы получены. Спасибо за участие в опросе.'
					});
				}
				else
				{
					notimooManager.show({
						title: 'Опросник',
						message: 'Необходимо ответить на все вопросы.'
					});
				}
			},
			onFailure: function(){}
		});
		$('interview-ok').addEvents({
			'click' : function(elem){
				var s = '';
				var e = $('interview-ok').getParent().getPrevious().getElements('input[checked]');
				e.each(function(elem){
					s += '_' + elem.get('value');
				});
				sendInterview.send({url: '/?interview=setanswer&s='+s.substr(1)});
			}
		});
	}

	// часы в шапке
	/*
	var clock = function()
	{
		data = new Date();
		switch (data.getMonth())
		{
			case 0: month = "января"; break;
			case 1: month = "февраля"; break;
			case 2: month = "марта"; break;
			case 3: month = "апреля"; break;
			case 4: month = "мая"; break;
			case 5: month = "июня"; break;
			case 6: month = "июля"; break;
			case 7: month = "августа"; break;
			case 8: month = "сентября"; break;
			case 9: month = "октября"; break;
			case 10: month = "ноября"; break;
			case 11: month = "декабря"; break;
		}
		h = data.getHours();
		m = data.getMinutes();
		if (m < 10) {m = "0" + m}
		$('time').set('text', data.getDate() + ' ' + month + ', ' + h + ':' + m);
	};
	clock();
	clock.periodical(1000);
	*/
});

function save(n,t,d,cn,cd)
{
	var cc = '';
	if (!t) t = n + '@' + d;
	if (cn && cd) cc = '?cc=' + cn + '@' + cd;
	document.write('<a href="' + 'mailto:' + n + '@' + d + cc + '" title="' + n + '@' + d + '">' + t +'</a>');
}

// Функция проверки на ввод не цифр
function enableElements(chkbox, group)
{
	var visSetting = (chkbox.checked) ? "" : "none"
	document.getElementById(group).style.display = visSetting
}

