// ev = 0.00;
function validStrings()
{
		if (OdersForm.fldName.value=="") 
		{
			alert("Укажите наименование организации или Ф.И.О.");
			OdersForm.fldName.focus();
			return false;
		}
		if (OdersForm.fldPhone.value==""  &&  OdersForm.fldEMail.value=="") 
		{
			alert("Укажите Телефон или Email");
			OdersForm.fldPhone.focus();
			return false;
		}
		var ncount = 0
		for (m=0;m<RowCount+1;m++)		
		{
			var oOldIns = document.all["order_tbl"+m]; 
			tr = oOldIns;
			tds = tr.cells;
			if (tds[0].getElementsByTagName("input")[0].value.length>0)
			{
				ncount++;
				inp=tds[2].getElementsByTagName("input");
				if(inp[0].type=="text") 
					if (!validNumber(inp[0],true,true))  return false;
				inp=tds[3].getElementsByTagName("input");
				if(inp[0].type=="text") 
					if (inp[0].value!="" && !validNumber(inp[0],false,true))  return false;
				if (inp[0].value=="" && (tds[1].innerText=="0.00" || tds[1].innerText=="0") && (document.OdersForm.qwest.value=="Отправить заказ" || (document.OdersForm.qwest.value=="Сумма заказа" && tds[0].getElementsByTagName("input")[0].style.color=="red")))
				{
					alert("Не указана цена в строке "+parseInt(m+1)+"!");
					return false;
				}
			}
		}
		if (!ncount)
		{
			alert("Нет наименований!");
			return false;
		}
		saveDataOrder();
		return true;
}
function  DellDetal(obj)
{
	url="korzina.php?id="+obj.parentNode.parentNode.cells[0].id;
	navigate(url);
}

function  AddDetal(obj)
{
	alert("Добавлено в заказ: ''"+obj.parentNode.parentNode.cells[0].innerText+"''");
	url="AddInSess.php?"+obj.parentNode.parentNode.cells[0].id+"cx"+obj.parentNode.getElementsByTagName("input")[0].value+"cx"+obj.parentNode.parentNode.cells[2].innerText;
	self.showModalDialog(url,null,"status:no;scroll:auto;center:yes;help:no;minimize:no;maximize:no;border:10px;statusbar:no;dialogWidth:1 px;dialogHeight:1 px;"); 
}

function  AddDetal2(obj)
{
	alert("Добавлено в заказ: ''"+obj.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.cells[0].innerText+"''");
	url="AddInSess.php?"+obj.id+"cx"+obj.parentNode.getElementsByTagName("input")[0].value+"cx0";
	self.showModalDialog(url,null,"status:no;scroll:auto;center:yes;help:no;minimize:no;maximize:no;border:10px;statusbar:no;dialogWidth:1 px;dialogHeight:1 px;"); 
}

function  OpenImag(nm)
{
	url="showIma.php?"+nm;
	lft = window.screen.width/2-200;
	tp = window.screen.height/2-200;
	open(url, null,'menubar=no,directories=no,location=no,resizable=no, target=viv scrollbars=yes,width=400,height=400');
}

function  op_txt(dd)
{
//	alert(dd.parentNode.cells[0].src);
document.getElementById("elimg").setAttribute('src',"img/spot2.gif");
return true;
//alert("SS");
//	dd.parentNode.cells[0].setAttribute('src', 'img/spot2.gif');
//	<img src="img/spot.gif" width="8" height="8">
	//.innerText parentNode.
}
function setsize() {
document.all["wbl"].width=346;
document.all["rbo"].width=window.screen.width-346
//alert("привет!");
}
function OpenWindow(id) {
w=720;
h=550;
url="detinfo.php?"+id.parentNode.id
lft = window.screen.width/2-270;
tp = window.screen.height/2-200;
window.name="openers";
open(url, "", 'menubar=no,directories=no,location=no,resizable=no, target=viv scrollbars=yes,width='+w +',height='+h+',left='+lft+',top='+tp);
}
function fixDate(date) {
	var base = new Date(0)
	var skew = base.getTime()
	if (skew > 0) date.setTime(date.getTime() - skew)
}

