var componentrootvarsid = 'http://cpcr.ru/components/getsid/';
var cvars_varsid = Array();
  var componentroottc2 = 'http://cpcr.ru/components/tarifcalc2/';
  var from_req;
  var TSL;
  var FSL;
  var def_city_id = '992|0';
  var def_city_recipt_id;
  var to_req;
  var dog_req;
  var req2;
  var checkerror; // строка сообщения ошибки проверок полей ввода
  var clientdogovornum = ' ';

  var currentcalcresult = Array(); // массив с пришедшими результатами
  var crows_count = 0; // текущее кол-во результатов


  var SAVES_CALCS_TABLE = new Array(); // массив в котором храним таблицу

  function Round2D(val, n) {
      if (typeof (val) == "string") {
          val = val.replace(/,/, ".");
      }
      val = Math.round(parseFloat(val) * 100) / 100;
      if (isNaN(val)) {
          return 0
      } else {
          return val.toFixed(n);
      }
  }

  function gvlid(id) {
      if (id != "") {
          try {
              return document.getElementById(id).value;
          } catch (theException) {
              return '-1';
          }
      } else {
          return '-1';
      }
  }

  function gvlid_cb(id) {
      try {
          d = document.getElementById(id);
          if (d.checked) {
              return d.value;
          } else {
              return 0;
          }
      } catch (theException) {
          return '-1';
      }
  }

  function debugprint(val) {
      try {
          d = document.getElementById('debugconsole');
          if (d) {
              d.innerHTML = d.innerHTML + "<br><br>" + val;
          }
      } catch (theException) {
      }
  }



  // отобразить текущие данные расчета
  function ShowCResult(Send_Weight, oW, rW, fromcity, tocity) {
      var crows = '';
      var owstar = '';
      if (Send_Weight > rW)
          owstar = '*';
      var paramtbl = '<P><b>Результаты рассчета:</b></P><p>Откуда: <b>' + fromcity + '</b><BR/>Куда: <b>' + tocity + '</b></p><p>Вес: <b>' + Round2D(Send_Weight, 3) + owstar + ' кг</b></p>';
      //crows = crows + '<tr><td></td><td align=center>Название услуги</td><td align=center>Тариф с НДС,<br> руб.</td><td align=center>Срок доставки,<br> раб. дни</td></tr>';
      crows = crows + '<tr><td align=center>Название услуги</td><td align=center>Тариф с НДС,<br> руб.</td><td align=center>Срок доставки,<br> раб. дни</td></tr>';
      for (var m = 0; m < currentcalcresult.length; m++) {
          if (currentcalcresult[m][0]) {
              //0 TariffType
              //1 Total_Dost
              //2 Total_DopUsl
              //3 Insurance
              //4 worth
              //5 DP
              currentcalcresult[m][6] = fromcity;
              currentcalcresult[m][7] = tocity;
              currentcalcresult[m][8] = Round2D(Send_Weight, 3);
              currentcalcresult[m][9] = Round2D(oW, 3);
              //crows = crows + '<tr><td><input type=checkbox id="selectedcres' + m + '"/></td><td align=center>' + currentcalcresult[m][0] + '</td><td align=center>' + Round2D(currentcalcresult[m][1], 2) + '</td><td align=center>' + currentcalcresult[m][5] + '</td></tr>';
              crows = crows + '<tr><td align=center>' + currentcalcresult[m][0] + '</td><td align=center>' + Round2D(currentcalcresult[m][1], 2) + '</td><td align=center>' + currentcalcresult[m][5] + '</td></tr>';
              crows_count = crows_count + 1;
          }
      }
      document.getElementById("tarifcalc-result-table").innerHTML = paramtbl + '<table class=cpcr_res cellpadding=3>' + crows + '</table>';
      document.getElementById("tarifcalc-result-table").style.display = 'block';
  }


  // сохранить отмеченные результаты в таблицу
  function savedata() {
      for (var m = 0; m < crows_count; m++) {
          var cbn = 'selectedcres' + m;
          if ((document.getElementById(cbn)) && (document.getElementById(cbn).checked)) {
              var tmp = new Array();
              tmp[0] = currentcalcresult[m][0]; // Название услуги
              tmp[1] = Round2D(currentcalcresult[m][1], 2); // Тариф с НДС, руб
              tmp[2] = Round2D(currentcalcresult[m][2], 2); // Дополнительные услуги
              tmp[3] = Round2D(currentcalcresult[m][3], 2); // Страховка, руб.
              tmp[4] = Round2D(currentcalcresult[m][4], 2); // Тариф за объявленную ценность, руб
              tmp[5] = currentcalcresult[m][5]; // Срок доставки, раб. дни
              tmp[6] = currentcalcresult[m][6]; // откуда
              tmp[7] = currentcalcresult[m][7]; // куда
              tmp[8] = currentcalcresult[m][8]; // send вес
              tmp[9] = currentcalcresult[m][9]; // обьемный вес
              SAVES_CALCS_TABLE[SAVES_CALCS_TABLE.length] = tmp;
          }
      }
      UpdateSavedTable();
  }

  function UpdateSavedTable() {
      if (SAVES_CALCS_TABLE.length > 0) {
          var cRowTable;
          var itogo_po_stroke = 0;
          var tout = '<br><b class="NewsDate">Таблица</b><br><table width=100% style="border-collapse: collapse;" cellpadding=5 border=1>';
          document.getElementById("savedtable").style.display = 'block';
          tout = tout + '<tr style="font-size:10px; font-weight:normal"><td width=10></td><td align=center width=10>Маршрут</td>';
          tout = tout + '<td align=center>Вес,<br> кг</td>';
          tout = tout + '<td align=center>Название<br> услуги</td>'
          tout = tout + '<td align=center>Срок<br> доставки<br>раб. дни</td>';
          tout = tout + '<td align=center>Тариф за<br> доставку с<br> НДС, руб.</td>';
          tout = tout + '<td align=center>Страховка<br>руб.</td>';
          tout = tout + '<td align=center>Тариф за<br> объявленную<br> ценность,<br> руб</td>';
          tout = tout + '<td align=center>Стоимость<br> доп.<br> сервисов (с<br> НДС руб.)</td>';
          tout = tout + '<td align=center>Итого, руб.</td></tr>';
          for (var i = 0; i < SAVES_CALCS_TABLE.length; i++) {
              cRowTable = SAVES_CALCS_TABLE[i];
              if (parseFloat(cRowTable[8]) == parseFloat(cRowTable[9])) {
                  maxW = cRowTable[8] + '*';
              } else {
                  maxW = cRowTable[8];
              }
              if (!isNaN(parseFloat(cRowTable[1])))
                  itogo_po_stroke = parseFloat(Round2D(cRowTable[1], 3));
              if (!isNaN(parseFloat(cRowTable[3])))
                  itogo_po_stroke = itogo_po_stroke + parseFloat(Round2D(cRowTable[3], 3));
              if (!isNaN(parseFloat(cRowTable[4])))
                  itogo_po_stroke = itogo_po_stroke + parseFloat(Round2D(cRowTable[4], 3));
              if (!isNaN(parseFloat(cRowTable[2])))
                  itogo_po_stroke = itogo_po_stroke + parseFloat(Round2D(cRowTable[2], 3));

              tout = tout + '<tr>';
              tout = tout + '<td align=center><a href="" onclick="removerow(' + i + '); return false;"><img border=0 src="http://cpcr.ru/components/tarifcalc2/i/del.gif"></a></td>';
              tout = tout + '<td align=center>' + cRowTable[6] + '<nobr><big><big>&rarr;</big></big></nobr><br>' + cRowTable[7] + '</td>'; //маршрут
              tout = tout + '<td align=center>' + maxW + '</td>'; // макс вес
              tout = tout + '<td align=center>' + cRowTable[0] + '</td>'; // услуга
              tout = tout + '<td align=center>' + cRowTable[5] + '</td>'; // срок
              tout = tout + '<td align=center>' + cRowTable[1] + '</td>'; // тариф
              tout = tout + '<td align=center>' + cRowTable[3] + '</td>'; // Страховка
              tout = tout + '<td align=center>' + cRowTable[4] + '</td>'; // тариф за ценность
              tout = tout + '<td align=center>' + cRowTable[2] + '</td>'; // доп. услуги
              tout = tout + '<td>' + Round2D(itogo_po_stroke, 2) + '</td>'; // Итого
              tout = tout + '</tr>';
          }
          tout = tout + '</table>';
          tout = tout + '<br><table width=100%><tr><td><div style="border:1px solid #000;width:200px; padding:4px; text-align:center">&nbsp;&nbsp;&nbsp;&nbsp;<a class="LinkBlueSmall"  onclick=" document.saveddata.submit(); return false" href="">Печать расчета (xls)</a>&nbsp;&nbsp;&nbsp;&nbsp;</div></td></tr></table>';
          var submitout = "";
          for (var i = 0; i < SAVES_CALCS_TABLE.length; i++) {
              cRowTable = SAVES_CALCS_TABLE[i];
              submitout = submitout + '<input name="row[]" type="hidden" value="' + cRowTable[0] + '|' + cRowTable[1] + '|' + cRowTable[2] + '|' + cRowTable[3] + '|' + cRowTable[4] + '|' + cRowTable[5] + '|' + cRowTable[6] + '|' + cRowTable[7] + '|' + cRowTable[8] + '|' + cRowTable[9] + '"/>';
          }
          submitout = '<form name=saveddata method=post target=_blank action="http://cpcr.ru/components/excel/tarifc_xls.php">' + submitout + '</form>';
          document.getElementById("savedtable").innerHTML = tout + submitout;
      }
  }



  function GetResulttc2() {
      var Send_Weight;
      var oW;
      var G1size, G2size, G3size;
      var rW;
      var _cvfc = cvars_fromcity[2] + ', ' + cvars_fromcity[5];
//alert("_cvfc=" + _cvfc + ", cvars_fromcity.length="+cvars_fromcity.length);
      var _cvtc = cvars_tocity[2] + ', ' + cvars_tocity[5];
//alert("_cvtc=" + _cvtc + ", cvars_tocity.length="+cvars_tocity.length);

      if (cvars_fromcity.length<1 || cvars_fromcity[0] == '') {
          alert('Не задан пункт отправления');
          return false;
      }
      if (cvars_tocity.length<1 || cvars_tocity[0]=='') {
          alert('Не задан пункт назначения');
          return false;
      }

      // расчет и проверка обьемного веса, и корректности полей
      oW = 0;
      if (document.getElementById("G1")!=null && document.getElementById("G2")!=null && document.getElementById("G3")!=null)
      {     
            G1size = document.getElementById("G1").value;
            G1size = parseFloat(G1size);
            G2size = document.getElementById("G2").value;
            G2size = parseFloat(G2size);
            G3size = document.getElementById("G3").value;
            G3size = parseFloat(G3size);
            oW = (G1size * G2size * G3size) / 6000;
      }

      wstr = document.getElementById("Weight").value;
      wstr = wstr.replace(/,/, ".");
      rW = parseFloat(wstr);
      if ((isNaN(oW)) || (oW <= 0)) {
          oW = 0;
      }
      if (isNaN(rW) || (rW <= 0)) {
          alert("Укажите вес отправления.");
          rW = 0;
          return false;
      }

      if ((rW >= 10000)) {
          alert("Для расчета больших отправлений, пожалуйста обратитесь к менеджеру");
          rW = 0;
          return false;
      }

      if (oW > rW) {
          Send_Weight = oW;
      } else {
          Send_Weight = rW;
      }


      var AmountCheck = -1;
      if (document.getElementById("AmountCheck1")!=null && document.getElementById("AmountCheck1").checked) {
          AmountCheck = document.getElementById("AmountCheck1").value;
      }
      else if (document.getElementById("AmountCheck2")!=null && document.getElementById("AmountCheck2").checked) {
          AmountCheck = document.getElementById("AmountCheck2").value;
      }

      // окончание проверки
      // запрос на рассчет
      document.getElementById('tarifcalc-load-status-bar').innerHTML = '<img src="/cpcr/load.gif">';
      var req = new JsHttpRequest();
      req.onreadystatechange = function() {
          var cpcr_Price4GoodsItem=0;
          var ToCityName="";
          if (req.readyState == 4) {
              if (req.responseJS.error) {
                  document.getElementById("tarifcalc-error-bar").innerHTML = req.responseJS.error;
                  document.getElementById("tarifcalc-result-table").innerHTML = '';
                  debugprint("ОШИБКА:" + req.responseText);

              } else {
//alert("!!! onreadystatechange - OK");
                  document.getElementById("tarifcalc-error-bar").innerHTML = '';
                  debugprint(req.responseText);
                  currentcalcresult = Array();
                  for (var m = 0; m < req.responseJS.count; m++) {
                      currentcalcresult[m] = req.responseJS.result2[m];
                  }
                  if (document.getElementById("shippingsum")==null) // это простой расчет
                  {
                      ShowCResult(Send_Weight, oW, rW, _cvfc, _cvtc);   // рисует табличку и отображает стоимость
                  }
                  else  // это значит, что мы в корзине считаем
                  {
                      // только что успешна просчитана стоимость доставки для товара с индексом GoodsInfo4DeliveryIdx
                      cpcr_Price4GoodsItem = Round2D(currentcalcresult[0][1], 2);
//alert("GoodsInfo4DeliveryIdx=" +GoodsInfo4DeliveryIdx+ ", Price4Item=" + cpcr_Price4GoodsItem + ", Price4ItemQuan=" + cpcr_Price4GoodsItem*GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Quantity);
                      cpcr_TotalCost = cpcr_TotalCost + cpcr_Price4GoodsItem*GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Quantity;
                      GoodsInfo4DeliveryIdx = GoodsInfo4DeliveryIdx + 1;
                      document.getElementById('tarifcalc-load-progress').innerHTML = "<img src='/cpcr/load.gif'> Обработано <b>" + GoodsInfo4DeliveryIdx + "</b> из <b>" + GoodsInfo4Delivery.length + "</b>...";
                      if (GoodsInfo4DeliveryIdx<GoodsInfo4Delivery.length)  // надо еще рассчитать стоимости доставки для товаров
                      {
                          document.getElementById("Weight").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Weight;
                          document.getElementById("G1").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Length;
                          document.getElementById("G2").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Width;
                          document.getElementById("G3").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Height;
                          GetResulttc2();
                      }
                      else  // все просчитали, запишем результат расчета в поле и выведем кнопку для оформления заказа
                      {
                          document.getElementById("shippingsum").value = cpcr_TotalCost;
                          document.getElementById("shippingcity").value = _cvtc;
                          document.getElementById("shippingcomment").value = "Стоимость доставки из " + _cvfc + " в " + _cvtc + ": " + cpcr_TotalCost + " руб.";
                          document.getElementById("tarifcalc-result-table").innerHTML = "<br />Стоимость доставки из <b>" + _cvfc + "</b> в <b>" + _cvtc + "</b>: <b>" + cpcr_TotalCost + "</b> руб.";
                          document.getElementById('tarifcalc-load-progress').innerHTML = "";
                          show_divMODE("SUBMITbut", "block");
//alert("ok. shippingsum=" + cpcr_TotalCost);
                      }
                  }
              }
              document.getElementById('tarifcalc-load-status-bar').innerHTML = '';
          }
      }

      req.open(null, componentroottc2 + 'tarifcalc.php', true);
      req.send({
          to_select_country: cvars_tocity[9] + '|' + cvars_tocity[10],
          to_select_region: cvars_tocity[3] + '|' + cvars_tocity[4],
          to_Cities_Id: cvars_tocity[0] + '|' + cvars_tocity[1],
          to_Cities_name: cvars_tocity[2],
          from_select_country: cvars_fromcity[9] + '|' + cvars_fromcity[10],
          from_select_region: cvars_fromcity[3] + '|' + cvars_fromcity[4],
          from_Cities_Id: cvars_fromcity[0] + '|' + cvars_fromcity[1],
          from_Cities_name: cvars_fromcity[2],
          Weight: Send_Weight, // отсылаем максимум(вес,обьемный вес)
          Amount: gvlid("Amount"),
          AmountCheck: AmountCheck,
          SMS: gvlid_cb("tc1-Sms"),
          BeforeSignal: gvlid_cb("tc1-BeforeSignal"),
          DuesOrder: gvlid_cb("tc1-DuesOrder"),
          PlatType: gvlid_cb("tc1-PlatType"),
          SID: cvars_varsid[0]
      });
      return false;
  }


