$(document).ready(function(){    
    $("a.discountsrest").hover(function(){
        $(this).parent().parent().addClass("disc_active");
    }, function(){
        $(this).parent().parent().removeClass("disc_active");
    })
})
function load(host, url, block) {

	proxy = host.split("/")
	for (var i in proxy) {
		if (proxy[i].search("proxy") === 0) {
			host = host.replace(proxy[i], "proxy" + Math.floor(Math.random()*10000000))
		}
	}

	obj = document.getElementById(block)
	if (!obj) return false

	rnd = "rnd=" + Math.floor(Math.random() * 100000)
	if (url.split("?", 1) == url) {
		url += "?" + rnd
	} else {
		url += "&" + rnd
	}

	obj.innerHTML = '<img src="' + host + 'img/loader.gif" class="loader" width="70" height="10" border="0" alt="" />'
	$('#' + block).load(host + encodeURI(url))

}

function load_block(host, url, block) {

	proxy = host.split("/")
	for (var i in proxy) {
		if (proxy[i].search("proxy") === 0) {
			host = host.replace(proxy[i], "proxy" + Math.floor(Math.random()*10000000))
		}
	}

	rnd = "rnd=" + Math.floor(Math.random() * 100000)
	if (url.split("?", 1) == url) {
		url += "?" + rnd
	} else {
		url += "&" + rnd
	}

	block.innerHTML = '<img src="' + host + 'img/loader.gif" class="loader" width="70" height="10" border="0" alt="" />'
	$(block).load(host + encodeURI(url))

}

function loadWithoutLoader(host, url, block) {

	proxy = host.split("/")
	for (var i in proxy) {
		if (proxy[i].search("proxy") === 0) {
			host = host.replace(proxy[i], "proxy" + Math.floor(Math.random()*10000000))
		}
	}

	rnd = "rnd=" + Math.floor(Math.random() * 100000)
	if (url.split("?", 1) == url) {
		url += "?" + rnd
	} else {
		url += "&" + rnd
	}

	obj = document.getElementById(block)
	if (!obj) return false

	$('#' + block).load(host + encodeURI(url))

}



function slideToggleCartList(host, url, block, head) {

	obj = document.getElementById(block)
	if (!obj) return false

	head = document.getElementById(head)
	if (!head) return false
	head = head.parentNode

	if (obj.style.display == "block") {
		head.style.backgroundColor = "#FFFFFF"
	} else {
		head.style.backgroundColor = "transparent"
		obj.innerHTML = '<img src="' + host + 'img/loader.gif" class="loader" width="70" height="10" border="0" alt="" />'
	}

	$('#' + block).slideToggle()
	$('#' + block).load(host + url)

	return false

}



function deleteItemCart(host, rid, mid) {

	obj = document.getElementById('cart_list')
	if (!obj) return false

	obj = document.getElementById('cart_head')
	if (!obj) return false

	load(host, "cart-list.html?act=del&rid=" + rid + "&mid=" + mid, 'cart_list')

	return false

}

function delItemCart(host, rid, mid, mname) {
	$.prompt('<h3>Блюдо &laquo;' + mname + '&raquo; будет <strong style="color:#F00;">удалено</strong></h3>', {
		callback: function(returnvalue) {
			returnvalue -= 0
			if (returnvalue) {
				document.location.href = host + "cart-list.html?act=del&rid=" + rid + "&mid=" + mid + "&rnd=" + Math.floor(Math.random()*100000)
			}
		},

		buttons: {
			Ok: '1',
			отмена: '0'
		}

	})
}

function delItemCartOrder(host, rid, mid, mname) {
	$.prompt('<h3>Блюдо &laquo;' + mname + '&raquo; будет <strong style="color:#F00;">удалено</strong></h3>', {
		callback: function(returnvalue) {
			returnvalue -= 0
			if (returnvalue) {
				document.location.href = host + "order/actions.html?act=del&rid=" + rid + "&mid=" + mid + "&rnd=" + Math.floor(Math.random()*100000)
			}
		},

		buttons: {
			Ok: '1',
			отмена: '0'
		}

	})
}

