var roothost = 'http://' + location.host;
document.write(unescape("%3Cscript src='/js/mbrowser.js' type='text/javascript'%3E%3C/script%3E"));
document.write(unescape("%3Cscript src='/js/ajax.js' type='text/javascript'%3E%3C/script%3E"));
var lang = 'ru';


window.addEvent('domready', function(){
	
	$$('input.empty').emptyInput();
	$$('input.hint').hintInput();
	
	
	this.addEvent('resize', function(){
		/*
		if(this.getWidth <= 996 || $('content').getStyle('margin-left').toInt() == 0 || Browser.Engine.trident ) return;
		
		
		$('content').getWidth();
		
		var r_width = $('content').getWidth() - $('content').getStyle('margin-left').toInt() - $('content').getElement('.left').getWidth() - $('content').getElement('.left').getStyle('margin-left').toInt() - $('content').getElement('.right').getStyle('margin-left').toInt();
		
		$('content').getElement('.right').setStyle('width', (r_width - 10) +'px');
		*/
	});
	
	
	this.addEvent('resize', function(){
		
		var goods = $$('#goods .good');
		var container = $('goods');
		var good_minwidth = 320;
		if(!container || !goods) return;
		
		var cols_num = Math.floor(container.getWidth() / good_minwidth);
		if(cols_num < 2) return;
		
		goods.setStyle('width', (100 / cols_num ) - (6/cols_num) + '%');
		
	});
	
	
	new Request({
		'url': '/check_worktime.php',
		'onSuccess': function(res){
			
			if(res != '1')
				return;
				
			var name = 'we_closed'
			var content = '\
			<p class="green" style="width: 480px; font-size: 1.1em" align="center"><br />\
				Обращаем ваше внимание, что в данный момент<br />\
				наша кухня закрыта. Все поступившие заказы<br />\
				будут обработаны после 10:00 утра.<br />\
			</p>';
			
			var ok_btn = new Element('div', {
				'text': 'OK',
				'class': 'smallbutton',
				'events': {
					'click': function(){
						popupFxs[name].hide();
					}
				}
			});

			popupFxs[name] = new Popup(name, content, 'Здравствуйте!');

			ok_btn.inject(popupFxs[name].textcontent.set('align', 'center'));
			popupFxs[name].show();
			
		}
	}).send();
	
	
	
	var voprosikEvent = function(els){
		
		if(!els) return;
		
		els.addEvent('click', function(e){
			e.stop();
			
			var name =  'voprosik';
			var content = '<p class="green" style="width: 480px; font-size: 1.1em" align="center"><br />Регистрируясь на нашем сайте, Вы избавляетесь<br/> от необходимости вводить каждый раз личные данные<br/> при оформлении заказа.</p>';
			if(this.hasClass('delivery')){
				name  = 'voprosik_delivery';
				content = '<p class="green" style="width: 480px; font-size: 1.1em" align="center"><br />При заказе без доставки действует скидка 10%.<br /> Заказ можно будет забрать по адресу ул. Электриков, 13.</p>';
				
			}
			if(popupFxs[name]){
				popupFxs[name].show();
				return;
			}
			
			var ok_btn = new Element('div', {
				'text': 'OK',
				'class': 'smallbutton',
				'events': {
					'click': function(){
						popupFxs[name].hide();
					}
				}
			});
			
			popupFxs[name] = new Popup(name, content, 'Внимание!');
			
			ok_btn.inject(popupFxs[name].textcontent.set('align', 'center'));
			popupFxs[name].show();
			

		});
	}
	
	
	voprosikEvent( $$('.voprosik') );
	
	
	
	this.addEvent('resize', function(){	
		if(!$('userlogin')) return;
		if(this.getWidth() < 1100 ){
			$$('#header .userbar, #header .header_btn').setStyle('margin-right', '1%');
		}
		else
			$$('#header .userbar, #header .header_btn').setStyle('margin-right', '');
	}).fireEvent('resize');
	
	
	
	new Element('div', {
		'id':'curtain',
		'styles': {
			'opacity': 0
		}
	}).inject('body');
	
	
	//меню
	if( $('menu') ){
		if($$('#menu li.curr')[0])
			$$('#menu li.curr')[0].getAllPrevious('li').addClass('psevdocurr');
	
		$$('#menu li').addEvent('click', function(){
			$$('#menu li.curr').removeClass('curr')
			$$('#menu li.psevdocurr').removeClass('psevdocurr');
			$$('#menu li .no_brtr').destroy();
			
			if(a = this.getElement('a')){
				window.location.href = a.get('href');
				$('goods').empty().getParent().addClass('loading');
				
				
			}
			this.addClass('curr');
			new Element('div', {'class':'no_brtr'}).inject(this);
			
			this.getAllPrevious('li').addClass('psevdocurr');
		});
	}
	
	
	//окошко авторизации
	if($('userlogin')){
		
		$('userlogin').addEvent('success', function(res){
			window.location.href = window.location.href;
		}).checkSubmitEvent(true);
	}
	
	
	//История заказов
	var repeatOrderRequest = new Request.JSON({
		'headers': {'X-Request': 'JSON'},
		'url': '/get/cart?act=repeat',
		'method': 'get',
		'onRequest': function(){
			order_loader.addClass('loading');
		},
		'onComplete': function(){
			order_loader.removeClass('loading');
			if(popupFxs['/history'])
				popupFxs['/history'].hide();
		},
		'onSuccess': function(JSON){
			switchStages(JSON);
			
			if(!orderSlide.open)
				orderSlide.toggle();
		}
	});
	
	var setHistory = function(json){
		var history = $('odershistory');
		if(history){
			
			history.getElements('.greenbutton').addEvent('click', function(){
				var orderid = this.get('name');
				if(orderid && orderid.toInt() >0)
					repeatOrderRequest.send('order='+orderid.toInt());
			});
			
			var myAccordion = new Accordion(history, 'div.orderdate', 'div.orderinfo', {
				opacity: false,
				initialDisplayFx: false,
				onActive: function(toggler, element){
					toggler.removeClass('close').addClass('open');
				},
				onBackground: function(toggler, element){
					toggler.removeClass('open').addClass('close');
				}
			});
			
			
			if(json.pages && json.pages.total > 1){
			
				var pages = new Element('div', {
					'align': 'center',
					'class': 'pages'
				});
				
				var i=1;
				var nn = json.pages.total;
				var start = 1;
				if(json.pages.total > 5){
					
					if(json.pages.curr > 2){
						start = json.pages.curr - 2;
					}
					nn = start + 4;
					
					if(nn > json.pages.total){
						start = start - (nn - json.pages.total);
						nn = json.pages.total;
					}
					
				}
				
				for (i=start;i<=nn;i++){
					var pagei = new Element('i',{
						'text': i,
						'events': {
							'click': function(){
								if(this.hasClass('curr')) return;
								
								pages.getElements('i').removeClass('curr');
								this.addClass('curr');
								
								historyPageRequest.send('p='+this.get('text'));
							}
						}
					}).inject(pages);
					
					if(i == json.pages.curr)
						pagei.addClass('curr');
				}
				
				new Element('span',{
					'html': '&larr;',
					'class': 'gray',
					'events': {
						'click': function(){
							if(pages.getElement('.curr').getPrevious('i'))
								pages.getElement('.curr').getPrevious('i').fireEvent('click');
						}
					}
				}).inject(pages, 'top');
				
				new Element('span',{
					'html': '&rarr;',
					'class': 'gray',
					'events': {
						'click': function(){
							if(pages.getElement('.curr').getNext('i'))
								pages.getElement('.curr').getNext('i').fireEvent('click');
						}
					}
				}).inject(pages);
				
				pages.inject(popupFxs['/history'].textcontent);
			}
			
		}
	}
	var historyPageRequest = new Request.JSON({
		'headers': {'X-Request': 'JSON'},
		'url': '/history?json=1',
		'method': 'get',
		'onRequest': function(){
			
			var history = $('odershistory');
			if(!history) return;
			
			history.empty();
			history.addClass('loading');
			
		},
		'onComplete': function(){
			var history = $('odershistory');
			if(!history) return;
			
			history.empty();
			history.removeClass('loading');
		},
		'onSuccess': function(JSON){
			var history = $('odershistory');
			if(!history) return;
			history.destroy();
			
			popupFxs['/history'].setHtml(JSON.html);
			setHistory(JSON);
		}
	});
	
	
	//popups
	$('curtain').setStyle('opacity', 0);
	var popupFxs = new Array();
	$$('#curtain, .align_center_to_left, .align_center').addEvent('click', function(e){
		
		$$('.textpopup .close_btn').fireEvent('click', e);
		
	});
	
	$$('a.json_in_popup').addEvent('click', function(e){
		e.stop();
		
		
		var href = this.get('href');
		
		if(!href || href == '') return;
		
		if(popupFxs[href]){
			popupFxs[href].show();
			return;
		}
		
		var title = (this.get('title')) ? this.get('title') : this.get('text');
		
		popupFxs[href] = new Popup(href, '<div class="loading"></div>', title);
		popupFxs[href].show();
		
		var json_in_popup_request = new Request.JSON({
			'method':'get',
			'url': href,
			'onSuccess': function(json){
				
				
				var fn = function(){
					popupFxs[href].setHtml(json.html)
					
					
					if(href == '/history'){
						setHistory(json);
						
					}
					
					if(href == '/service'){
						var form = popupFxs[href].popup.getElement('form');
						
						form.addEvents({
							'onRequest': function(){
								form.getElement('input[type=submit]').set('disabled', true).addClass('disabled');
							},
							'onComplete': function(){
								form.getElement('input[type=submit]').set('disabled', false).removeClass('disabled');
							},
							'success': function(res){
								popupFxs[href].hide(true);
								popupFxs[href] = false;
							}
							
						}).checkSubmitEvent(true);
						
						form.getElement('input[type=submit]').addEvent('click', function(e){
							e.stop();
							if(!this.hasClass('disabled'))
								form.sendform(e);
						});
						
						form.getElement('textarea').addEvent('keyup', function(){
							if(this.get('value') == '')
								form.getElement('input[type=submit]').addClass('disabled');
							else
								form.getElement('input[type=submit]').removeClass('disabled');
						}).fireEvent('keyup');
						
					}
					
					popupFxs[href].show(true);
					
					if(href == '/register'){
						var form = popupFxs[href].popup.getElement('form')
						form.addEvent('success', function(res){
							
							popupFxs[href].hide(true);
							
							var fn = function(){window.location.href = window.location.href};
							fn.delay(500);
							
						}).checkSubmitEvent(true);
						
						form.getElement('input[type=submit]').addEvent('click', function(e){
							e.stop();
							form.sendform(e);
						});
						
						var new_address_btn = popupFxs[href].popup.getElement('.new_address_btn');
						
						var addresstitle = new_address_btn.getParent('tr');
						var oldaddress1 = addresstitle.getNext('tr');
						var oldaddress2 = oldaddress1.getNext('tr');
						
						var address_table = addresstitle.getParent('table');
						
						var address1 = oldaddress1.clone();
						var address2 = oldaddress2.clone();
						
						addresstitle = addresstitle.clone();
						
						var num = addresstitle.getElement('b').get('text').replace('Адрес ', '');
						num = num.toInt();
						
						if(addresstitle.getElement('.new_address_btn'))
							addresstitle.getElement('.new_address_btn').destroy();
						addresstitle.getElement('b').set('text', 'Адрес '+num);
						
						
						
						
						address1.getElements('input').each(function(input){
							input.set('value', '');
						});
						address2.getElements('input').each(function(input){
							input.set('value', '');
						});
						
						
						new_address_btn.addEvent('click', function(){
							num++;
							var new_addresstitle = addresstitle.clone();
							new_addresstitle.getElement('b').set('text', 'Адрес '+num+'  ')
							new_addresstitle.inject(address_table);
							
							var new_address1 = address1.clone().inject(address_table);
							var new_address2 = address2.clone().inject(address_table);
							//new_address1.set('html', new_address1.get('html').replace(/address\[(\d+)\]/, 'address['+num+']') )
							//new_address2.set('html', new_address2.get('html').replace(/address\[(\d+)\]/, 'address['+num+']') )
							
							
							new Element('span', {
								'class': 'ajax',
								'html': 'удалить',
								'events': {
									'click': function(e){
										e.stop();
										new_addresstitle.destroy();
										new_address1.destroy();
										new_address2.destroy();
									}
								}
							}).injectAfter( new_addresstitle.getElement('b') );
							
							
							new_address1.getElements('input').each(function(input){
								input.set('name', input.get('name').replace(/address\[(\d+)\]/, 'address['+num+']'));
							});
							new_address2.getElements('input').each(function(input){
								input.set('name', input.get('name').replace(/address\[(\d+)\]/, 'address['+num+']'));
							});
							
							
							//.replace(/address\[(\d+)\]/, 'address['+num+']').inject(address_table);
						});
						
						if(popupFxs[href].popup.getElements('.del_address_btn')){
							popupFxs[href].popup.getElements('.del_address_btn').addEvent('click', function(e){
								e.stop();
								var addresstitle = this.getParent('tr');
								var oldaddress1 = addresstitle.getNext('tr');
								var oldaddress2 = oldaddress1.getNext('tr');
							
								addresstitle.destroy();
								oldaddress1.destroy();
								oldaddress2.destroy();
							
							});
						}
					}
				}
				
				
				
				fn.delay(500);
				
			}
		}).send('json=1');
		
	});
	
	
	//кнопки
	$$('.header_btn').addEvent('click', function(e){
		if(this.get('id') == '') return;
		e.stop();
		var btn_id = this.get('id');
		
		var id = btn_id.replace(/\_btn$/, '');
		
		
		if(popupFxs[id]){
			popupFxs[id].show();
		}
		
	});
	
	
	//Окошко заказа
	var status = {
		'false': 'Свернуть',
		'true': 'Развернуть'
	};
	var orderSlide = new Fx.Slide('order', {
		duration: 300,
		'onStart': function(){
			$('order_toggle').getElement('i').set('html', status[this.open]);
			
			if(this.open){
				$('order_toggle').getElement('img.arr').addClass('up');
			}
			else
				$('order_toggle').getElement('img.arr').removeClass('up');
		}
	}).hide();
	$('order_toggle').getElement('i').set('html', status['true']);
	$('order_toggle').getElement('img.arr').addClass('up');
	
	orderSlide.step = function(){
		var time = $time();
		if (time < this.time + this.options.duration){
			var delta = this.options.transition((time - this.time) / this.options.duration);
			this.set(this.compute(this.from, this.to, delta));
		} else {
			this.set(this.compute(this.from, this.to, 1));
			this.complete();
		}
		this.onStep();
	};
	
	orderSlide.onStep = function(){
		this.fireEvent('step', this.subject);
	};
	
	var window_scroll = window.getScroll();
	var fixed_top = $('order_container').getStyle('margin-top').toInt() * -1;
	orderSlide.addEvent('onStep', function(el){
		
		//var offsetSize = window.getSize(), scrollSize = window.getScrollSize();
		//var max = scrollSize.y - offsetSize.y;
		
		//window.scrollTo(window_scroll.x, max);
		
		var margin = ( fixed_top + el.getStyle('height').toInt() + el.getStyle('margin-top').toInt());
		$('order_container').setStyle('margin-top',   -1 * margin + 'px');
		$('body').setStyle('padding-bottom',  margin + 'px');
		
	});
	
	$$('#order_toggle i').addEvent('click', function(e){
		e.stop();
		orderSlide.toggle();
	});
	
	
	
	
	var cart = $('order');
	var cart_content = $('order').getElement('.content');
	var order_loader = $('order_loader');
	var total_price = $('total_price');
	
	set_total_price = function(JSON){
		
		if(JSON.discount && JSON.discount.price != '')
			total_price.set('html', JSON.discount.price+' руб.'+'<p class="sans-serif red" style="font-size: 0.5em;">'+JSON.discount.name+'</p>');
		else
			total_price.set('text', JSON.price+' руб.');
	};
	
	
	
	var quantRequest = new Request.JSON({
		'headers': {'X-Request': 'JSON'},
		'url': '/get/cart?act=quant',
		'method': 'get',
		'onRequest': function(){
			order_loader.addClass('loading');
		},
		'onComplete': function(){
			order_loader.removeClass('loading');
		},
		'onSuccess': function(JSON){
			
			if(!$('cartgood'+JSON.gid)) return;
			
			if(JSON.quant <= 0){
				$('cartgood'+JSON.gid).destroy();
				get_pizzas_table();
				cartRequest.send();
				return;
			}
			
			var quant = $('cartgood'+JSON.gid).getElement('td.quant')
			
			if(!quant) return;
			
			quant.set('text', quant.get('text').replace(/\d+/, JSON.quant));
			//total_price.set('text', JSON.price);
			
			set_total_price(JSON);
		}
	});
	
	
	
	var pizzas_table = false;
	//Выделенная пицца
	var get_pizzas_table = function(){
		pizzas_table = false;
		if(cart_content.getElements('.pizza') && cart_content.getElements('.pizza').length > 0){
			pizzas_table = new Element('table', {
				'cellpadding': '5',
				'cellspacing': '0',
				'border': '0',
				'styles':{
					'margin-bottom': '1em'
				}
			});
			
			cart_content.getElements('.pizza').each(function(pizza){
				
				var tr = new Element('tr').inject(pizzas_table);

				pizza.getElement('.icon').clone().addClass('icon').inject(tr);
				var name = pizza.getElement('.name').clone().addClass('name red').addClass('serif bold').inject(tr).set('align', 'left');
				
				var weight = pizza.getElement('.weight').get('text').toString().replace(/\s+/, ' ').replace(/^\s+/, '').replace(/\s+$/, '');
				if( weight != '' )
					name.set('html', name.get('text') + ' <span class="weight">'+weight+'</span>');
				
				
				id = pizza.get('id').replace(/^cartgood/, '');

				new Element('input', {
					'type': 'checkbox',
					'name': 'additional[]',
					'value': id
				}).inject(
					new Element('td').inject(tr)
				).makeCheckbox();
				
				$$('#addit_content a.addcart').removeClass('disabled');
			
			});
			
		}
		else{
			$$('#addit_content a.addcart').addClass('disabled');
		}
			
		
		return pizzas_table;
	}
	//
	var curr_stage = 0;
	var switchStages = function(JSON){
		cart_content.set('html', JSON.html);
		
		curr_stage = JSON.stage;
		
		cart_content.getElements('input[type=checkbox]').makeCheckbox();
		
		$$('.stages .smallbutton').removeClass('active').addClass('disabled');
		
		$('order_level').set('text', JSON.title)
		
		cart.removeClass('stage0').removeClass('stage1').removeClass('stage2').removeClass('stage3').removeClass('stage4');
		cart.addClass('stage'+JSON.stage);
		
		if(stage_btn = $('stage'+JSON.stage)){
			stage_btn.removeClass('disabled');

			if(stage_btn.getPrevious('.smallbutton'))
				stage_btn.getAllPrevious('.smallbutton').removeClass('disabled').addClass('active');
		}
		
		
		
		set_total_price(JSON);
		
		
		
		cart_content.getElements('input.empty').emptyInput();
		cart_content.getElements('input.hint').hintInput();
		
		if(JSON.stage == 0){
			$$('#addit_content a.addcart').addClass('disabled');
		}
		if(JSON.stage == 1){
			
			//Выбранная пицца
			get_pizzas_table();
			
			
			cart_content.getElements('.select img').addEvent('click', function(e){
				
				this.get('rel').toInt();
				
				quantRequest.send('gid='+this.get('rel')+'&m='+this.hasClass('minus'));
				
			});
			
		}
		else if(JSON.stage == 2){
			
			if(cart_content.getElement('.address_select')){
				cart_content.getElement('.address_select').addEvents({
				
					'change': function(){
						var selected = this.getSelected();
				
						if(selected)
							this.getNext('i').set('text', selected.get('title'));
					},
					'keyup': function(){
						this.fireEvent('change');
					}
				
				
				});
			}
		}
		
		if(JSON.stage == 3 || JSON.stage == 2){
			voprosikEvent(cart_content.getElements('.voprosik') );
		}
		
		if(JSON.stage == 4){
			if(popupFxs['/history']){
				popupFxs['/history'].popup.destroy();
				popupFxs['/history'] = false;
			}
		}
		
		
		if(JSON.stage == 2 || JSON.stage == 3){
			send_order_form = false;
			
			send_order_form = cart_content.getElement('form').removeEvents().addEvents({
				'success': function(res){
					switchStages(res);
				}

			}).checkSubmitEvent(true, true)
		}
	}
	
	var send_order_form = false;
	//Обновить корзину
	var cartRequest = new Request.JSON({
		'headers': {'X-Request': 'JSON'},
		'url': '/get/cart',
		'method': 'get',
		'onRequest': function(){
			order_loader.addClass('loading');
		},
		'onComplete': function(){
			order_loader.removeClass('loading');
		},
		'onSuccess': function(JSON){
			
			switchStages(JSON);
			
		}
	});
	cartRequest.send();
	
	
	
	$$('.stages .smallbutton').addEvent('click', function(){
		if(!(id = this.get('id')) || this.hasClass('disabled') ) return;
		
		var num = id.replace(/^stage/, '').toInt();
		
		if(!this.hasClass('active'))
			num++;
		
		
		if(num == 2 && curr_stage < 2){
			get_pizzas_table();
			
			if(!pizzas_table || pizzas_table.getElements('tr').length < 0){
				
				if(popupFxs['minimalorder']){
					popupFxs['minimalorder'].show();
					return;
				}

				var ok_btn = new Element('div', {
					'text': 'OK',
					'class': 'smallbutton',
					'events': {
						'click': function(){
							popupFxs['minimalorder'].hide();
						}
					}
				});

				popupFxs['minimalorder'] = new Popup('voprosik', '<p class="green" style="width: 480px; font-size: 1.1em" align="center"><br />Минимальный заказ — одна пицца</p>', 'Внимание!');

				ok_btn.inject(popupFxs['minimalorder'].textcontent.set('align', 'center'));
				popupFxs['minimalorder'].show();
				
				return;
			}
		}
		
		
		if(num == 3){
			if(send_order_form)
				send_order_form.sendform();
			return;
			
		}
		else if(num == 4){
			if(send_order_form)
				send_order_form.sendform();
			return;
			
		}
		cartRequest.send('stage='+num);
		
	});
	
	
	
	//Выбор аналога
	var analog_select_event = function(e){
		var selected = this.getSelected();
		var id = selected.get('rel').toString().replace('analog', '');
		
		var parent = this.getParent('div');
		parent.getElement('b.price').set('text', selected.get('value') +" руб.");
		parent.getNext('a.addcart').set('href', "/#addcart/"+id);
	};
	$$('select.analog_select').each(function(select){
		
		
		select.addEvents({
			'keyup': analog_select_event,
			'click': analog_select_event,
			'change': analog_select_event
		});
		select.getElements('option').addEvent('click', analog_select_event.bind(select));
		
	});
	
	
	
	
	//Добавить в корзину
	var addCartRequest = new Request.JSON({
		'headers': {'X-Request': 'JSON'},
		'url': '/get/cart?act=add',
		'method': 'get',
		'onRequest': function(){
			order_loader.addClass('loading');
		},
		'onComplete': function(){
			order_loader.removeClass('loading');
		},
		'onSuccess': function(JSON){
			if(!orderSlide.open)
				orderSlide.toggle();
			
			switchStages(JSON);
			
		}
	});
	
	$$('.good a.addcart').addEvent('click', function(e){
		e.stop();
		
		var href = (this.get('href')) ? this.get('href') : this.get('target');
		
		var gid = href.replace(/^(.*?)addcart\/(\d+)/, '$2');
		
		addCartRequest.send('gid='+gid);
	});
	
	//Дополнительный добавки
	$$('#addit_content a.addcart').addEvent('click', function(e){
		e.stop();
		
		if(!pizzas_table || this.hasClass('disabled') || pizzas_table.getElements('tr').length <= 0) return;
		
		
		var gid =this.get('href').replace(/^(.*?)addcart\/(\d+)/, '$2');
		
		if( pizzas_table.getElements('tr').length == 1 ){
			var to = pizzas_table.getElement('input[type=checkbox]').get('value');
			addCartRequest.send('gid='+gid+'&to='+to+',');
			return;
		}
		
		
		var el = new Element('div', {
			'html': '<br /><span class="small green">Укажите к какой пицце нужно добавить дополнительный ингридиент</span>',
			'align': 'center',
			'styles': {
				'width': '30em'
			}
		});
		
		
		var good_info_table = new Element('table', {
			'border': '0',
			'cellpadding': '10'
		});
		var good_info = this.getParent('tr').clone().inject(good_info_table);
		
		good_info.getElement('.col4').destroy();
		good_info.getElement('.col1').removeClass('green').addClass('red');
		
		
		var button = new Element('div', {
			'class': 'smallbutton',
			'text': 'Добавить',
			'events': {
				'click': function(e){
					e.stop();
					var to = '';
					pizzas_table.getElements('input[type=checkbox]').each(function(check){
						
						if(!check.get('checked')) return;
						
						to = to + check.get('value') + ',';
					});
					
					if(to != '')
						addCartRequest.send('gid='+gid+'&to='+to);
						
					popupFxs['additional'].hide(true);
				}
			}
		});
		
		good_info_table.inject(el);
		pizzas_table.inject(el);
		button.inject(el);
		
		
		popupFxs['additional'] = new Popup('additional', el, ' ');
		popupFxs['additional'].show();
		
	});
	
	
	
	//ZOOM товара
	$$('.good .img a').addEvents({
		'click': function(e){
			e.stop();
		
			var rel = this.get('rel');
		
			if(popupFxs[rel]){
				popupFxs[rel].show();
				return;
			}
		
			var good = this.getParent('.good');
		
			var title = good.getElement('h3').get('text');
		
		
			var content = new Element('div',{
				'class': 'goodzoom',
				'styles': {
					'width': '600px'
				}
			});
			new Element('img', {
				'src': this.get('href')
			}).inject(
			
				new Element('div', {
					'styles': {
						'width': '100%'
					} 
				}).inject(content)
			);
		
			var right = new Element('div', {
				'class': 'info',
				'align': 'right',
				'styles': {
					'float': 'right',
					'font-size': '1.2em',
					'margin-top': '0.2em'
				} 
			}).inject(content);
			
			var weight = good.getElement('.weight');
			var new_weight = weight.clone().addClass('weight').inject(right);
			
			
			new Element('span', {'html': '&nbsp;&nbsp;&nbsp;'}).inject(right);
			good.getElement('.price').clone().addClass('price').inject(right);
			new Element('br').inject(right);
			new Element('br').inject(right);
			
			
			
			/*
			good.getElement('.addcart').clone().addClass('addcart').cloneEvents(good.getElement('.addcart')).addEvent('click', function(e){
				e.stop();
				popupFxs[rel].hide(true);
				popupFxs[rel] = false;
			
			}).addClass('red').inject(right).set('href', good.getElement('.addcart').get('href'));
			*/
			
			good.getElement('.green').clone().setStyles({
				'font-style': 'italic',
				'font-size': '1.1em',
				'line-height': '1.5em'
			}).addClass('green').inject(content);
			
		
			new Element('div', {'class': 'cb'}).inject(content);
			
			new Element('button',{
				'class': 'addcart greenbutton',
				'text': 'Заказать',
				'target': good.getElement('.addcart').get('href'),
				'href': good.getElement('.addcart').get('href'),
				'events': {
					'click': function(e){
						e.stop();
						popupFxs[rel].hide(true);
						popupFxs[rel] = false;
					}
				}
			}).cloneEvents(good.getElement('.addcart')).inject(
				new Element('div', {
					'align': 'center',
					'styles':{'margin-top': '1em'}
				}).inject(content)
			);
			
			
			
			
			//Выбор аналога
			if( new_weight.getElement('select') ){
				
				var selected_option = weight.getElement('select').getSelected().get('rel').toString();
				
				
				var analog_select_window_event = function(e){
					var selected = this.getSelected();
					var id = selected.get('rel').toString().replace('analog', '');

					var parent = this.getParent('div.goodzoom');
					parent.getElement('b.price').set('text', selected.get('value') +" руб.");

					parent.getElement('button.addcart').set({
						'href': "/#addcart/"+id,
						'target': "/#addcart/"+id
					});
				};
				var select = new_weight.getElement('select');
				
				select.getElements('option').each(function(option){
					
					if( option.get('rel').toString() == selected_option )
						option.set('selected', true);
					else
						option.set('selected', false);
					
				});
				
				select.addEvents({
					'keyup': analog_select_window_event,
					'click': analog_select_window_event,
					'change': analog_select_window_event
				}).fireEvent('keyup');
				select.getElements('option').addEvent('click', analog_select_window_event.bind(select));
			}
			
			
			//popupFxs[rel] = new Popup(rel, '<div class="goodzoom" style="width: 600px">' + content.get('html') + '</div>', title);
			popupFxs[rel] = new Popup(rel, content, title);
			popupFxs[rel].title.setStyle('font-size', '2em');
			popupFxs[rel].show();
			
		},
		
		'mouseover': function(){
			this.getParent('.good').addClass('hovered')
		},
		'mouseout': function(){
			this.getParent('.good').removeClass('hovered')
		}
		
	});
	
	$$('.good .img .zoomer').addEvent('click', function(e){
		e.stop();
		
		this.getParent('.img').getElement('a').fireEvent('click', e);
	});
	
	
	
	//Элементы формы
	$$('.smallbutton a').each(function(a){
		
		a.getParent('.smallbutton').addEvent('click', function(e){
			a.fireEvent('click', e);
		});
		
	});
	
	
	//чекбоксы
	$$('input[type=checkbox]').each(function(check){
		check.makeCheckbox();
	});
	
	$$('.allcheckboxes').each(function(allcantainer){
		var all_check = allcantainer.getElement('input[type=checkbox].all');
		
		var allchecks = allcantainer.getElements('input[type=checkbox]');
		
		if(!all_check || !allchecks) return;
		
		
		$$(all_check).addEvent('click', function(){
			var checked = !this.get('checked');
				
			allchecks.each(function(check){
				if(check != this)
					check.set('checked', checked).fireEvent('change');
			}.bind(this));
		});
		
		
		allchecks.each(function(check){
			if(check == all_check) return;
			
			check.addEvent('change', function(){
				
				if(this.get('checked') && all_check.get('checked'))
					all_check.set('checked', false).fireEvent('change');
				
			});
		});
		
	});
	
	
	
	$$('#goods .tags input[type=checkbox]').addEvent('click', function(){
		var this_c = this;
		var display = (this.get('checked')) ? '' : 'none';
		
		if(this.get('value') == 0){
			if(this.get('checked')){
				$$('#goods .tags input[type=checkbox].all').set('checked', true).fireEvent('change');
				$$('#goods .good').setStyle('display', '');
				
				return;
			}
			
		}
		var class_tags = '';
		$$('#goods .tags input[checked]').each(function(chk){
			if(chk.get('value') == 0) return;
			
			if(chk != this_c)
				chk.set('checked', false).fireEvent('change');
			//class_tags = class_tags+'#goods .good.tag'+chk.get('value')+',';
		});
		
		if(this.get('checked'))
			class_tags = '#goods .good.tag'+this.get('value')+',';
		
		class_tags = class_tags.replace(/,$/, '');
		
		$$('#goods .good').setStyle('display', 'none');
		
		if(class_tags != '')
			$$(class_tags).setStyle('display', '');
		else{
			$$('#goods .tags input[type=checkbox].all').set('checked', true).fireEvent('change');
			$$('#goods .good').setStyle('display', '');
		}
	});
	
});