function SaveValuta(doll,euro)
{
	 ev = euro;
	dol = doll;
	alert(doll);
//	alert(doll+"  "+euro);
}
function setCookie(name, value, expires, domain,path, secure) 
{
 //	alert(value);
 var curCookie = name + "=" + escape(value) +((expires) ? "; expires=" + expires.toGMTString() : "")+
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
		document.cookie = curCookie
}
function getCookie(name) 
{
	var prefix = name + "="
	var cookieStartIndex = document.cookie.indexOf(prefix)
	if (cookieStartIndex == -1)
		return null
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
	if (cookieEndIndex == -1)
		cookieEndIndex = document.cookie.length
	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT"
	}
}
//---------------------------------------------------------------------
function getName(id,name_det,newPrice,newQuantity) 
{
  var itemstart = 0;
  var ret = true;
 if ( (data = getCookie("detal"))!=null ) {
  itemstart = data.search(name_det)
  if (itemstart !=-1) {
    var n = 0;
    var j = itemstart+id.length;
    while (n!=3) {
     j++;
     if (data.substring(j,j+1) == '|')  n++;
    }
//	alert(data)
    data = data.replace(data.substring(itemstart,j),name_det+"|"+newPrice+"|"+newQuantity);
//	alert(data)
    document.cookie="detal="+data;
    ret = false;
  }
 }
 return ret;
}

function updateItem(itemno) 
{
 //alert(document.all['str'+itemno].cells[0].id);
  var sum_str  = parseFloat(document.all['str'+itemno].cells[3].innerText);
  var sum_all  = parseFloat(document.all['SumAll'].cells[1].innerText);
  var kol_vo   = parseInt(document.all['quant'+itemno].value);
  sum_all-=sum_str;
  getName(document.all['str'+itemno].cells[0].id,document.all['str'+itemno].cells[0].innerText,document.all['str'+itemno].cells[2].innerText,document.all['quant'+itemno].value)
  sum_str  = kol_vo*parseFloat(document.all['str'+itemno].cells[2].innerText);
  document.all['str'+itemno].cells[3].innerText = String(sum_str);
  sum_all += sum_str;
  document.all['SumAll'].cells[1].innerText = String(sum_all);
}

function validNumber(obj,int_inp,show)
{
	var comma = 0;
	if (int_inp)
	{
		digits="0123456789"
		if (obj.value.length==0) {
		obj.focus()
		alert("Укажите количество!")
		return false;
		}
	}
	else digits="0123456789."
	for(i=0; i<obj.value.length; i++)
	{if (digits.indexOf(obj.value.charAt(i))<0)
		{
			if (show) alert("Неверное число!")
			obj.focus();
			obj.value =obj.value.substring(0,obj.value.length-1);
			return false;
		}
		if (obj.value.charAt(i)=='.') comma++;
	}

	if (!int_inp && comma>1)
	{
		if (show) alert("Неверное число!")
		obj.focus()
		obj.value =obj.value.substring(0,obj.value.length-1);
		return false;
	}
	return true;
}

function chengeKol(obj,key,id)
{
	var int_inp = false;
	if (obj.value=="" && key<48) return;
	if (validNumber(obj,true,true) && id)  updateItem(id);
}
//----------------------------------------------------------
function addItem(newID,newItem,newPrice,newQuantity)
{
	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + 31 * 24 * 60 * 60 * 1000)
	if ( (data = getCookie("detal"))!=null)
		setCookie("detal",data+"["+newID+"]"+newItem+"|"+newPrice+"|"+newQuantity+"|")
	else 
		setCookie("detal","["+newID+"]"+newItem+"|"+newPrice+"|"+newQuantity+"|")
}

function removeAll() 
{
	deleteCookie("detal");
	document.all['tblo'].removeNode(true);
	document.all['tblnm'].removeNode(true);
	document.forms.OdersForm.removeNode(true);
}

