var idxCounter = 0;

function delete_row(oTr)
{
	var oTable = oTr.parentElement.parentElement;
	oTable.deleteRow(oTr.rowIndex);	
}

function add_empty(strTableId)
{
	var oTable = document.getElementById(strTableId);
	if(oTable != null)
	{
		if(oTable.rows.length == 1)
		{
			var oTr = oTable.insertRow();
			var oTd = document.createElement("TD");
			oTd.align = "center";
			switch(strTableId)
			{
				case "uploads":
				oTd.colSpan = 5;
				oTd.innerText = "Ни один файл не найден";
				break;
				case "ingrid":
				oTd.colSpan = 5;
				oTd.innerText = "Ни одной записи не найдено";
				break;
			}
			oTr.appendChild(oTd);
		}
	}
}

function add_file(strTableId)
{
	var oTable = document.getElementById(strTableId);
	var c = -1;

	if(oTable != null)
	{
		switch(strTableId)
		{
			case "uploads":
				if(oTable.rows.length == 2)
				{
					if(oTable.rows(1).all(0).innerText.toLowerCase() == "ни один файл не найден")
					{
						oTable.deleteRow(1);
						c = 0;
					}
				}
				if(c == -1)
					c = parseInt(oTable.rows(oTable.rows.length-1).all(0).innerText);
				var oTr = oTable.insertRow();
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='hidden' value='' name='idPhoto[]'>"+(c + 1);
				oTr.appendChild(oTd);
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='file' name='uploaded_file[]'>";
				oTr.appendChild(oTd);
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='file' name='uploaded_file_thumb[]'>";
				oTr.appendChild(oTd);
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='text' name='sDescription[]' value=''>";
				oTr.appendChild(oTd);
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<a href='#' onclick='delete_row(this.parentElement.parentElement); add_empty(\"uploads\");'><img src='images/icon_delete.gif' width='15' height='15' border='0' alt='Удалить'></a>";
				oTr.appendChild(oTd);
			break;
			case "ingrid":
				if(oTable.rows.length == 2)
				{
					if(oTable.rows(1).all(0).innerText.toLowerCase() == "ни одной записи не найдено")
					{
						oTable.deleteRow(1);
						c = 0;
					}
				}
				if(c == -1)
					c = parseInt(oTable.rows(oTable.rows.length-1).all(0).innerText);
				var oTr = oTable.insertRow();
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='hidden' value='' name='idRecipeProduct[]'>"+(c + 1);
				oTr.appendChild(oTd);
				var o = document.getElementById("select_form");
				var oTd = document.createElement("TD");
				oTd.innerHTML = replaceString(o.innerHTML, "_Hidden", "[]");
				oTr.appendChild(oTd);
				/*
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='text' name='strNameIngridient[]' value='' size='35'>";
				oTr.appendChild(oTd);
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<input type='text' name='strVolume[]' value='' size='10'>";
				oTr.appendChild(oTd);
				*/
				var oTd = document.createElement("TD");
				oTd.innerHTML = "<a href='#' onclick='delete_row(this.parentElement.parentElement); add_empty(\"ingrid\");'><img src='images/icon_delete.gif' width='15' height='15' border='0' alt='Удалить'></a></a>";
				oTr.appendChild(oTd);
			break;
		}
		//document.body.innerHTML = document.body.innerHTML;
	}
}

function replaceString(sString, sReplaceThis, sWithThis)
{
  if (sReplaceThis != "" && sReplaceThis != sWithThis)
  {
    var counter = 0;
    var start = 0;
    var before = "";
    var after = "";
    while (counter<sString.length) {
      start = sString.indexOf(sReplaceThis, counter);
      if (start == -1)
	  {
       break;
       }
	   else
	   {
         before = sString.substr(0, start);
         after = sString.substr(start + sReplaceThis.length, sString.length);
         sString = before + sWithThis + after;
         counter = before.length + sWithThis.length;
        }
      }
    }
 return sString;
}

function fileImageDelete(oImg)
{
	oImg.parentElement.all(0).style.display = '';
	oImg.parentElement.all(1).style.display = 'none';
	oImg.style.display = 'none';
	document.all.files_to_delete.value=document.all.files_to_delete.value+oImg.parentElement.all(1).innerText+";";
}

