function hide_kat (id)
  {
  	var obj = document.getElementById(id);
    if (obj.style.display == 'none') obj.style.display = '';
    else obj.style.display = 'none';

  }

function show_img(img,width,height)
	{
	   var a
	   var b
	   var url
	   vidWindowWidth=width;
	   vidWindowHeight=height;
	   a=(screen.height-vidWindowHeight)/5;
	   b=(screen.width-vidWindowWidth)/2;
	   features="top="+a+",left="+b+",width="+vidWindowWidth+",height="+vidWindowHeight+",toolbar=no,menubar=no,location=no,directories=no,scrollbars=no,resizable=no";
	   url="/show.php?img="+img;
	   window.open(url,'',features,true);
	}

function add(msg_num)
  {
       var a
	   var b
	   var url
	   var vidWindowWidth
	   var vidWindowHeight

	   vidWindowWidth=250;
	   vidWindowHeight=30;
	   a=(screen.height-vidWindowHeight)/5;
	   b=(screen.width-vidWindowWidth)/2;

	   features="top="+a+",left="+b+",width="+vidWindowWidth+",height="+vidWindowHeight+",toolbar=no,menubar=no,location=no,directories=no,scrollbars=no,resizable=no";
	   url="/add.php?id_tov="+msg_num;
	   mreplywin = window.open(url,'',features,true);

  }
var cookies;
var cookie;


function end_zak()
{
   value = "";   if (div = document.getElementById('zak_name'))
    {
      if (div.value!="")
       {    		value += "Name: " + div.value + '\n';
    		div.style.backgroundColor = '#ffffff';
       }
      else
       {       		div.style.backgroundColor = '#fbec6c';
       		return 0;
       }
    } else {    	return 0;
    }
   if (div = document.getElementById('zak_fam'))
    {
       if (div.value!="")
        {
    		value += "Fam: " + div.value + '\n';
    		div.style.backgroundColor = '#ffffff';
    	}
       else
       {
       		div.style.backgroundColor = '#fbec6c';
       		return 0;
       }
    } else {
    	return 0;
    }
   if (div = document.getElementById('zak_tel'))
    {
       if (div.value!="")
       {
    		value += "Tel: " + div.value + '\n';
    		div.style.backgroundColor = '#ffffff';
       }
       else
       {
       		div.style.backgroundColor = '#fbec6c';
       		return 0;
       }
    } else {
    	return 0;
    }
   if (div = document.getElementById('zak_email'))
    {
       if (div.value!="")
       {
    		value += "E-mail: " + div.value + '\n';
    		div.style.backgroundColor = '#ffffff';
       }
       else
       {
       		div.style.backgroundColor = '#fbec6c';
       		return 0;
       }
    } else {
    	return 0;
    }
   if (div = document.getElementById('zak_koment'))
    {
       if (div.value!="")
       {
    		value += "Koment: " + div.value + '\n';
    		div.style.backgroundColor = '#ffffff';
       }

       else
       {
       		div.style.backgroundColor = '#fbec6c';
       		return 0;
       }
    } else {
    	return 0;
    }
   if (div = document.getElementById('no_login'))
    {
       var tov = new Array();
	   cookies = parseCookie();
	   value += "\n";
	   for (cookie in cookies)
		 {
	       tov = cookies[cookie].split("|");
	       //DeleteAllCookie()
	       tov[2] = parseFloat(tov[2]);
	       if (tov[2]>0)
	        {
	            value += "Name: " + tov[3] + "\tKol-vo: " + tov[1] + "\tMoney: " + tov[2] + "\n";
	        }
		 }
        post_mes (value, div);
        DeleteAllCookie();
        write_cart();
    }
}


function edit_cart ()
{   var tov = new Array();
   cookies = parseCookie();
   for (cookie in cookies)
	 {
       tov = cookies[cookie].split("|");
       //DeleteAllCookie()
       tov[2] = parseFloat(tov[2]);
       if (tov[2]>0)
        {
            if (div = document.getElementById('tov_kol_' + tov[0] + ''))
            {
            	if (div.value<1) DeleteCookie(cookie);
            	else SetCookie("tov["+ tov[0] +"]", tov[0] + "|" + parseInt(div.value) + "|" + tov[2] + "|" + tov[3], null, null, "/", null);
            }
            if (div = document.getElementById('tov_del_' + tov[0] + ''))
            {
            	if (div.checked==true) DeleteCookie(cookie);
            }
        }
	 }
	all_cart ();
	write_cart();
}

