function FoodItem() {}
FoodItem.prototype = {
	init: function(container, chapter, index) {
		this.container = container;
		this.chapter = chapter;
		this.index = index;
		this.ingredients = as.$$('td.what p', container).innerHTML.toUpperCase();
		this.price = parseInt(as.$$('td.add a.add', container).getAttribute('rel'));

		return this;
	}
}

function FoodChapter() {}
FoodChapter.prototype = {
	init: function(container, index) {
		this.container = container;
		this.index = index;
		this.itemList = [];

		return this;
	}
}

function FoodList() {}
FoodList.prototype = {
	init: function() {
		this.chapterList = [];
		this.chapters = as.w("table.foods-list tr.header");
		this.items = as.w("table.foods-list td.what");
		this.selectBox = as.$$('select#fftype');

		this.addOption(this.selectBox, 'Все', -1);
		this.chapters.each(as.bind(function(index) {
			var container = this.chapters.set[index];
			var chapter = container.getAttribute('rel');
			this.addOption(this.selectBox, as.$$('h3', container).innerHTML, chapter);
			this.chapterList[chapter] = new FoodChapter().init(container, chapter);
		}, this));

		this.items.each(as.bind(function(index) {
			var container = this.items.set[index].parentNode;
			var chapter = container.getAttribute('rel');
			this.chapterList[chapter].itemList[index] = new FoodItem().init(container, chapter, index);
		}, this));

		return this;
	},
	addOption: function(list, text, value) {
		var oOption = document.createElement("option");
		oOption.appendChild(document.createTextNode(text));
		oOption.setAttribute("value", value);
		list.appendChild(oOption);
	}
}

function initFoodIList() {
	var findForm = as.$$('form#foodfilter');
	if( !findForm )
		return;
	var foodList = new FoodList().init();

	as.e.click(as.$$('input#ffclear'), function() {
		this.items.each(function(index) {
			this.parentNode.style.display = '';
		});
		this.chapters.each(function(index) {
			this.style.display = '';
		});
	}, foodList);

	as.e.click(as.$$('input#fffind'), function() {
		var chapter = this.selectBox.options[this.selectBox.selectedIndex].value;
		var min_price = as.$$('input#ffpricefrom').value;
		var max_price = as.$$('input#ffpriceto').value;
		var search = as.$$('input#ffcontent').value.toUpperCase();
		var words = search.replace(/\s+/, ' ').split(' ');
		for (var c in this.chapterList) {
			var items = this.chapterList[c].itemList;
			var chaptervisible = false;
			for (var i in items) {
				var chapter_cond = (chapter < 0 || items[i].chapter == chapter);
				var min_price_cond = (min_price == '' ? true : items[i].price >= parseInt(min_price));
				var max_price_cond = (max_price == '' ? true : items[i].price <= parseInt(max_price));
				var search_cond = (search == '' || words.length < 1);
				if (!search_cond) {
					var ingredients = items[i].ingredients;
					for (var w in words) {
						if (ingredients.indexOf(words[w]) >= 0) {
							search_cond = true;
							break;
						}
					}
				}
				//console.debug([chapter_cond, min_price_cond, max_price_cond, search_cond, words]);
				var display = (chapter_cond && min_price_cond && max_price_cond && search_cond ? '' : 'none');
				if( display == '' ) {
					chaptervisible = true;
				}
				items[i].container.style.display = display;
			}
			this.chapters.set[c].style.display = (chaptervisible ? '' : 'none');
		}
	}, foodList);
}
as.ready(initFoodIList);