function count(oChkbox)
{
	if(oChkbox.checked)
		idxCounter += 1;
	else idxCounter -= 1;
	var o = document.getElementById("delete_selected");
	if(o != null)
	{
		if(idxCounter == 0)
			o.disabled = true;
		else o.disabled = false;
	}
}

function color_bg(oChkbox, oTr, strColor)
{
	if(oChkbox.checked)
		oTr.style.backgroundColor = strColor;
	else
		oTr.style.backgroundColor = "";
}

function shMenu(id)
{
	var tbl = eval("document.all.subtable" + id);
	var arrow = eval("document.all.arrow" + id);
	if(tbl.className == "hidden")
	{
		tbl.className = "";
		arrow.src = "images/arrow02.gif";
	} 
	else
	{
		tbl.className = "hidden";
		arrow.src = "images/arrow01.gif";
	}
}

function showMenuAll(a)
{
	if(a.innerText == "показывать меню")
	{
		a.innerText = "скрывать меню"
		document.all.subtable1.className = '';
		document.all.subtable7.className = '';
		document.all.subtable10.className = '';
		document.all.subtable15.className = '';
		document.all.subtable19.className = '';
		document.all.arrow1.src = 'images/arrow02.gif';
		document.all.arrow7.src = 'images/arrow02.gif';
		document.all.arrow10.src = 'images/arrow02.gif';
		document.all.arrow15.src = 'images/arrow02.gif';
		document.all.arrow19.src = 'images/arrow02.gif';
		setCookie('isMenuShow', 1);
	}
	else
	{
		a.innerText = "показывать меню"
		document.all.subtable1.className = 'hidden';
		document.all.subtable7.className = 'hidden';
		document.all.subtable10.className = 'hidden';
		document.all.subtable15.className = 'hidden';
		document.all.subtable19.className = 'hidden';
		document.all.arrow1.src = 'images/arrow01.gif';
		document.all.arrow7.src = 'images/arrow01.gif';
		document.all.arrow10.src = 'images/arrow01.gif';
		document.all.arrow15.src = 'images/arrow01.gif';
		document.all.arrow19.src = 'images/arrow01.gif';
		setCookie('isMenuShow', 0);
	}
}

function getCookie(name)
{
  var cookies = document.cookie;
  var start = cookies.indexOf(name + '=');
  if (start == -1) return null;
  var len = start + name.length + 1;
  var end = cookies.indexOf(';',len);
  if (end == -1) end = cookies.length;
  return unescape(cookies.substring(len,end));
}

function setCookie(name, value, expires, path, domain, secure)
{
  value = escape(value);
  expires = (expires) ? ';expires=' + expires.toGMTString() :'';
  path    = (path)    ? ';path='    + path                  :'';
  domain  = (domain)  ? ';domain='  + domain                :'';
  secure  = (secure)  ? ';secure'                           :'';

  document.cookie =
    name + '=' + value + expires + path + domain + secure;
}

function deleteCookie(name, path, domain) {
  var expires = ';expires=Thu, 01-Jan-70 00:00:01 GMT';
  (path)    ? ';path='    + path                  : '';
  (domain)  ? ';domain='  + domain                : '';

  if (getCookie(name))
    document.cookie = name + '=' + expires + path + domain;
}

function voting(f)
{
	var k = 0;
	for(i=0;i<f.elements.length;i++)
	{
		el = f.elements(i);
		if(el.checked) k++;
	}
	if(k > 0)
	{
		//var myWin = window.open("index.php", "win", "height=150, width=300, menubar=no, scrollbars=no, status=no, toolbar=no");
		f.submit();
		//parent.location.reload();
	}
	else
	{
		alert("Необходимо отметить один из пунктов!");
	}
}

function show_image(url, width, height)
{
	window.open(url, "photo", "height="+height+", width="+width+", menubar=no, scrollbars=no, status=no, toolbar=no");
}