function all_cart ()
{
 if (div = document.getElementById('all_cart'))
 {
  value = "";
  value += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"trash\">";
  value += "<tr><td id=\"tr_head\">Товары</td><td id=\"ampty\">&nbsp;</td><td>Кол-во</td><td>Сумма</td><td>убрать</td></tr>";

   var sum = 0;
   var tov = new Array();
   cookies = parseCookie();
	// Вывод всех cookie.
	for (cookie in cookies)
	 {
	   //alert(cookie + "=" + cookies[cookie]);
       tov = cookies[cookie].split("|");
       //DeleteAllCookie()
       //alert(tov[2]);
       tov[2] = parseFloat(tov[2]);
       if (tov[2]>0)
        {
            tov[1] = parseInt(tov[1]);
            value += "<tr>";
            value += "<td id=\"model_img\"></td><td id=\"name\">" + tov[3] + "</td>";
            value += "<td><div class=\"trash_stat\"><input id=\"tov_kol_" + tov[0] + "\" name=\"tov_kol_" + tov[0] + "\" type=\"text\" value=\"" + tov[1] + "\" style=\"width:30px;\"></div></td>";
            value += "<td><div class=\"trash_stat\">" + tov[2] + "</div></td>";
            value += "<td><div class=\"trash_stat\" id=\"del\"><input id=\"tov_del_" + tov[0] + "\" name=\"tov_del_" + tov[0] + "\" type=\"checkbox\"></div></td>";
            value += "</tr>";
        	sum += tov[2]*tov[1];
        }
	 }

  value += "</table>";
  value += "<table class=\"done\"><tr><td>Всего товаров на сумму: <span class=\"colored\">" + sum + "</span> руб.</td></tr><tr><td><a hstyle=\"cursor:pointer;\" onClick=\"edit_cart ();\">Пересчитать</a></td></tr><tr><td><a onClick=\"edit_cart (); document.location='zakaz.html'\">Оформить заказ</a></td></tr></table>";

  div.innerHTML = value;
 }
}





window.onload = function ()
{	write_cart();
	all_cart ();
}

function write_cart()
{
   div = document.getElementById('left_stat');
   var kol = 0;
   var sum = 0;
   var tov = new Array();
   cookies = parseCookie();
	// Вывод всех cookie.
	for (cookie in cookies)
	 {
	   //alert(cookie + "=" + cookies[cookie]);
       tov = cookies[cookie].split("|");
       //DeleteAllCookie()
       //alert(tov[2]);
       tov[2] = parseFloat(tov[2]);
       if (tov[2]>0)
        {
          tov[1] = parseInt(tov[1]);
          sum += tov[2]*tov[1];
          kol++;
        }
	 }
	// Проверка существования cookie по имени foo.
	if (null == cookies.foo) {
	   // Отсутствует cookie по имени foo
	}
   /*
   for (var i = 1; i < tov.length; i++) {   	  alert(tov[i]);
   	  sum += tov[i][2];
   }
   */

   value = "Выбранно товаров: " + kol + " шт.<br />Общая сумма: " + sum + " руб.";
   div.innerHTML = value;
}

function add_cart(id, cena, kol, name)
 {
   if (IsCookieEnabled())
   {
    SetCookie("tov["+id+"]", id + "|" + kol + "|" + cena + "|" + name, null, null, "/", null); 	write_cart();
 	alert('Товар добавлен в корзину.');
   }
   else
   	alert ("NO Cookie");
 }