var Popup = new Class({
	
	Implements: Options,

	options: {
		'popup': false,
		'fx': false,
		'content': false,
		'full_size': {
			'width': false,
			'height': false
		}
	},

	initialize: function(id, content, title, options){
		this.setOptions(options);
		
		this.popupscontainer = $('popupscontainer');
		
		this.not_alligned = (Browser.Engine.trident && Browser.Engine.version <= 5 && !(/MSIE 8/i.test( navigator.appVersion)) );
		
		
/*
		this.popup = this.options.popup;
		this.fx = this.options.fx;
		this.content = this.options.content;
		this.full_size = this.options.full_size;
		
		
*/
		this.create(id, content, title);
		
		this.fx = new Fx.Morph(this.content, {duration: ( (this.not_alligned) ? 0 : 300) });
		this.hidden = true;
	},
	
	show: function(afterload){
		$('curtain').fade(0.3);
		if(this.popup.getStyle('display') == 'none' ){
			this.popup.setStyle('display', 'block');
		}	
		
		this.hidden = false;
		
		if(afterload){
			var oldsizes = this.full_size;
			
			this.getFullSize();
			
			this.content.setStyles(
				oldsizes
			);
			
		}
		
		this.popup.setStyle('margin-top', window.getScroll().y+'px');
		
		this.fx.start(
			this.full_size
		).chain(function(){ this.content.setStyles({'width':'', 'height':''}); }.bind(this) );
	
	},
	
	hide: function(del){
		$('curtain').fade(0);
		this.fx.start({
		    'height': 1,
		    'width': 1
		}).chain(function(){
			this.popup.setStyle('display', 'none');
			if(del)
				this.popup.destroy();
		}.bind(this));
		this.hidden = true;
	},
	
	create: function(id, content, title){
	
		//var html = 	'<div class="framed" style="display: block;"><div class="f_tt"></div><div class="f_r"><div class="f_rr"></div><div class="f_b"><div class="f_bb"><div></div></div><div class="f_l"><div class="f_ll"><div></div></div><div class="f_c"><div class="close_btn green">закрыть <span class="red">×</span></div><div class="header"></div><div class="textcontent">'+content+'</div></div></div></div></div></div>';
		
		var textcontent = ($type(content) == 'string') ? content : '';
		
		var html = 	'<div class="framed r-border-shape"><div class="tb"><div class="cn l"></div><div class="cn r"></div></div><div class="content"><div class="close_btn red sans-serif">закрыть ×</div><h1 class="header">'+title+'</h1><div class="textcontent">'+textcontent+'</div></div><div class="bb"><div class="cn l"></div><div class="cn r"></div></div></div>';
		
/*		
		var html = 	'
		<div class="framed r-border-shape">
			<div class="tb">
				<div class="cn l"></div>
				<div class="cn r"></div>
			</div>
			
			<div class="content">
				<div class="close_btn red sans-serif">закрыть ×</div>
				<h1 class="header">География доставки</h1>
				<div class="textcontent">'+content+'</div>
			</div>
			
			<div class="bb">
				<div class="cn l"></div>
				<div class="cn r"></div>
			</div>
		</div>
		';

*/		
		
		var popup = new Element('div',{
			'id': id,
			'class': 'textpopup align_center_to_right',
			'html': html,
			'events': {
				'click': function(e){
					e.stop();
				}
			}
		}).inject(this.popupscontainer);
		
		this.popup = popup;
		
		this.framed = popup.getElement('.framed');
		
		this.content = this.popup.getElement('.content');
		this.title = this.popup.getElement('.header');
		
		this.textcontent = this.popup.getElement('.textcontent');
		
		if($type(content) == 'element')
			content.inject(this.textcontent);
		
		this.getFullSize();
		
		
		this.content.setStyle('overflow', 'hidden');
		
		this.popup.getElement('.close_btn').addEvent('click', function(e){
			e.stop();
			this.hide();
		}.bind(this));
		
		this.content.setStyles({
			'width': '1px',
			'height': '1px'
		});
		this.popup.setStyle('display', 'none');
		
		return popup;
	},
	
	setHtml: function(html){
		this.textcontent.set('html', html);
		//this.getFullSize();
		return this;
	},
	
	injectEl: function(el, pos){
		el.inject(this.textcontent, pos);
		
		this.content.setStyles({
			'width': 'auto',
			'height': 'auto'
		});
		
		
		this.getFullSize();
		
		if(this.popup.getStyle('display') == 'none'){
			this.content.setStyles({
				'width': '1px',
				'height': '1px'
			});
		}
		
		return this;
	},
	
	getFullSize: function(){
		this.full_size = {
			'width': this.content.getStyle('width'),
			'height': this.content.getStyle('height')
		}
		
		if(this.not_alligned){
			this.framed.setStyle('width', this.textcontent.getWidth() + 32 +'px');
		}
		
		return this.full_size;
	}
	
});