function addItemCart(host, rid, mid, redirect, name_rest_encode, name_goods_encode, name_rest, name_goods, price, select) {
	//alert(host + "\n" + rid + "\n" + mid + "\n" + redirect + "\n" + name_goods + "\n" + name_rest + "\n" + price + "\n" + select)
	var oXmlHttp = createXMLHttp()
   	oXmlHttp.open("GET", host + "cart-get.html?rid=" + rid + "&mid=" + mid, true)
   	oXmlHttp.onreadystatechange = function() {

	   	if (oXmlHttp.readyState == 4) {

		    if (oXmlHttp.status == 200) {
				result = oXmlHttp.responseText
				added = 0
				if (result > 0) added++
				if (select) {
					num = num_tov_pr = parseInt(result)
				} else {
					num = num_tov_pr = document.getElementById('count_goods_' + mid).value
				}

				selectpr = '<select style="width: 45px;" onchange="num_tov_pr = this.value;" name="num_tov_pr" id="num_tov_pr">'
				num_tov_pr = 1
				for (i = 1; i <= 20; i++) {
					if (num == i) {
						selectpr += '<option value="' + i + '" selected>' + i + '</option>'
						num_tov_pr = i
					} else {
						selectpr += '<option value="' + i + '">' + i + '</option>'
					}
				}
				selectpr += "</select>"

				if (added) {
					$.prompt('<h2>Это блюдо уже добавлено в корзину</h2><h3>' + name_goods + '</h3><b class="green">' + price + ' грн.</b><br />Изменить количество: ' + selectpr, {
						callback: function(returnvalue) {
							returnvalue -= 0
							if (returnvalue) {
								load(host, 'cart-list.html?act=add&name=' + name_goods_encode + '&rid=' + rid + '&mid=' + mid + '&count=' + num_tov_pr + '&price=' + parseFloat(price) * parseInt(num_tov_pr) + '&rnd=' + Math.floor(Math.random() * 100000), 'cart_list')
							}
						},

						buttons: {
							Ok: '1',
							отмена: '0'
						}

					})

				} else {

					text = ""
					text = '<h3>Уважаемый клиент!</h3><ul><li>Стоимость доставки из каждого ресторана считается отдельно;</li><li>Минимальная стоимость заказа в одном ресторане - 100 грн.</li></ul>';

					$.prompt('<h2>Добавить в корзину и перейти в меню ресторана "' + name_rest + '"?</h2><h3>' + name_goods + '</h3><b class="green">' + price + ' грн.</b><br />Количество: ' + selectpr + text, {
						callback: function(returnvalue) {
							returnvalue -= 0
							if (returnvalue) {
								load(host, 'cart-list.html?act=add&name=' + name_goods_encode + '&rid=' + rid + '&mid=' + mid + '&count=' + num_tov_pr + '&price=' + parseFloat(price) * parseInt(num_tov_pr) + '&rnd=' + Math.floor(Math.random() * 100000), 'cart_list')
								if (redirect) setTimeout('eval("document.location = \'' + redirect + '\'")', 2000)
							}
						},
						buttons: {
							Ok: '1',
							отмена: '0'
						}

					})

				}

			} else {
				displayCustomerInfo("Ошибка: " + oXmlHttp.statusText);
			}

		}
	}

   	oXmlHttp.send(null)

}
function addItemCartCount(host, rid, mid, redirect, name_rest_encode, name_goods_encode, name_rest, name_goods, price, select) {
	var oXmlHttp = createXMLHttp()
   	oXmlHttp.open("GET", host + "cart-get.html?rid=" + rid + "&mid=" + mid, true)
   	oXmlHttp.onreadystatechange = function() {

	   	if (oXmlHttp.readyState == 4) {

		    if (oXmlHttp.status == 200) {
				result = oXmlHttp.responseText
				added = 0
				if (result > 0) added++
				if (select) {
					num = num_tov_pr = parseInt(result)
				} else {
					num = num_tov_pr = document.getElementById('count_goods_' + mid).value
				}

				if (added) {
					f_text = "Блюдо уже добавлено в корзину. Изменить количество?"
				} else {
					f_text = "Добавить в корзину?"
				}
				$.prompt('<h2>' + f_text + '</h2><h3>' + name_goods + '</h3><b class="green">' + price + ' грн.</b><br />Количество: ' + num, {
					callback: function(returnvalue) {
						returnvalue -= 0
						if (returnvalue) {
							load(host, 'cart-list.html?act=add&name=' + name_goods_encode + '&rid=' + rid + '&mid=' + mid + '&count=' + num_tov_pr + '&price=' + parseFloat(price) * parseInt(num_tov_pr) + '&rnd=' + Math.floor(Math.random() * 100000), 'cart_list')
							if (redirect) setTimeout('eval("document.location = \'' + redirect + '\'")', 2000)
						}
					},
					buttons: {
						Ok: '1',
						отмена: '0'
					}

				})

			} else {
				displayCustomerInfo("Ошибка: " + oXmlHttp.statusText);
			}

		}
	}

   	oXmlHttp.send(null)

}