// вычисление стоимости доставки для почты России. Вообще, сюда мы попадаем только если есть товары
function cpcr_StartCalculation()
{
    GoodsInfo4DeliveryIdx = 0;
    cpcr_TotalCost=0;
    document.getElementById("tarifcalc-result-table").innerHTML="";
    if (GoodsInfo4DeliveryWrongDataGoodsID>0)
    {
        alert("Нельзя расчитать стоимость доставки, т.е. не для всех товаров задан вес и габариты")
        return false;
    }
    if (document.getElementById("shippingsum")==null || document.getElementById("Weight")==null || document.getElementById("G1")==null || document.getElementById("G2")==null || document.getElementById("G3")==null)
    {
        alert("Нельзя расчитать стоимость доставки, т.к. не определены все необходимые поля")
        return false;
    }
    show_divMODE("SUBMITbut", "none");
    document.getElementById("shippingsum").value=0;
    document.getElementById("Weight").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Weight;
    document.getElementById("G1").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Length;
    document.getElementById("G2").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Width;
    document.getElementById("G3").value = GoodsInfo4Delivery[GoodsInfo4DeliveryIdx].Height;
    GetResulttc2();    
    return false;
}


  // контроль суммы страхования
  function CheckSumtc2(d, k) {
      if ((k.value > 0) && (k.value < 500000)) {
          // 2 кнопки
          if (document.getElementById("AmountCheck1")!=null)
                document.getElementById("AmountCheck1").style.display = 'block';
          if (document.getElementById("AmountCheck2")!=null)
                document.getElementById("AmountCheck2").style.display = 'block';
          if (document.getElementById("paramins2txt")!=null)
                document.getElementById("paramins2txt").style.display = 'block';
      } else {
          if (k.value >= 500000) {
              //1 кнопка
              if (document.getElementById("AmountCheck1")!=null)
              {
                  document.getElementById("AmountCheck1").checked = true;
                  document.getElementById("AmountCheck1").style.display = 'block';
              }
              if (document.getElementById("AmountCheck2")!=null)
                  document.getElementById("AmountCheck2").style.display = 'none';
              if (document.getElementById("paramins2txt")!=null)
                  document.getElementById("paramins2txt").style.display = 'none';
          }
      }
  }

  // откыть-закрыть панель доп. параметров
  function SwapExtra() {
      if (document.getElementById("extraparams").style.display == 'block') {
          document.getElementById("extraparams").style.display = 'none';
          document.getElementById("swextra").innerHTML = 'показать';
          document.getElementById("swextrar").style.display = 'inline';
          document.getElementById("swextral").style.display = 'none';
      } else {
          document.getElementById("extraparams").style.display = 'block';
          document.getElementById("swextra").innerHTML = 'скрыть';
          document.getElementById("swextral").style.display = 'inline';
          document.getElementById("swextrar").style.display = 'none';
      }
  }

  // откыть-закрыть панель доп. параметров
  function SwapInfo(num) {
      if (num == 1) {
          document.getElementById('info11').style.display = 'block';
          document.getElementById('info12').style.display = 'none';
      } else {
          document.getElementById('info12').style.display = 'block';
          document.getElementById('info11').style.display = 'none';
      }
  }

  function ShowInfo2(num) {
      if (num == 1) {
          document.getElementById('info22').style.display = 'none';
          document.getElementById('info23').style.display = 'none';
          document.getElementById('info24').style.display = 'none';
          document.getElementById('info21').style.display = 'block';
      } else if (num == 2) {
          document.getElementById('info21').style.display = 'none';
          document.getElementById('info23').style.display = 'none';
          document.getElementById('info24').style.display = 'none';
          document.getElementById('info22').style.display = 'block';
      } else if (num == 3) {
          document.getElementById('info21').style.display = 'none';
          document.getElementById('info22').style.display = 'none';
          document.getElementById('info24').style.display = 'none';
          document.getElementById('info23').style.display = 'block';
      } else if (num == 4) {
          document.getElementById('info21').style.display = 'none';
          document.getElementById('info22').style.display = 'none';
          document.getElementById('info23').style.display = 'none';
          document.getElementById('info24').style.display = 'block';
      }
  }
  function HideInfo() {
      document.getElementById('info11').style.display = 'none';
      document.getElementById('info12').style.display = 'none';
  }

  function HideInfo2() {
      document.getElementById('info21').style.display = 'none';
      document.getElementById('info22').style.display = 'none';
      document.getElementById('info23').style.display = 'none';
      document.getElementById('info24').style.display = 'none';
  }

  // удалить ряд
  function removerow(id) {
      SAVES_CALCS_TABLE.splice(id, 1);
      UpdateSavedTable();
  }





      var componentrootfromcity = 'http://cpcr.ru/components/selectcitydepbyname/';
      var cvars_fromcity = Array();
      function Dep_List_Changefromcity(defcity) {
          dep_val = document.getElementById("Departamentfromcity").value;
          document.getElementById('Status2fromcity').innerHTML = '<img src="/cpcr/load.gif">';
          var reqfromcity = new JsHttpRequest();
          reqfromcity.onreadystatechange = function() {
              if (reqfromcity.readyState == 4) {
                  if (reqfromcity.responseJS.error) {
                      document.getElementById("DepCityContainerfromcity").innerHTML = '';
                  }
                  else {
                      document.getElementById("DepCityContainerfromcity").innerHTML = '<select id="DepartamentCityfromcity" name="DepartamentCityfromcity">' + reqfromcity.responseJS.deplist + '</select>';
                      if (defcity != '0') {
                          document.getElementById("DepartamentCityfromcity").value = defcity;
                      }
                  }
                  document.getElementById('Status2fromcity').innerHTML = '';
              }
          }
          reqfromcity.open(null, componentrootfromcity + 'filials.php', true);
          reqfromcity.send({ dep_value: dep_val });
      }

      function updatelocalvarfromcity(val) {
          cvars_fromcity = val.split("^"); // global
//alert("updatelocalvarfromcity: " + val);
      }

      function FindDepCityfromcity(findcity) {
          document.getElementById('StatusInfofromcity').innerHTML = "";
          document.getElementById("DepCityContainerfromcity").innerHTML = ""
          document.getElementById('Status2fromcity').innerHTML = '<img src="/cpcr/load.gif">';
          var reqfromcity = new JsHttpRequest();
          reqfromcity.onreadystatechange = function() {
              if (reqfromcity.readyState == 4) {
                  if (reqfromcity.responseJS.error) {
                      document.getElementById("DepCityContainerfromcity").innerHTML = '';
                  }
                  else {
                      document.getElementById("DepCityContainerfromcity").innerHTML = '<select onchange="updatelocalvarfromcity(this.value)" name="fromcity">' + reqfromcity.responseJS.citieslist + '</select>';
                      if (reqfromcity.responseJS.citieslist) {
                          document.getElementById('StatusInfofromcity').innerHTML = 'Найдены варианты <i>(выберите подходящий):</i>';
                          updatelocalvarfromcity(reqfromcity.responseJS.first);
                      } else {
                          document.getElementById('StatusInfofromcity').innerHTML = '';
                          document.getElementById("DepCityContainerfromcity").innerHTML = '<span style="color:#f00">Город не найден</span>';
                      }
                  }
                  document.getElementById('Status2fromcity').innerHTML = '';
              }
          }
          reqfromcity.open(null, componentrootfromcity + 'getcitybyname.php', true);
          reqfromcity.send({ findcity: findcity });
          return false;
      }

      function Checkbuttonfromcity(d) {
          if ((d.which == 13) || (d.keyCode == 13)) {
              FindDepCityfromcity(document.getElementById("StrCityFindfromcity").value);
          }
      }





      var componentroottocity = 'http://cpcr.ru/components/selectcitydepbyname/'; var cvars_tocity = Array();
      function Dep_List_Changetocity(defcity) {
          dep_val = document.getElementById("Departamenttocity").value;
          document.getElementById('Status2tocity').innerHTML = '<img src="/cpcr/load.gif">';
          var reqtocity = new JsHttpRequest();
          reqtocity.onreadystatechange = function() {
              if (reqtocity.readyState == 4) {
                  if (reqtocity.responseJS.error) {
                      document.getElementById("DepCityContainertocity").innerHTML = '';
                  }
                  else {
                      document.getElementById("DepCityContainertocity").innerHTML = '<select id="DepartamentCitytocity" name="DepartamentCitytocity">' + reqtocity.responseJS.deplist + '</select>';
                      if (defcity != '0') {
                          document.getElementById("DepartamentCitytocity").value = defcity;
                      }
                  }
                  document.getElementById('Status2tocity').innerHTML = '';
              }
          }
          reqtocity.open(null, componentroottocity + 'filials.php', true);
          reqtocity.send({ dep_value: dep_val });
      }

      function updatelocalvartocity(val) {
          cvars_tocity = val.split("^"); // global
          
          if (document.getElementById("tarifcalc-result-table")!=null)
                document.getElementById("tarifcalc-result-table").innerHTML = "";          
          if (document.getElementById("shippingsum")!=null)
                document.getElementById("shippingsum").value = 0;
          show_divMODE("SUBMITbut", "none");          
      }

      function FindDepCitytocity(findcity) {
          document.getElementById('StatusInfotocity').innerHTML = "";
          document.getElementById("DepCityContainertocity").innerHTML = ""
          document.getElementById('Status2tocity').innerHTML = '<img src="/cpcr/load.gif">';
          var reqtocity = new JsHttpRequest();
          reqtocity.onreadystatechange = function() {
              if (reqtocity.readyState == 4) {
                  if (reqtocity.responseJS.error) {
                      document.getElementById("DepCityContainertocity").innerHTML = '';
                  }
                  else {
                      document.getElementById("DepCityContainertocity").innerHTML = '<select onchange="updatelocalvartocity(this.value)" id="tocity" name="tocity">' + reqtocity.responseJS.citieslist + '</select>';
                      if (reqtocity.responseJS.citieslist) {
                          document.getElementById('StatusInfotocity').innerHTML = 'Найдены варианты <i>(выберите подходящий):</i>';
                          updatelocalvartocity(reqtocity.responseJS.first);
                      } else {
                          document.getElementById('StatusInfotocity').innerHTML = '';
                          document.getElementById("DepCityContainertocity").innerHTML = '<span style="color:#f00">Город не найден</span>';
                      }
                  }
                  document.getElementById('Status2tocity').innerHTML = '';
              }
          }
          reqtocity.open(null, componentroottocity + 'getcitybyname.php', true);
          reqtocity.send({ findcity: findcity });
          return false;
      }

      function Checkbuttontocity(d) {
          if ((d.which == 13) || (d.keyCode == 13)) {
              FindDepCitytocity(document.getElementById("StrCityFindtocity").value);
          }
      }


    // залогинивание для КНС
    function LoginKNS()
    {
        cvars_varsid[0] = "4C51BFCEA3F14C41929B3E68C58DB291";
        cvars_varsid[1] = "КНС (ООО)";
    }

    function GetSidvarsid(Contract, Pass)
    {
        var SidChekvarsid = document.getElementById("SidChekvarsid");
        if (SidChekvarsid!=null && SidChekvarsid.checked == false) {
            cvars_varsid[0] = 0;
            cvars_varsid[1] = '';
            if (document.getElementById("SidInfoContainervarsid")!=null)
                document.getElementById("SidInfoContainervarsid").innerHTML = 'Авторизоваться';
            return true;
        }
        var reqvarsid = new JsHttpRequest();
        if (document.getElementById("ErrorSidInfoContainervarsid")!=null)
            document.getElementById("SidInfoStatusvarsid").innerHTML = '<img src="/cpcr/load.gif">';
        reqvarsid.onreadystatechange = function() {
            if (reqvarsid.readyState == 4) {
                if (reqvarsid.responseJS.error) {
                    if (document.getElementById("ErrorSidInfoContainervarsid")!=null)
                        document.getElementById("ErrorSidInfoContainervarsid").innerHTML = '<span style="color:red">' + reqvarsid.responseJS.error + '</span>';
                    if (document.getElementById("SidInfoContainervarsid")!=null)
                        document.getElementById("SidInfoContainervarsid").innerHTML = 'Авторизоваться';
                    cvars_varsid[0] = 0;
                    cvars_varsid[1] = '';
                    if (document.getElementById("SidInfoStatusvarsid")!=null)
                        document.getElementById("SidInfoStatusvarsid").innerHTML = '';
                    if (SidChekvarsid!=null)
                        SidChekvarsid.checked = false;

                } else {
                    cvars_varsid[0] = reqvarsid.responseJS.SID;
                    cvars_varsid[1] = reqvarsid.responseJS.EXTRAINFO;
                    //alert("cvars_varsid[0]='" + cvars_varsid[0] + "', cvars_varsid[1]='" + cvars_varsid[1] + "'");
                    if (document.getElementById("SidInfoContainervarsid")!=null)
                        document.getElementById("SidInfoContainervarsid").innerHTML = reqvarsid.responseJS.EXTRAINFO;
                    if (document.getElementById("ErrorSidInfoContainervarsid")!=null)
                        document.getElementById("ErrorSidInfoContainervarsid").innerHTML = '';
                    if (document.getElementById("SidInfoStatusvarsid")!=null)
                        document.getElementById("SidInfoStatusvarsid").innerHTML = '';
                    if (SidChekvarsid!=null)
                        SidChekvarsid.checked = true;
                }
            }
        }
        reqvarsid.open(null, componentrootvarsid + 'getsid.php', true);
        reqvarsid.send({ c: Contract, p: Pass });
        return false;
    }

    function Checkbuttonvarsid(d) {
        if ((d.which == 13) || (d.keyCode == 13)) {
            // FindDepCityvarsid( document.getElementById("StrCityFindvarsid").value);
        }
    }