Native.implement([Element], {
	
	'makeCheckbox': function(){
		var check = this;
		
		var img = new Element('img', {
			'src': '/spics/blank.gif',
			'class': 'checkbox '+check.get('checked'),
			'align': 'bottom'
		}).inject(check, 'after');
		
		check.setStyle('display', 'none');
		
		check.addEvent('change', function(){
			img.addClass( this.get('checked') ).removeClass( !this.get('checked') );
		});
		
		img.addEvent('click', function(e){
			e.stop();
			check.set('checked', !check.get('checked'));
			check.fireEvent('click');
			check.fireEvent('change');
		});
		
		var label = check.getParent('label')
		if(label)
			label.addEvent('click', function(e){ img.fireEvent('click', e); });
		
	},
	
	'emptyInput': function(){
		var el = this;
		if($type(el) != 'element' || el.get('tag') != 'input' || !el.hasClass('empty') ) return true;
	
		val = el.get('value');
		var type = el.get('type');
		
		
		
		el.addEvents({
			'blur': function(){
				if(this.get('value') != '') return;
				
				this.set('value', val).addClass('empty');
				if(type == 'password' && !Browser.Engine.trident)
					this.set('type', 'text');
			},
			'focus': function(){
				if(this.get('value') == val)
					this.set('value', '').removeClass('empty');
					
				if(type == 'password' && !Browser.Engine.trident)
					this.set('type', type);
			}
			
		});
		
		var form = el.getParent('form');
		if(form)
			form.addEvent('submit', function(){
				if(el.get('value') == val)
					el.set('value', '').removeClass('empty');
			});
	},
	
	'hintInput': function(){
		var el = this;
		if($type(el) != 'element' || el.get('tag') != 'input' || !el.hasClass('hint') ) return true;

		var val = el.get('placeholder');
		var type = el.get('type');
		
		if(el.get('value') == ''){
			el.addClass('empty').set('value', val);
			if(type == 'password' && !Browser.Engine.trident)
				this.set('type', 'text');
		}
		
		el.addEvents({
			'blur': function(){
				if(this.get('value') != '') return;
				
				this.set('value', val).addClass('empty');
				if(type == 'password' && !Browser.Engine.trident)
					this.set('type', 'text');
			},
			'focus': function(){
				if(this.get('value') == val)
					this.set('value', '').removeClass('empty');
					
				if(type == 'password')
					this.set('type', type);
			}
			
		});
		
		var form = el.getParent('form');
		if(form)
			form.addEvent('submit', function(){
				if(el.get('value') == val)
					el.set('value', '').removeClass('empty');
			});
	}
	
	
});