function MetroSelect() {}
MetroSelect.prototype = {
	init: function(s) {
		this.s = s;
		this.s.value = 'к любой станции метро';
		this.sel = as.$$('div.what-where-when select.metro');
		this.sel.style.display = 'none';
		this.sel.name = '';
		this.s.style.display = 'inline';
		this.inputHidden = document.createElement('input');
		this.inputHidden.type = 'hidden';
		this.inputHidden.className = 'metro-hidden';
		this.inputHidden.name = 'metro';
		as.$$('div.what-where-when form').appendChild(this.inputHidden);

		this.addEventListeners();
	},
	addEventListeners: function() {
		as.e.click(this.s,this.tryShowPopup,this);
	},
	tryShowPopup: function(e) {
		e.preventDefault();
		this.s.blur();
		if (!this.popup){
			this.createPopup();
		}
	},

	tryShowPopup: function(e) {
		e.preventDefault();

		if (!this.popup){
			this.createPopup();
		}
	},
	createPopup: function() {
		this.popup = as.append("<div class='metro-popup as-popup'><a href='#' class='close'>закрыть</a><div class='overlay'></div><div class='popup-content'><h3>Выберите станцию метро</h3></div></div>",document.body);
		var popupContent = as.$$("div.popup-content",this.popup);

		as.w("optgroup",this.s.parentNode).each(function() {
			var list = as.append("<ul class='" + this.className + "'></ul>",popupContent);
			as.w("option",this).each(function() {
				var item = as.append("<li><a href='#' rel="+this.value+">"+this.innerHTML+"</a></li>",list);
				item.metroOption = this;

				if (this.selected) {
					item.className += " selected";
				}
			});
		});

		var close = as.$$("a.close",this.popup);
		as.e.click(close,this.closePopup,this);
		as.e.click(popupContent,this.trySelectOption,this);

		this.showPopup();
	},
	showPopup: function() {
		this.popup.style.display = "block";
		var sWhere = as.where(this.s);
		as.style(this.popup,{
			top: sWhere.top + sWhere.height + 10 + "px",
			left: sWhere.left + sWhere.width/2 - this.popup.offsetWidth/2 + "px"
		});
	},
	closePopup: function(e) {
		e.preventDefault();
		as.remove(this.popup);
		this.popup = null;
	},
	trySelectOption: function(e) {
		var item = as.parent(e.target,"li");
		if (item) {
			this.closePopup(e);
			item.metroOption.selected = true;
			this.s.value = as.$$('a',item).innerHTML;
			as.$$('input.metro-hidden',this.s.parentNode).value = as.$$('a',item).rel;
		}
	}
}

function TimeSelect() {}
TimeSelect.prototype = {
	init: function(i) {
		this.i = i;
		this.addEventListeners();
	},
	addEventListeners: function() {
		as.e.focus(this.i,this.createPopup,this);
	},
	createPopup: function() {
		if (this.popup) return;
		this.popup = as.append("<div class='time-popup as-popup'><a href='#' class='close'>закрыть</a><div class='overlay'></div><div class='popup-content'><h3>Время доставки</h3></div></div>",document.body);
		var close = as.$$("a.close",this.popup);
		as.e.click(close,this.closePopup,this);
		var popupContent = as.$$("div.popup-content",this.popup);
		popupContent.innerHTML += "<div class='time-clock'><ul class='before'></ul><ul class='after'></ul></div><div class='switcher'><a class='before switcher' href='#'>до полудня</a> | <a class='after switcher' href='#'>после полудня</a></div>";

		var ulBefore = as.$$("ul.before",popupContent);
		var ulAfter = as.$$("ul.after",popupContent);
		for (var i=1;i<=12;i++) {
			as.append("<li class='hour" + i + "'><a href='#'>" + i + "</a></li>",ulBefore);
		}
		for (var i=13;i<=24;i++) {
			as.append("<li class='hour" + i + "'><a href='#'>" + i + "</a></li>",ulAfter);
		}
		as.w("div.switcher a",popupContent).click(this.switchTime,this);
		this.switchTime(null,0);

		as.w("div.time-clock a",popupContent).click(this.setTime,this);
		this.showPopup();
	},
	switchTime: function(e,index) {
		e && e.preventDefault();
		as.w("div.switcher a",this.popup).each(function(i) {
			this.className = this.className.replace(/\bactive\b/gi,"");
			if (i == index) {
				this.className += " active";
			}
		});
		as.w("div.time-clock ul",this.popup).each(function(i) {
			this.style.display = "none";
			if (i == index) {
				this.style.display = "block";
			}
		});
	},
	setTime: function(e) {
		e.preventDefault();
		var value = e.target.innerHTML.length > 1 ? e.target.innerHTML : "" + "0" + e.target.innerHTML;
		value += ":00";
		this.i.value = value;
		this.closePopup();
	},
	showPopup: function() {
		this.popup.style.display = "block";
		var sWhere = as.where(this.i);
		as.style(this.popup,{
			top: sWhere.top + sWhere.height + 10 + "px",
			left: sWhere.left + sWhere.width/2 - this.popup.offsetWidth/2 + "px"
		});
	},
	closePopup: function(e) {
		e && e.preventDefault();
		as.remove(this.popup);
		this.popup = null;
	}
}