function removeItem(itemno) 
{
 var name_det = document.all['str'+itemno].cells[0].innerText;
 var sum_str  = parseFloat(document.all['str'+itemno].cells[3].innerText);
 var sum_all  = parseFloat(document.all['SumAll'].cells[1].innerText);
 var itemstart = 0;
 if ( (data = getCookie("detal"))!=null )
 {
  itemstart = data.search(name_det)
  if (itemstart !=-1) 
  {
   var n = 0;
   var j = itemstart+name_det.length;
   while (n!=2)
   {
     j++;
     if (data.substring(j,j+1) == '|')  n++;
   }
//   alert(data.substring(itemstart-1,j+1))
   data = data.replace(data.substring(itemstart-1,j+1),"");
   document.cookie="detal="+data;
   sum_all -= sum_str;
    if (sum_all==0) {
     if (window.name=="myname1") parent.document.all["ofza"].style.visibility='hidden';
	 removeAll() 
	}
   else {
    document.all['str'+itemno].removeNode(true);
    document.all['SumAll'].cells[1].innerText = String(sum_all);
	if (window.name=="myname1")
	{
	parent.document.all["myname1"].height=parent.document.all["myname1"].height-27;
	parent.document.all["tofrm"].height=parent.document.all["tofrm"].height-27;
	}
   }
  }
 }
}

//-------------------------------------------------------------------
function saveToCoockieDetal(id_t,name_det,cost,kol)
{
//	cost = convertComma(String(cost));
	if (getName(id_t,name_det,cost,kol))
		addItem(id_t,name_det,cost,kol);
}

function  SaveToZakaz()
{
	 inp=document.getElementsByTagName("input");
	 for(ci=0; ci < inp.length; ci++) 
	 {
	 	if(inp && inp[ci].type=='checkbox')  
		{
			if  (inp[ci].checked)
			{
				tr=inp[ci].parentNode.parentNode;
				tds = tr.cells;
//				alert(inp[ci].id);//	id detals
//				alert(tds[5].getElementsByTagName("input")[0].value); //Kol - vo
//				alert(tds[3].innerText); Cost
//				alert(tds[1].innerText); Name
//				alert(tds[5].innerText); 
				if (tds.length>0)
					saveToCoockieDetal(inp[ci].id,tds[1].innerText,parseFloat(tds[3].innerText)*parseFloat(tds[5].innerText),tds[5].getElementsByTagName("input")[0].value)
				else
					saveToCoockieDetal(inp[ci].id,tds[1].innerText,tds[3].innerText,0)
			}
		}
	}
}

function ShowOrder(itemlist,theitem,theprice,thequantity,itemtotal,id_det) 
{
document.write('<tr ID="str'+itemlist+'"><td align=left class="OrdTd" id='+id_det+'>'+theitem+'</td><td align=middle class="OrdTd"><INPUT TYPE=TEXT NAME="quant'+itemlist+'" VALUE="'+thequantity+'" SIZE=3 onKeyUp=chengeKol(this,event.keyCode,'+itemlist+')></td><td align=right class="OrdTd">'+theprice+'</td><td align=right class="OrdTd">'+itemtotal+'</td><td class="OrdTd" align="center"><IMG SRC="ima/space.gif" WIDTH="6" HEIGHT="2" ALT=""><a href="javascript:removeItem('+itemlist+')"><IMG SRC="img/remove.gif" WIDTH="13" HEIGHT="15" BORDER="0" ALT="Удалить"></a>&nbsp;</td></tr>');
}