function SetCookie(strName, oValue , oDateExpires , strDomain , strPath , bSecure)
{
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;

    var oDate = false; // аргумент expires

    if((argc > 2) && (argv[2] != null))
    {
        // задана дата
        // дату допустимо задавать:
        //    объектом Date,
        //    числом (миллисекундное смещение от 00:00:00 01.01.1970)
        //    строкой в формате, приемлемом для Date.parse

        var nStamp = (typeof(argv[2]) != "number")    ?
                Date.parse(argv[2].toString())        :
                argv[2];

        if(!isNaN(nStamp))
            oDate = new Date(nStamp);
            oDate = oDate + 10000;
    }

    document.cookie =   strName + "=" + escape(oValue.toString())                   +
                        (oDate ? "; expires=" + oDate.toGMTString() : "")           +
                        (((argc > 3) && (argv[3])) ? "; domain=" + argv[3] : "")    +
                        (((argc > 4) && (argv[4])) ? "; path=" + argv[4] : "")      +
                        ((argc > 5) ? (argv[5] ? "; secure" : "") : "");

}
function GetCookie(strName)
{
    if((typeof(strName) == "string") && strName.length)
    {
        var i = 0, j;

        var strFind    = strName + "=";
        var strCookie  = document.cookie;

        do
        {
            j = i + strFind.length;

            if(strCookie.substring(i, j) == strFind)
            {
                var nEnd = strCookie.indexOf(";", j);

                if(nEnd < 0)
                    nEnd = strCookie.length;

                return unescape(strCookie.substring(j, nEnd));
            }
        }
        while(i = strCookie.indexOf(" ", j) + 1);
    }

    return null;
}
function DeleteCookie(strName)
{
    document.cookie = strName + "=0; expires=" + (new Date(0)).toGMTString();
}
function DeleteAllCookie()
{
    var arr = new Array();
    var str = document.cookie;

    var i = 0, nBeg = 0, nEnd;

    do
    {
        if((nEnd = str.indexOf("=", nBeg)) > -1)
            arr[i] = str.substring(nBeg, nEnd);
    }
    while(i++, nBeg = str.indexOf(" ", nEnd) + 1);

    for(i = 0; i < arr.length; i++)
        DeleteCookie(arr[i]);
}
function IsCookieEnabled()
{
    if(typeof(navigator.cookieEnabled) != "undefined")
        return navigator.cookieEnabled;
    else
    {
        // свойство navigator.cookieEnabled не поддерживается
        // установим и получим тестовую куку

        var _c = "__V_TEST_COOKIE_NAME_";

        SetCookie(_c, "1");

        if(GetCookie(_c) != null)
        {
            DeleteCookie(_c);
            return true;
        }

        return false;
    }
}

function parseCookie() {
      // Разделение cookie.
      var cookieList = document.cookie.split("; ");
      // Массив для каждого cookie находится в cookieList
      var cookieArray = new Array();
      for (var i = 0; i < cookieList.length; i++) {
         // Разделение пар имя-значение.
         var name = cookieList[i].split("=");
         // Декодирование и добавление в массив cookie.
         cookieArray[unescape(name[0])] = unescape(name[1]);
      }
      return cookieArray;
   }

		 function get_http()
		  {
		    if (window.XMLHttpRequest) {
		        try {
		            return new XMLHttpRequest();
		        } catch (e){}
		    } else if (window.ActiveXObject) {
		        try {
		            return new ActiveXObject('Msxml2.XMLHTTP');
		        } catch (e){}
		        try {
		            return new ActiveXObject('Microsoft.XMLHTTP');
		        } catch (e){}
		    }
		    return null;
		  }
function post_mes (mes, div)
{	url = '/mail.php';
    this.http = get_http();
    this.working = false;
    var param = null;
    var ret = "";
    if (!this.working && this.http)
	{
		var http = this.http;
		var method = "POST";
		this.http.open(method, url, true);
		if (method == "POST")
		{
		  param = "mes=" + encodeURI(mes);
		  this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		  this.http.setRequestHeader("Content-length", param.length);
		  this.http.setRequestHeader("Connection", "close");
		}
		this.http.onreadystatechange = function()
		  {
		                if (http.readyState == 4)
		                  {
		                    ret = http.responseText;
		                    div.innerHTML = ret;
		                    this.working = false;
		                  }else
		                  {
		                     // данные в процессе получения,
		                     // можно повеселить пользователя
		                     //сообщениями
		                     // ЖДИТЕ ОТВЕТА
		                  }
		  }
		this.working = true;
		this.http.send(param);
	}
	if(!this.http)
	{
		alert('Ошибка при создании XMLHTTP объекта!');
	}
}