function show_image_doc(url, width, height, description)
{
	var oWin = window.open("", "photo", "height="+height+", width="+width+", menubar=no, scrollbars=no, status=no, toolbar=no");
	oWin.document.write('<html><head><title>'+description+'</title></head></head><body  leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0"><img src='+url+'></body></html>');
}

function add_to_basket()
{
	var checked = false;
	var f = document.getElementById("pro_f");
	for(i=0;i<f.elements.length;i++)
	{
		if(f.elements(i).type == "checkbox")
		{
			if(f.elements(i).checked)
			{
				checked = true;
				break;
			}
		}
	}
	if(!checked)
	{
		alert("Вы ничего не отметили!");
		return;
	}
	f.submit();
}

function add_to_basket2()
{
	var f = document.getElementById("add_to_basket");
	if(f.intQuantity.value == "")
	{
		alert("Введите количество!");
		return;
	}
	f.submit();
}

function delete_from_basket()
{
	var checked = false;
	var f = document.getElementById("pro_f");
	for(i=0;i<f.elements.length;i++)
	{
		if(f.elements(i).type == "checkbox")
		{
			if(f.elements(i).checked)
			{
				checked = true;
				break;
			}
		}
	}
	if(!checked)
	{
		alert("Вы ничего не отметили!");
		return;
	}
	if(confirm("Вы уверены, что хотите удалить из корзины отмеченные продукты?"))
	{
		f.to_do.value = "delete_from_basket";
		f.submit();
	}
}

function change_quantity()
{
	var f = document.getElementById("pro_f");
	f.to_do.value = "change_quantity";
	f.submit();
}

function clear_required(o)
{
	if(o.value.length > 0) o.className = 'my_input';
	else o.className = 'is_required';
}

function change_user_type(o)
{
	switch(o.value)
	{
		case "Физическое лицо":
			document.getElementById("contact_person").style.display = "none";
			document.getElementById("fio").innerText = "Ф.И.О.";
		break;
		case "Юридическое лицо":
			document.getElementById("contact_person").style.display = "";
			document.getElementById("fio").innerText = "Название компании";
		break;
	}
}

function validate_email(str, not_valid_text)
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert(not_valid_text)
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert(not_valid_text)
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert(not_valid_text)
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    alert(not_valid_text)
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert(not_valid_text)
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    alert(not_valid_text)
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    alert(not_valid_text)
	    return false
	 }
	 return true
}

function validate_registration(f)
{
	if(!validate_email(f.strEmail.value, "Вы ввели некорректный адрес электронной почты!"))
		return;
	var o = document.getElementById("change_pass");
	var chkPass = false;
	if(o != null)
	{
		if(o.checked) chkPass = true;
	}
	else chkPass = true;
	if(chkPass)
	{
		if(f.strPassword.value.length < 3)
		{
			alert("Пароль менее трех символов!");
			return;
		}
		if(f.strPassword.value != f.strPassword2.value)
		{
			alert("Пароли не совпадают!");
			return;
		}
		pass = f.strPassword.value;
		var s="";
		for(i=0;i<pass.length;i++)
		{
			if((pass.charCodeAt(i) >= 48 && pass.charCodeAt(i) <= 57) || (pass.charCodeAt(i) >= 97 && pass.charCodeAt(i) <= 122) || (pass.charCodeAt(i) >= 65 && pass.charCodeAt(i) <= 90))
			{
			}
			else
			{
				alert("Пароль содержит запрещенные символы!");
				return;
			}
		}
	}
	for(i=0;i<f.elements.length;i++)
	{
		if(f.elements(i).className == "is_required" && f.elements(i).value == "" && f.elements(i).name != "strPassword" && f.elements(i).name != "strPassword2")
		{
			alert("Одно из обязательных полей не заполнено!");
			return;
		}
	}
	f.submit();
}

function do_required(f)
{
	if(f.strEmail.value == "") f.strEmail.className = "is_required";
	if(f.strPassword.value == "") f.strPassword.className = "is_required";
	if(f.strPassword2.value == "") f.strPassword2.className = "is_required";
	if(f.strFullName.value == "") f.strFullName.className = "is_required";
}