function createXMLHttp() {

	if (typeof XMLHttpRequest != "undefined") {
		return new XMLHttpRequest()

	} else if(window.ActiveXObject) {
		var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0",
						 "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp",
						 "Microsoft.XMLHttp"]
		for (var i = 0; i < aVersions.length; i++) {
			try {
				var oXmlHttp = new ActiveXObject(aVersions[i])
				return oXmlHttp
			} catch (oError) {}
		}

		throw new Error("Невозможно создать объект XMLHttp.")
	}

}



function restMenuRoll(obj) {

	if (obj.className == "restmenu_tr") {
		obj.className = "restmenu_tr_over"
	} else {
		obj.className = "restmenu_tr"
	}

}

function menuRoll(obj, bg1, bg2) {

	childs = $(obj).children("td")

	count = 0
	for (var i = 0; i < childs.length; i++) {
		if (childs[i].className == "dishes_bg5") {
			childs[i].className = "dishes_bg" + eval("bg" + (count%2 + 1))
			count++

		} else {

			cl = childs[i].className.substr(0, 9)
			if (cl == "dishes_bg") {
				childs[i].className = "dishes_bg5"
			}

		}

	}

}





function loadMenu(host, mid, rid) {

	document.getElementById("menu" + mid + "link").style.backgroundImage = ""
	inner = document.getElementById("menu" + mid).innerHTML

	if (inner == "") {
		document.getElementById("menu" + mid + "link").style.backgroundImage = "url('" + host + "img/loader.gif')"
		loadWithoutLoader(host, 'restaurant/menuload.html?mid=' + mid + '&rid=' + rid, "menu" + mid)

	} else {
		$("#menu" + mid).slideToggle()

	}

	return false
}




function showDishesPic(url, id) {

	obj = document.getElementById(id)
	if (!obj) return false

	if (obj.style.display == "block") {
		obj.style.display = "none"
	} else {
		obj.style.display = "block"
		$('#' + id).load(url)
	}

}




function goToSearch(host, param, obj) {
	document.location.href = host + "search-dishes.html?" + param + "=" + obj.value
}



function  clear_field() {
	l = document.getElementById('login').value
	p = document.getElementById('passwd').value
	if (l == "e-mail") {
		document.getElementById('login').value = ""
		document.getElementById('passwd').value = ""
	}
}
function  fill_field() {
	l = document.getElementById('login').value
	p = document.getElementById('passwd').value
	if (l == "") {
		document.getElementById('login').value = "e-mail"
		document.getElementById('passwd').value = "password"
	}
}




function checkReg() {
	phone = document.getElementById('phone').value
	mobile = document.getElementById('mobile').value
	reg = /\d{10}/
	if (document.getElementById('ufam').value == '') {
		$.prompt('<h3>Введите, пожалуйста, <b style="color:#F00;">фамилию</b></h3>')
		return false
	}
	if (document.getElementById('uname').value == '') {
		$.prompt('<h3>Введите, пожалуйста, <b style="color:#F00;">имя</b></h3>')
		return false
	}
	if ( (mobile == '') || (mobile.search(reg) == -1) ) {
		$.prompt('<h3>Не введен <b style="color:#F00;">номер мобильного телефона</b> либо введен неправильно</h3>')
		return false
	}
	if (document.getElementById('address').value == '') {
		$.prompt('<h3>Не введен <b style="color:#F00;">адрес доставки</b></h3>')
		return false
	}
	email = document.getElementById('email').value
	reg_email = /^[0-9a-zA-Z\_.]+@[0-9a-zA-Z\_.]+\.[a-zA-Z\_.]+$/
	if (email.search(reg_email) == -1) {
		$.prompt('<h3>Не введен <b style="color:#F00;">E-mail</b>, либо он введен неправильно</h3>')
		return false
	}
	if (document.getElementById('pass').value == '') {
		$.prompt('<h3>Не введен <b style="color:#F00;">пароль</b></h3>')
		return false
	}
	if (document.getElementById('passr').value == '') {
		$.prompt('<h3>Подтвердите <b style="color:#F00;">пароль</b></h3>')
		return false
	}
	if (document.getElementById('pass').value != document.getElementById('passr').value) {
		$.prompt('<h3>Пароли не совпадают</h3>')
		return false
	}
	return true
}