function formatDate(timediff, date){
	if(!timediff)
		return date;
	
	var res =/(\d+):(\d+):(\d+)/.exec(timediff);
	var hours = res[1].toInt();
	var minutes = res[2].toInt();
	
	var result;
	if(hours > 72){
		var res =/(\d{4})-(\d{2})-(\d{2})/.exec(date);
		
		return res[3]+'.'+res[2]+'.'+res[1];
	}
	else if(hours > 23){
		var days = (hours / 24).round();
		
		result = days + ' ' + ruWordByInt(days, new Array('день', 'дня', 'дней') );
	}
	else if(hours <= 0){
		if(minutes == 0)
			return 'меньше минуты';
		else
			result = minutes + ' ' + ruWordByInt(minutes, new Array('минута', 'минуты', 'минут') );
	}
	else
		result = hours + ' ' + ruWordByInt(hours, new Array('час', 'часа', 'часов') );
	
	return result + ' назад';
}

function ruWordByInt(int, words){
	var res =/\d$/.exec(int);
	var e = res[0];
	
	if(e == '1')
		word = words[0];
	else if(e == '2' || e == '3' || e == '4')
		word = words[1];
	else
		word = words[2];
	if( int.toInt() > 9 &&  int.toInt() < 20 )
		word = words[2];
	
	return word;
}