function order_confirm()
{
	var f = document.getElementById("pro_f");
	f.to_do.value = "order_confirm";
	f.submit();
}

function delete_order()
{
	if(confirm("Вы уверены, что хотите удалить заказ?"))
	{
		var f = document.getElementById("order_actions");
		f.to_do.value = "delete_order";
		f.submit();
	}
}

function order_confirm_submit()
{
	var f = document.getElementById("pro_f");
	f.to_do.value = "order_confirm_submit";
	f.submit();
}

function checkUncheck(obj1, obj2)
{
	if(obj1.type.toLowerCase() == "text")
	{
		if(obj1.value != "" && obj1.value != "0")
		{
			obj2.checked = true;
		}
		else obj2.checked = false;
	}
	else
	{
		if(obj1.checked && (obj2.value == "" || obj2.value == "0"))
		{
			obj2.value = "1";
		}
		else obj2.value = "0";
	}
}

function change_password(o)
{
	if(o.checked)
	{
		document.all.pass1.style.display = "";
		document.all.pass2.style.display = "";
	}
	else
	{
		document.all.pass1.style.display = "none";
		document.all.pass2.style.display = "none";
	}
}

function add_rec(f)
{
	for(i=0;i<f.elements.length;i++)
	{
		if(f.elements(i).className == "is_required" && f.elements(i).value == "")
		{
			alert("Одно из обязательных полей не заполнено!");
			return;
		}
	}
	f.submit();
}

function show_vacancy(id)
{
	for(i=0;i<document.all.length;i++)
	{
		if(document.all(i).tagName.toLowerCase() == "blockquote" && document.all(i).id != "vacancy_"+id)
		{
			document.all(i).style.display = "none";
		}
	}
	var o = document.getElementById("vacancy_"+id);
	if(o.style.display == "none") o.style.display = "";
	else o.style.display = "none";
}

function price_list_check(o)
{
	var chkbox = false;
	var radio = false;
	for(i = 0; i < o.elements.length; i++)
	{
		if(o.elements(i).name.indexOf("checkbox") >= 0)
		{
			if(o.elements(i).checked) chkbox = true;
		}
		if(o.elements(i).name == "radiobutton")
		{
			if(o.elements(i).checked) radio = true;
		}
	}
	if(!chkbox)
	{
		alert("Вы не отметили сферу деятельности!");
		return;
	}
//	if(!radio)
//	{
//		alert("Вы не отметили насколько Вас заинтересовала наша компания!");
//		return;
//	}
	if(o.contact_person.value == "" || o.city_name.value == "" || o.phone_number.value == "" || o.email.value == "")
	{
		alert("Вы не заполнили одной из обязательных полей:\n\nКонтактное лицо\nГород\nТелефон\nEmail");
		return;
	}
	o.submit();
	o.reset();
}

function show_news(idx)
{
	var o = document.getElementById("news_"+idx);
	if(o != null)
	{
		if(o.style.display == "")
			o.style.display = "none";
		else
			o.style.display = "";
	}
}

function show_recipes(idx)
{
	var d = document.all.allrecipes;
	var s = "recipes_"+idx;
	for(i=0;i<d.all.length;i++)
	{
		if(d.all(i).id.indexOf("recipes_")==0)
		{
			d.all(i).style.display = "none";
		}
		if(d.all(i).id==s)
		{
			d.all(i).style.display = "";
		}
	}
}

function subscribe()
{
	if(validate_email(document.all.subs_email.value, "Вы ввели некорректный адрес электронной почты!"))
	{
		document.all.reload_image.src="index.php?to_do=subscribe&email="+document.all.subs_email.value;
		alert("Спасибо за подписку!");
		document.all.subs_email.value = "";
	}
}

function show_det()
{
	var n1 = document.getElementById("n1");
	var n2 = document.getElementById("n2");
	var n3 = document.getElementById("n3");
	if(n1 != null)
	{
		if(n1.style.display == "")
		{
			n1.style.display = "none";
			n2.style.display = "none";
			n3.style.display = "";
		}
		else
		{
			n1.style.display = "";
			n2.style.display = "";
			n3.style.display = "none";
		}
	}
}