function initFood() {
	as.w("div.what-where-when input.metro").each(function() {
		new MetroSelect().init(this);
	});


	as.w("div.what-where-when input.time").each(function() {
		new TimeSelect().init(this);
	});
}
as.ready(initFood);


function foodCounter(){}
foodCounter.prototype = {
	init: function(){
		this.addLinks = as.$('table.foods-list td.add a.add');
		if (!this.addLinks) return;
		this.orderContainer = as.$$('div.order-counter');
		this.addCounter = true;
		this.tableOrderList = '';
		this.itemNumberS = as.$('div.itemNumber');
		this.foodsBody = as.$$('table.foods tbody');
		this.foodsInput = as.$('table.foods input');
		this.costSum = 0;

		for (var i=0;i<this.foodsInput.length;i++){
			this.foodsInput[i].value = 1;
		}

		this.showTextarea();

		this.setValuesCookie();
	},
	setValuesCookie: function(){
		var itemNumbers = [],itemValues = [],itemNumberNumber = as.$('table.foods div.itemNumber input');


		for (var i=0;i<this.addLinks.length;i++){
			itemNumbers[i] = this.getCookie('item'+this.addLinks[i].id);
			itemValues[i] = this.getCookie('value'+this.addLinks[i].id);
		}
		for (var i=0;i<itemNumbers.length;i++){
			if (itemNumbers[i] && (itemNumbers[i] != 'null')){
				itemNumberNumber[i].value = itemValues[i];
				this.addLinkClick(this.addLinks[i],i,itemValues[i]);
			}
		}

	},
	setCookie: function(name, value, expiredays, path, domain, secure) {
	   if (expiredays) {
		  var exdate=new Date();
		  exdate.setDate(exdate.getDate()+expiredays);
		  var expires = exdate.toGMTString();
	   }
	   document.cookie = name + "=" + escape(value) +
	   ((expiredays) ? "; expires=" + expires : "") +
	   ((path) ? "; path=" + path : "") +
	   ((domain) ? "; domain=" + domain : "") +
	   ((secure) ? "; secure" : "");
	},
	getCookie: function(name) {
	   var cookie = " " + document.cookie;
	   var search = " " + name + "=";
	   var setStr = null;
	   var offset = 0;
	   var end = 0;
	   if (cookie.length > 0) {
		  offset = cookie.indexOf(search);
		  if (offset != -1) {
			 offset += search.length;
			 end = cookie.indexOf(";", offset)
			 if (end == -1) {
				end = cookie.length;
			 }
			 setStr = unescape(cookie.substring(offset, end));
		  }
	   }
	   return setStr;
	},
	deleteCookie: function(name, path, domain) {
	   this.setCookie(name, null, 0, path, domain);
	   return true;
	},
	showTextarea: function(){
		var self = this, del = as.$('table.foods a.del');

		for (var i=0;i<this.addLinks.length;i++){
			(function(i){
				self.addLinks[i].onclick = function(e){
					self.stopEvent(e);
					self.addLinkClick(this,i);
				}
			})(i)
		}
	},
	addLinkClick: function(thisLink,i,itemValue){
		this.itemNumber = as.$$('div.itemNumber',thisLink.parentNode);
		this.itemNumber.style.display = 'block';
		this.itemNumberNumber = as.$$('div.itemNumber input',thisLink.parentNode);
		this.itemDelButton = as.$$('div.itemNumber a.del',thisLink.parentNode);

		this.itemNumberNumber.className = this.itemNumberNumber.className.replace(/\bitem\d\b/gi,'');
		this.itemDelButton.className = this.itemDelButton.className.replace(/\bitem\d\b/gi,'');
		thisLink.parentNode.parentNode.id = thisLink.parentNode.parentNode.className.replace(/\bitem\d\b/gi,'');
		this.itemNumberNumber.className += ' item'+i;
		thisLink.parentNode.parentNode.id += 'item'+i;
		this.itemDelButton.className += ' item'+i;
		thisLink.className += ' hidden';

		this.createOrder(thisLink.parentNode.parentNode.innerHTML);

		if (itemValue) {
			this.itemNumberNumber.value = itemValue;

			this.setCookie('item'+thisLink.id,i,'','/');
			this.setCookie('value'+thisLink.id,itemValue,'','/');
		}
		else{
			this.setCookie('item'+thisLink.id,i,'','/');
			this.setCookie('value'+thisLink.id,this.itemNumberNumber.value,'','/');
		}


		var orderDel = as.$('a.del',this.tableOrderBody),delLinkMenu = as.$('a.del',this.foodsBody),delLinkOrder = as.$('a.del',this.tableOrderBody);


		this.initItemNumbers(i);

		this.deleteItem(thisLink,i,delLinkOrder);
		this.deleteItem(thisLink,i,delLinkMenu,orderDel);
		this.measureCost();

		//alert(document.cookie);
	},
	createOrder: function(itemHTML){
		this.orderFoodsList = as.$$('div.orderFoodsList');
		this.tableOrderListTr = '<tr>'+itemHTML+'</tr>';
		this.tableOrderList += this.tableOrderListTr;
		this.orderFoodsList.innerHTML = '<table class="foods-list">'+this.tableOrderList+'</table>';
		this.orderFoodsList.innerHTML += '<p class="count">Заказ на <span></span><a href="#" class="escape">очистить</a></p>';
		this.tableOrderBody = as.$$('div.order-counter table.foods-list tbody');
		var tr = as.$('div.orderFoodsList table tr');
		for (var i=0;i<tr.length;i++){
			tr[i].className = tr[i].className.replace(/\blarge\b/gi,'');
		}

		this.showCloseWrap = as.$$('div.order-counter span.wrap');
		this.costPlace = as.$$('div.orderFoodsList p.count span');

		this.addCounter = false;
		this.escapeActions();
		this.wrapActions();
	},
	wrapActions: function(){
		var self = this;
		this.showCloseWrap.innerHTML = '<a href="#" class="unwrap">развернуть список</a><a href="#" class="wrap" style="display:none;">свернуть список</a>';
		this.unwrapper = as.$$('div.order-counter a.unwrap');
		this.wrapper = as.$$('div.order-counter a.wrap');
		this.unwrapper.onclick = function(e){
			self.stopEvent(e);
			this.style.display = 'none';
			self.wrapper.style.display = 'inline';
			as.$$('div.orderFoodsList table').className += ' large';
		}
		this.wrapper.onclick = function(e){
			self.stopEvent(e);
			this.style.display = 'none';
			self.unwrapper.style.display = 'inline';
			as.$$('div.orderFoodsList table').className = as.$$('div.orderFoodsList table').className.replace(/\blarge\b/gi,'');
		}
	},
	escapeActions: function(tableOrderList){
		var escaper = as.$$('a.escape',this.orderFoodsList),self = this;
		escaper.onclick = function(e){
			self.stopEvent(e);
			self.allDelete();
		}
	},
	allDelete: function(){
		this.orderFoodsList.innerHTML = '';
		for (var j=0;j<this.itemNumberS.length;j++){
			this.itemNumberS[j].style.display = 'none';
			this.addLinks[j].className = this.addLinks[j].className.replace(/\bhidden\b/gi,'');
		}
		this.tableOrderList = '';
		for (var i=0;i<this.menuNumberFields.length;i++){
			this.menuNumberFields[i].value = 1;
		}
		this.costSum = 0;
		this.showCloseWrap.innerHTML = 'добавляйте блюда в список для удобства заказа по телефону';

		for (var i=0;i<this.addLinks.length;i++){
			this.deleteCookie('item'+this.addLinks[i].id,'/');
			this.deleteCookie('value'+this.addLinks[i].id,'/');
		}

	},
	deleteItem: function(thisLink,i,delLink,orderDel){
		var self = this,cost = 0;
		for (var i=0;i<delLink.length;i++){
			(function(i){
				delLink[i].onclick = function(e){
					self.stopEvent(e);

					self.deleteCookie('item'+as.$$('a.add',this.parentNode.parentNode).id,'/');
					self.deleteCookie('value'+as.$$('a.add',this.parentNode.parentNode).id,'/');

					self.deleteActions(this,this.className.replace(/\D/gi,''),'',orderDel);
				}
			})(i)
		}
	},
	deleteActions: function(thisLink,i,delLink,orderDel){
		if (this.tableOrderBody.childNodes.length == 1){
			this.allDelete();
		}
		else {
			var deletenumber = i;
			this.itemNumberS[deletenumber].style.display = 'none';
			this.addLinks[deletenumber].className = this.addLinks[deletenumber].className.replace(/\bhidden\b/gi,'');
			if (orderDel){
				for (var j=0;j<orderDel.length;j++){
					if (thisLink.className.match(orderDel[j].className)){
						this.tableOrderBody.removeChild(orderDel[j].parentNode.parentNode.parentNode);
					}
				}
			}
			else this.tableOrderBody.removeChild(thisLink.parentNode.parentNode.parentNode);
			this.tableOrderList =  as.$$('div.orderFoodsList table tbody').innerHTML;
			this.measureCost();
		}
		this.initItemNumbers();
	},
	initItemNumbers: function(){
		var self = this;
		this.menuNumberFields = as.$('table.foods input');
		this.orderNumberFields = as.$('div.orderFoodsList table input');
		this.getValue();
		for (var i=0;i<this.menuNumberFields.length;i++){
			(function(i){
				self.menuNumberFields[i].onkeyup = function(e){
					self.stopEvent(e);
					for (var j=0;j<self.orderNumberFields.length;j++){
						if (self.orderNumberFields[j].className.replace(/\D/gi,'') == (this.className.replace(/\D/gi,''))){
							if (typeof(this.value) != 'number'){
								this.value = this.value.replace(/\D/gi,'');
							}
							self.orderNumberFields[j].value = this.value;
							self.measureCost();
						}
					}
					self.setCookie('value'+as.$$('a.add',this.parentNode.parentNode).id,this.value,'','/');
					self.setCookie('item'+as.$$('a.add',this.parentNode.parentNode).id,this.value,'','/');
				}
			})(i)
		}
		for (var i=0;i<this.orderNumberFields.length;i++){
			(function(i){
				self.orderNumberFields[i].onkeyup = function(e){
					for (var j=0;j<self.menuNumberFields.length;j++){
						if (this.className.replace(/\D/gi,'') == (self.menuNumberFields[j].className.replace(/\D/gi,''))){
							if (typeof(this.value) != 'number'){
								this.value = this.value.replace(/\D/gi,'');
							}
							self.menuNumberFields[j].value = this.value;
							self.measureCost();
						}
					}
					self.setCookie('value'+as.$$('a.add',this.parentNode.parentNode).id,this.value,'','/');
					self.setCookie('item'+as.$$('a.add',this.parentNode.parentNode).id,this.value,'','/');
				}
			})(i)
		}
	},
	getValue: function(){
		for (var i=0;i<this.menuNumberFields.length;i++){
			for (var j=0;j<this.orderNumberFields.length;j++){
				if (this.menuNumberFields[i].className.match(this.orderNumberFields[j].className)){
					this.orderNumberFields[j].value = this.menuNumberFields[i].value;
				}
			}
		}
	},
	measureCost: function(cost,multiple){
		var td = as.$('div.orderFoodsList table td.add'),sum = 0,lastNum = 0;
		for (var i=0;i<td.length;i++){
			if (as.$$('input',td[i]).value == ''){
				sum += (parseInt(as.$$('a.add',td[i]).rel)*0);
			}
			else sum += (parseInt(as.$$('a.add',td[i]).rel)*parseInt(as.$$('input',td[i]).value));
		}
		sum = sum.toString();
		lastNum = sum[sum.length-1];
		switch (lastNum){
			case '1':
			this.costPlace.innerHTML = sum + ' рубль';
			break;

			case '2':
			this.costPlace.innerHTML = sum + ' рубля';
			break;

			case '3':
			this.costPlace.innerHTML = sum + ' рубля';
			break;

			case '4':
			this.costPlace.innerHTML = sum + ' рубля';
			break;

			default:
			this.costPlace.innerHTML = sum + ' рублей';
		}

	},
	stopEvent: function(e){
		var event = e || window.event;
		event.preventDefault ? event.preventDefault() : event.returnValue = false;
	}
}
function initFoodCounter() {
	new foodCounter().init();
}
as.ready(initFoodCounter);