function checkNNData(){
	var f = true;
	$$('.NN').each(function(star){
		if(f && star.get('value') == '')
			f = false;
	});
	return f;
}

function starSelect(){
	
	var cont = new Element('div').injectAfter($('star_sel'));
	
	//var value = new Element('span');
	
	$$('#star_sel option').each(function(option){
		
		if(option.get('value').toInt() == 0)
			return true;
		//console.log(option.get('html'));
		
		new Element('span', {
			'class': 'ssel',
			'text': '*',
			'title': option.get('html'),
			'events': {
				'mouseover': function(){
					var s = false;
					var this_c = this;
					$$('.ssel').removeClass('sel').removeClass('unsel').each(function(ssel){
						if(ssel == this_c){
							s = true;
							return false;
						}
						else if(s)
							ssel.addClass('unsel');
						else
							ssel.addClass('sel');
					});
				},
				'mouseout': function(){
					$$('.ssel').removeClass('sel').removeClass('unsel');
				},
				'click': function(e){
					e.stop();
					this.addClass('sel');
					$$('.ssel').removeClass('curr');
					$$('.sel').addClass('curr');
					$$('#star_sel option').set('selected', false);
					option.set('selected', true);
					
					//value.set('html', this.get('title') );
				}
			}
		}).inject(cont);
		/*
		new Element('img', {
			'class': 'ssel',
			'src': /spics/blank.gif',
			'width': 20,
			'height': 17,
			'title': option.get('html'),
			'events': {
				'mouseover': function(){
					var s = false;
					var this_c = this;
					$$('.ssel').removeClass('sel').removeClass('unsel').each(function(ssel){
						if(ssel == this_c){
							s = true;
							return false;
						}
						else if(s)
							ssel.addClass('unsel');
						else
							ssel.addClass('sel');
					});
				},
				'mouseout': function(){
					$$('.ssel').removeClass('sel').removeClass('unsel');
				},
				'click': function(e){
					e.stop();
					this.addClass('sel');
					$$('.ssel').removeClass('curr');
					$$('.sel').addClass('curr');
					$$('#star_sel option').set('selected', false);
					option.set('selected', true);
					
					//value.set('html', this.get('title') );
				}
			}
		}).inject(cont);
		*/
	});
	//value.inject(cont);
	$('star_sel').setStyle('display', 'none');
	
}