function LoadTovar(order)
{
 var isSave = false;
 var thisitem = 1;
 var itemstart = 0;
 var itotal = 0;
 var subtotal = 0;
 var npp=0;
 var all_sum = 0;
 if ( (data = getCookie("detal"))!=null)
 {
  document.writeln('<TABLE ID=tblo BORDER=0 CELLSPACING=1 CELLPADDING=2 bgColor=#efedd8 width=100%');
  document.writeln('<TR><TD class="topinf">Наименование товара</TD><TD class="topinf">Кол-во</TD><TD class="topinf">Цена</TD><td class="topinf">Сумма<TD class="topinf">Удалить</TD></TR>');
  for (j=0;j<data.length;j++) {
 	if (data.substring(j,j+1) == '[') 
	{
		itemstart = j+1;
		thisitem = 1;
		npp++;
		itotal = 0;
	} 
	else
	{
		if (data.substring(j,j+1) == '|' || data.substring(j,j+1) == ']') 
		{
			if (thisitem==1)  id_det = data.substring(itemstart,j);
			if (thisitem==2)  name_det = data.substring(itemstart,j);
			if (thisitem==3)  cost_det = data.substring(itemstart,j);
			if (thisitem==4)  {	kol_det  = data.substring(itemstart,j); 
				itotal = (eval(cost_det*kol_det));
				subtotal = subtotal + itotal;
				ShowOrder(npp,name_det,cost_det,kol_det,itotal,id_det);}
				thisitem++;
				itemstart=j+1;
			}
		}
	}
	document.writeln('<tr ID="SumAll"><td align=right class="topinf" colspan=3>Итого:</td><td align=right class="OrdTd">'+subtotal+'</td><td class="topinf"></td></tr></table>');
//	if (order) 
	{
	document.writeln('<BR><form name="OdersForm" method="post"  onSubmit="javasript:return SetBtn('+subtotal+')" action="korsina.asp"><table ID="tblnm" cellspacing=0 cellpadding=5 width="500" align=center  border=0 height="96"><tbody><tr><td height="32" width="250" class=br_b><strong>Организации или  ФИО:</strong></td><td width="250" height="32"> <input name=fldName maxlength="50" size="39" width="50" onChange="firmChenge()"></td></tr>');
	document.writeln('<tr> <td height="32" class="br_b"><strong>Телефон / ФИО контакта:</strong></td><td height="32"> <input name=fldPhone maxlength="13" size="13" onChange="firmChenge()">/ <input name=fldContact maxlength="20" size="20" onChange="firmChenge()"> </td></tr><tr> <td  height="32" class="br_b"><strong>E-mail (электронная почта):</strong></td><td height="32"><input name=fldEMail maxlength="30" size="25" width="30" onChange="firmChenge()"></td></tr></table><BR>');
	document.writeln('<div align="center"><table width="100%" border="0" cellspacing="0" cellpadding="0" ><tr><td width="36%" height="36">&nbsp; </td><td width="20%"><input type="submit" name="Submit" value="Отправить"></td><td width="3%">&nbsp; </td><td width="21%"><input type="reset" name="Submit2" value="Очистить" onClick="removeAll()"></td><td width="2%">&nbsp; </td><td width="18%">&nbsp; </td></tr></table></div></form>');
	LoadFirmaAndPhone();
	} 
 } 
 else 
 if (order) document.writeln('<strong>Заявка не заполнена. Предварительно выберите товар</strong>');
 else  
 document.writeln('Заказ не заполнен.<br> Начните оформление заказа с выбора товара:<br> 1. Войдете в каталог продукции выбрав необходимый раздел.<br> 2. Проставьте отметку (отметки) напротив наименования оборудования и требуемое колчество.<br>');
}

function LoadFirmaAndPhone()
{
  var thisitem = 1;
  var itemstart = 0;
  if ( (data = getCookie("nameF"))!=null)
  {
   for (i=0;i<data.length;i++) {
    if (data.substring(i,i+1) == '|') {
    if (thisitem==1) document.all["fldName"].value    = data.substring(itemstart,i);
    if (thisitem==2) document.all["fldPhone"].value   = data.substring(itemstart,i);
    if (thisitem==3) document.all["fldContact"].value = data.substring(itemstart,i);
    if (thisitem==4) document.all["fldEMail"].value   = data.substring(itemstart,i);
    thisitem++;
    itemstart=i+1; }
  }
 }
}	
function SetBtn(subt)
{
	setCookie("order","setord");
	setCookie("subtot",document.all['SumAll'].cells[1].innerText);
}

function firmChenge()
{
isSave = true;
}

function saveFirmaAndPhone()
{
	if (isSave==true)
	{
		var now = new Date()
		fixDate(now)
		now.setTime(now.getTime() + 31 * 24 * 60 * 60 * 1000)
		setCookie("nameF",document.all["fldName"].value+"|"+document.all["fldPhone"].value+"|"+document.all["fldContact"].value+"|"+document.all["fldEMail"].value+"|",now);
	}
}