function checkOrder(reg) {

	sids = ids.split(":")
	chk = true
	for (var n=1; n<sids.length; n++) {
		sum = parseFloat(document.getElementById("total" + sids[n]).innerHTML)
		if (sum < 100) chk = false
	}
	if (!chk) {
		$.prompt('<h3>Минимальная стоимость заказа в одном ресторане<br /><strong>100 грн</strong></h3>')
		return false
	}

	if (reg) {
		
	} else {
		phone = document.getElementById('phone').value
		mobile = document.getElementById('mobile').value
		reg = /\d{10}/
		if (document.getElementById('ufam').value == '') {
			$.prompt('<h3>Введите, пожалуйста, <b style="color:#F00;">фамилию</b></h3>')
			return false
		}
		if (document.getElementById('uname').value == '') {
			$.prompt('<h3>Введите, пожалуйста, <b style="color:#F00;">имя</b></h3>')
			return false
		}
		if ( (mobile == '') || (mobile.search(reg) == -1) ) {
			$.prompt('<h3>Не введен <b style="color:#F00;">номер мобильного телефона</b> либо введен неправильно</h3>')
			return false
		}
		if (document.getElementById('address').value == '') {
			$.prompt('<h3>Не введен <b style="color:#F00;">адрес доставки</b></h3>')
			return false
		}
		email = document.getElementById('email').value
		reg_email = /^[0-9a-zA-Z\_.]+@[0-9a-zA-Z\_.]+\.[a-zA-Z\_.]+$/
		if (email.search(reg_email) == -1) {
			$.prompt('<h3>Не введен <b style="color:#F00;">E-mail</b>, либо он введен неправильно</h3>')
			return false
		}
		if (document.getElementById('pass').value == '') {
			$.prompt('<h3>Не введен <b style="color:#F00;">пароль</b></h3>')
			return false
		}
		if (document.getElementById('passr').value == '') {
			$.prompt('<h3>Подтвердите <b style="color:#F00;">пароль</b></h3>')
			return false
		}
		if (document.getElementById('pass').value != document.getElementById('passr').value) {
			$.prompt('<h3>Пароли не совпадают</h3>')
			return false
		}
	}
	return true
}


ids = ""
function resetPrice(obj, rid) {

	var tr = $(obj.parentNode.parentNode.parentNode).children("tr")
	total = 0
	for (var i=0; i<tr.length; i++) {
		var td = $(tr[i]).children("td")
		count = ""
		price = ""
		for (var k=0; k<td.length; k++) {
			var elems = $(td[k]).children()
			for (var m=0; m<elems.length; m++) {
				var cls = $(elems[m]).attr("class")
				if (cls == "select_price") {
					var count = $(elems[m]).val()
				}
				if (cls == "restmenu_price") {
					var price = parseFloat(elems[m].innerHTML)
				}
			}
		}
		if ( (count) && (price) ) {
			total = total + price * count
		}
	}
	
	var td = document.getElementById("total" + rid).parentNode
	var info = document.getElementById("info" + rid)
	var div = $(td).children("div.restmenu_price")

	if (total < 100) {
		td.style.backgroundColor = "#FF0000"
		td.style.color = "#FFFFFF"
		div[0].style.color = "#FFFFFF"
		info.innerHTML = '<h2 style="margin:12px 0 8px 0;">ИТОГО:<br /><span style="font-size:12px; color:#b81a1a;">В стоимость заказа не включена доставка<br />Минимальная стоимость заказа в одном ресторане - 100 грн</span></h2>'
	} else {
		td.style.backgroundColor = "transparent"
		td.style.color = "#3B3B3B"
		div[0].style.color = "#489900"
		info.innerHTML = '<h2 style="margin:12px 0 8px 0;">ИТОГО:<br /><span style="font-size:12px; color:#b81a1a;">В стоимость заказа не включена доставка</span></h2>'
	}
	document.getElementById("total" + rid).innerHTML = total
	document.getElementById("total_grn" + rid).innerHTML = valut(total)

	sids = ids.split(":")
	total_sum = 0
	for (var n=1; n<sids.length; n++) {
		total_sum = total_sum + parseFloat(document.getElementById("total" + sids[n]).innerHTML)
	}

	document.getElementById("totalSum").innerHTML = '<em><b>' + total_sum + '</b> ' + valut(total_sum) + '</em>'
}



function valut(summa) {
	summa = parseFloat(summa)
	if (summa == "") summa = 0
	if ( (summa >= 10) && (summa <= 20) ) {
		value = "гривен"
	} else {
		summa = summa.toString()
		summa = summa.split("")
		chislo = summa[summa.length - 1]

		if (chislo == 1) {
			value = "гривня"
		} else if ( (chislo == 2) || (chislo == 3) || (chislo == 4) ) {
			value = "гривни"
		} else {
			value = "гривен"
		}

	}

	return value
}



function checkRecover() {
	if (document.getElementById('login_recover').value == "") return false
	return true
}












