function clearSearch()
{
   document.frmsearch.tfSearchTxt.value = "";
   document.frmsearch.tfSearchTxt.style.textAlign = "left";
}

function numberMainRubric(subRubricId)
{
   for (i = 0; i < aSubRubrics.length; i++)
   {
      for (j = 0; j < aSubRubrics[i].length; j++)
      {
	 parts = aSubRubrics[i][j].split("|");
         if (parts[0] == subRubricId) return i;
      }
   }

   return 0;
}

function viewSubRubrics(theSubRubric)
{
   selectedMain = document.frm.cbMainRubrics.selectedIndex

   selectNum = 0

   var oSubRubricList = document.forms["frm"].elements["cbSubRubrics"]
   var oSubRubricListCnt = aSubRubrics[selectedMain].length
   oSubRubricList.length = 0
   for (i = 0; i < oSubRubricListCnt; i++)
   {
      aParts = aSubRubrics[selectedMain][i].split("|")
      sText = aParts[1]
      sValue = aParts[0]

      if (theSubRubric == parseInt(sValue)) selectNum = i;

      if (document.createElement)
      {
         var newRubricListOption = document.createElement("OPTION");
         newRubricListOption.text = sText;
         newRubricListOption.value = sValue;
         (oSubRubricList.options.add) ? oSubRubricList.options.add(newRubricListOption) : oRubricList.add(newRubricListOption, null);
      }
      else
      {
         oSubRubricList.options[i] = new Option(sText, sValue, false, false)
      }
   }

   document.frm.cbSubRubrics[selectNum].selected = true
}

function clearAddFirmForm(numPacket)
{
   switch (numPacket)
   {
      case 1:
         cntEMailCell = document.all.emails.rows.length;
         for (i = 0; i < cntEMailCell; i++)
	     document.all.emails.deleteRow(0);

         cntWwwCell = document.all.wwws.rows.length;
         for (i = 0; i < cntWwwCell; i++)
            document.all.wwws.deleteRow(0);

         document.all.hdnWwwCnt.value = 0;
         document.all.hdnEMailCnt.value = 0;

      case 2:
         document.all.tbEMail.value = "";
         document.all.tbWWW.value = "";
         document.all.tfDescription.value = "";

      case 3:
         cntPhoneCell = document.all.phones.rows.length;
         for (i = 0; i < cntPhoneCell; i++)
	       document.all.phones.deleteRow(0);

         cntRubricCell = document.all.rubrics.rows.length;
         for (i = 0; i < cntRubricCell; i++)
            document.all.rubrics.deleteRow(0);

      case 4:
         document.all.hdnPhoneCnt.value = 0;
         document.all.hdnRubricCnt.value = 0;
         document.all.cbMainRubrics.selectedIndex = 0;
         document.all.tbName.value = "";
         document.all.tbAddressCity.value = "м. Київ";
         document.all.tbAddressAnother.value = "";
         document.all.tfPhoneNum.value = "";
         document.all.tfPhoneCode.value = "044";
         document.all.tfLicence.value = "";
         document.all.tfAddressIndex.value = "";
         viewSubRubrics();
   }
}

function checkFirm()
{
   if ( document.frm.tbName.value.length == 0 )
   {
      document.frm.tbName.focus()
      alert('Поле Назва порожнє!');
      return false;
   }

   if ( document.frm.tfNameRu.value.length == 0 )
   {
      document.frm.tfNameRu.focus()
      alert('Поле із російською назвою порожнє!');
      return false;
   }

    if (document.frm.tfContactEMail.value.length > 0) {
        var pattern = /^[\w\-\.]{1,100}\@[\w\-\.]{1,100}\.\w{2,5}$/i;
        if ( pattern.exec(document.frm.tfContactEMail.value) == null ){
            document.frm.tfContactEMail.focus()
            alert('Поле <Контактний E-Mail> містить некоректний адрес!');
            return false;
        }
    }

   pattern = /^\d{1,5}$/;
   var tfAddressIndex = $('#tfAddressIndex');
   if ( pattern.exec(tfAddressIndex.val()) == null ) {
      tfAddressIndex.focus()
      alert('Індекс повинен містити лише цифри!');
      return false;
   }

   var tfAddressCity = $('#tfAddressCity');
   if ( tfAddressCity.val().length == 0 ) {
      tfAddressCity.focus()
      alert('Поле Населений пункт порожнє!');
      return false;
   }

   var tfAddressAnother = $('#tfAddressAnother');
   if ( tfAddressAnother.val().length == 0 ) {
      tfAddressAnother.focus()
      alert('Поле Вулиця та ін. порожнє!');
      return false;
   }

   pattern = /^\d{1,5}$/;
   var tfPhoneCode = $('#tfPhoneCode');
   if ( pattern.exec(tfPhoneCode.val()) == null ) {
      tfPhoneCode.focus()
      alert('Код міста у номері телефона повинен містити лише цифри!');
      return false;
   }

   pattern = /^\d{1,8}$/;
   var tfPhoneNum = $('#tfPhoneNum');
   if ( pattern.exec(tfPhoneNum.val()) == null ) {
      tfPhoneNum.focus()
      alert('Номер телефона повинен містити лише цифри!');
      return false;
   }

   aParts = aSubRubrics[document.frm.cbMainRubrics.selectedIndex][document.frm.cbSubRubrics.selectedIndex].split("|")
   if (aParts[2] == 1 && document.frm.tfLicence.value.length == 0)
   {
      document.frm.tfLicence.focus()
      alert("Для того, щоб зареєструватись у вказаній Вами рубриці, Ви обов'язково повинні вказати інформацію про Вашу ліцензію у відповідному полі реєстраційної форми!");
      return false;
   }

   return true;
}

function showMap(nameFirm, pathImg)
{
   win = open("","","scrollbars=no,width=400,height=300");
   win.document.open();
   win.document.write("<head><title>Схематична карта \"Як нас знайти!\" для підприємства "+nameFirm+ "</title></head>");
   win.document.write("<body><center>Схематична карта \"Як нас знайти!\" для підприємства <b>"+nameFirm+"</b><br><img src='downloads/map/"+pathImg+"'></center></body>");
   win.document.close();
}

function showExamplePacket(titlePacket, nameImg)
{
   win = open("","","scrollbars=no,width=1000,height=500");
   win.document.open();
   win.document.write("<head><title>Приклад пакету "+titlePacket+ "</title></head>");
   win.document.write("<body><center>Приклад пакету <b>\""+titlePacket+ "\"</b><br><img src='/images/"+nameImg+"'></center></body>");
   win.document.close();
   return false;
}

// === Управление телефонами

function addPhone(limitPhone, packet)
{
   var numPhone = 0, i = 0, thePhone;
   var cntPhone = document.getElementById("cntPhone").value;
   var phonesDescSize = [0, 12, 12, 8];
   var phonesDescMLen = [0, 200, 200, 8];

   cntPhone++;

   if ( cntPhone > limitPhone ) {
      alert("Ви можете додати не більше " + (limitPhone + 1) + " номерів!");
      return;
   }

   // перебор свободных номеров для имен полей Phone
   while ( ++i <= cntPhone) {
      if (document.getElementById("idPhoneNum" + i) == null) {
        numPhone = i;
        break;
      }
   }

   currentRow = document.all.phones.rows.length;
   document.all.phones.insertRow(currentRow);
   document.all.phones.rows[currentRow].id = "phone"+numPhone;

   document.all.phones.rows[currentRow].insertCell(0);
   document.all.phones.rows[currentRow].insertCell(1);
   document.all.phones.rows[currentRow].insertCell(2);
   document.all.phones.rows[currentRow].insertCell(3);
   document.all.phones.rows[currentRow].insertCell(4);

   document.all.phones.rows[currentRow].cells[0].innerHTML="<span class='text13px'></span>";
   document.all.phones.rows[currentRow].cells[1].innerHTML="<input type='text' name='tfPhoneCode"+numPhone+"' id='idPhoneCode"+numPhone+"' size='5' maxlength='5' class='textfield' value='044'>";
   document.all.phones.rows[currentRow].cells[2].innerHTML="<input type='text' name='tfPhoneNum"+numPhone+"' id='idPhoneNum"+numPhone+"' size='9' maxlength='9' class='textfield' value=''>";
   document.all.phones.rows[currentRow].cells[3].innerHTML="<input type='text' name='tfPhoneDesc"+numPhone+"' id='idPhoneDesc"+numPhone+"' size='"+phonesDescSize[packet]+"' maxlength='"+phonesDescMLen[packet]+"' class='textfield' value=''>";
   document.all.phones.rows[currentRow].cells[4].innerHTML="<a href=javascript:delPhone("+numPhone+")> <img src='/images/telephone_delete.gif' alt='Зайвий' title='Зайвий' /></a>";

   document.getElementById("cntPhone").value = cntPhone;
}

function delPhone(thePhone)
{
   var theCellPhone;
   var cntCells = document.all.phones.rows.length;
   var cntPhone = parseInt(document.getElementById("cntPhone").value);

   for ( var i = 1; i <= cntCells; i++ )
   {
     theCellPhone = eval("document.all.phones.rows[" + (i-1) + "].id");
     if ( theCellPhone == "phone" + thePhone )
     {
       document.all.phones.deleteRow(i - 1);
       document.getElementById("cntPhone").value = --cntPhone;
       break;
     }
   }
}

// === Управление EMail

function addEMail(limitEMail)
{
   var numEMail = 0, i = 0, theEMail;
   var cntEMail = document.getElementById("cntEMail").value;

   cntEMail++;

   if ( cntEMail > limitEMail )
   {
      alert("Ви можете додати не більше " + (limitEMail + 1) + " email-ів!");
      return;
   }

   // перебор свободных номеров для имен полей EMail
   while ( ++i <= cntEMail)
   {
      if (document.getElementById("idEMail" + i) == null)
      {
        numEMail = i;
        break;
      }
   }

   currentRow = document.all.emails.rows.length;
   document.all.emails.insertRow(currentRow);
   document.all.emails.rows[currentRow].id = "email"+numEMail;

   document.all.emails.rows[currentRow].insertCell(0);
   document.all.emails.rows[currentRow].insertCell(1);

   document.all.emails.rows[currentRow].cells[0].innerHTML="<input type='text' name='tfEMail"+numEMail+"' id='idEMail"+numEMail+"' size='35' maxlength='80' class='textfield' value=''>";
   document.all.emails.rows[currentRow].cells[1].innerHTML="&nbsp; <a href=javascript:delEMail("+numEMail+")><img src='/images/email_del.gif' alt='зайвий' /></a>";

   document.getElementById("cntEMail").value = cntEMail;
}

function delEMail(theEMail)
{
   var theCellEMail;
   var cntCells = document.all.emails.rows.length;
   var cntEMail = parseInt(document.getElementById("cntEMail").value);

   for ( var i = 1; i <= cntCells; i++ )
   {
     theCellEMail = eval("document.all.emails.rows[" + (i-1) + "].id");
     if ( theCellEMail == "email" + theEMail )
     {
       document.all.emails.deleteRow(i - 1);
       document.getElementById("cntEMail").value = --cntEMail;
       break;
     }
   }
}

// === Управление Www

function addWww(limitWww)
{
   var numWww = 0, i = 0, theWww;
   var cntWww = document.getElementById("cntWww").value;

   cntWww++;

   if ( cntWww > limitWww )
   {
      alert("Ви можете додати не більше " + (limitWww + 1) + " web-адрес!");
      return;
   }

   // перебор свободных номеров для имен полей Www
   while ( ++i <= cntWww)
   {
      if (document.getElementById("idWww" + i) == null)
      {
        numWww = i;
        break;
      }
   }

   currentRow = document.all.www.rows.length;
   document.all.www.insertRow(currentRow);
   document.all.www.rows[currentRow].id = "www"+numWww;

   document.all.www.rows[currentRow].insertCell(0);
   document.all.www.rows[currentRow].insertCell(1);

   document.all.www.rows[currentRow].cells[0].innerHTML="<input type='text' name='tfWww"+numWww+"' id='idWww"+numWww+"' size='35' maxlength='80' class='textfield' value='' />";
   document.all.www.rows[currentRow].cells[1].innerHTML="&nbsp; <a href=javascript:delWww("+numWww+")><img src='/images/server_del.gif' alt='зайва' /></a>";

   document.getElementById("cntWww").value = cntWww;
}

function delWww(theWww)
{
   var theCellWww;
   var cntCells = document.all.www.rows.length;
   var cntWww = parseInt(document.getElementById("cntWww").value);

   for ( var i = 1; i <= cntCells; i++ )
   {
     theCellWww = eval("document.all.www.rows[" + (i-1) + "].id");
     if ( theCellWww == "www" + theWww )
     {
       document.all.www.deleteRow(i - 1);
       document.getElementById("cntWww").value = --cntWww;
       break;
     }
   }
}

function sizeTextfield(type, limit, name)
{
   var objTf, objCalc;

   switch(type)
   {
     case 1:
       objTf = document.getElementById("desc");
       objCalc = document.getElementById("cntDescription");
     break;

     case 2:
       objTf = document.getElementById("licence");
       objCalc = document.getElementById("cntLicence");
     break;

     case 3:
       objTf = document.getElementById("tf"+name);
       objCalc = document.getElementById("cnt"+name);
     break;
     
   }

   len = objTf.value.length;
   if (len > limit) objTf.value = objTf.value.substr(0, limit);
   else objCalc.value = limit - len;
}

function addRubric(limitRubric)
{
   var cntRubric = parseInt(document.getElementById("cntRubric").value);
   var mainRubrics = document.getElementById("mainRubrics");
   var subRubrics = document.getElementById("subRubrics");
   var i = 0, theRubric, numRubric = 0;
   cntRubric++;

   if ( cntRubric > limitRubric )
   {
      alert("Ви можете додати підприємство тільки у " + limitRubric + " підрубрики!");
      return;
   }

   // добавление не повторяющийся рубрики
   var selectedRubric = subRubrics.options[subRubrics.selectedIndex].value;

   while ( ++i <= limitRubric)
   {
      if (document.getElementById("idRubric" + i) != null)
      {
        theRubric = document.getElementById("idRubric" + i).value;
        if (theRubric == selectedRubric)
        {
	      alert("Підприємство вже зареєстроване в цій рубриці!");
          return;
        }
      }
   }

   var textMainRubric = mainRubrics.options[mainRubrics.selectedIndex].text;
   var textSubRubric = subRubrics.options[subRubrics.selectedIndex].text;

   // перебор свободных номеров для имен полей рубрик
   i = 0;
   while ( ++i <= cntRubric )
   {
     if (document.getElementById("idRubric" + i) == null)
     {
       numRubric = i;
       break;
     }
   }

   currentRow = document.all.rubrics.rows.length;
   document.all.rubrics.insertRow(currentRow);
   document.all.rubrics.rows[currentRow].id = "rubric"+numRubric;

   document.all.rubrics.rows[currentRow].insertCell(0);
   document.all.rubrics.rows[currentRow].insertCell(1);

   document.all.rubrics.rows[currentRow].cells[0].innerHTML="<input type='edit' name=\"tfRubricName"+numRubric+"\" value=\""+textMainRubric+"&raquo;"+textSubRubric+"\" size='70' class='tfreadonly' readonly='1'> <input type='hidden' name='hdnRubric"+numRubric+"' id='idRubric"+numRubric+"' value='"+selectedRubric+"'>";
   document.all.rubrics.rows[currentRow].cells[1].innerHTML="&nbsp; <a href=javascript:delRubric("+numRubric+")><img src='/images/folder_del.gif' alt='зайва' /></a>";

   document.getElementById("cntRubric").value = cntRubric;
}

function delRubric(theRubric)
{
   cntRubricCell = document.all.rubrics.rows.length;

   if ( cntRubricCell > 0 )
   {
      cntRubric = document.frm.hdnRubricCnt.value;
      for ( i = 0; i < cntRubric; i++ )
      {
         tmpRubricNum = "document.all.rubrics.rows["+i+"].id";
         numRubric = eval(tmpRubricNum);
         if ( numRubric == "rubric" + theRubric )
         {
            document.all.rubrics.deleteRow(i);
            cntRubric--;
            document.frm.hdnRubricCnt.value = cntRubric;
            break;
         }
      }
   }
}

function addRubricFields(limitRubric)
{
   cntRubric = document.all.hdnRubricCnt.value;
   cntRubric++;

   if ( cntRubric > limitRubric )
   {
      alert("Ви можете додати підприємство тільки у " + limitRubric + " підрубрики!");
      return;
   }

   currentRow = document.all.rubrics.rows.length;

   // перебор свободных номеров для имен полей рубрик - hdnRubricI
   i = 1;
   while ( i <= cntRubric)
   {
      tmpRubricNum = "document.all.hdnRubric"+i;
      objNumRubric = eval(tmpRubricNum);

      if ( objNumRubric == null )
      {
	    numRubric = i;
	    break;
      }

      i++;
   }

   document.all.rubrics.insertRow(currentRow);
   document.all.rubrics.rows[currentRow].id = "rubric"+numRubric;

   document.all.rubrics.rows[currentRow].insertCell(0);
   document.all.rubrics.rows[currentRow].insertCell(1);

   document.all.rubrics.rows[currentRow].cells[0].innerHTML="<input type='edit' value=\"\" size='70' name=\"tfRubricName"+numRubric+"\" class='tfreadonly' readonly> <input type='hidden' name='hdnRubric"+numRubric+"' value=''>";
   document.all.rubrics.rows[currentRow].cells[1].innerHTML="&nbsp; <a href=javascript:delRubric("+numRubric+")>зайва</a>";

   document.all.hdnRubricCnt.value = cntRubric;
}

// === Проверка полей

function checkBaseField()
{
   var tfName = $('#firmName');
   if ( tfName.val().length == 0 ) {
      tfName.focus()
      alert('Поле Назва порожнє!');
      return false;
   }

   pattern = /^\d{1,5}$/;
   var tfAddressIndex = $('#tfAddressIndex');
   if ( pattern.exec(tfAddressIndex.val()) == null ) {
      tfAddressIndex.focus()
      alert('Індекс повинен містити лише цифри!');
      return false;
   }

   var tfAddressCity = $('#tfAddressCity');
   if ( tfAddressCity.val().length == 0 ) {
      tfAddressCity.focus()
      alert('Поле Населений пункт порожнє!');
      return false;
   }

   var tfAddressAnother = $('#tfAddressCity');
   if ( tfAddressAnother.val().length == 0 ) {
      tfAddressAnother.focus()
      alert('Поле Вулиця та ін. порожнє!');
      return false;
   }

   pattern = /^\d{1,5}$/;
   var tfPhoneCode = $('#tfPhoneCode');
   if ( pattern.exec(tfPhoneCode.val()) == null ) {
      tfPhoneCode.focus()
      alert('Код міста у номері телефона повинен містити лише цифри!');
      return false;
   }

   pattern = /^\d{1,8}$/;
   var tfPhoneNum = $('#tfPhoneNum');
   if ( pattern.exec(tfPhoneNum.val()) == null ) {
      tfPhoneNum.focus()
      alert('Номер телефона повинен містити лише цифри!');
      return false;
   }

   return true;
}

function checkPhoneRubricField(maxPhone, maxRubric)
{
   var i = 1, numPhone, cntRubric;

   while (i <= maxPhone)
   {
      tmpPhoneNum = "document.all.tfPhoneNum"+i;
      objPhoneNum = eval(tmpPhoneNum);

      if ( objPhoneNum != null )
      {
         tmpPhoneCode = "document.all.tfPhoneCode"+i;
         objPhoneCode = eval(tmpPhoneCode);

         pattern = /^\d{1,5}$/;
         codePhone = objPhoneCode.value;
         if ( pattern.exec(codePhone) == null )
         {
            objPhoneCode.focus()
            alert('Код міста у номері телефона повинен містити лише цифри!');
            return false;
         }

         pattern = /^\d{1,8}$/;
         numPhone = objPhoneNum.value;
         if ( pattern.exec(numPhone) == null )
         {
            objPhoneNum.focus()
            alert('Номер телефона повинен містити лише цифри!');
            return false;
         }
      }
      i++;
   }

   i = 1;
   cntRubric = 0;
   while (i <= maxRubric)
   {
      tmpRubricId = "document.all.hdnRubric"+i;
      objRubricId = eval(tmpRubricId);

      if ( objRubricId == null ) cntRubric++;
      i++;
   }

   if ( cntRubric == maxRubric )
   {
      document.all.cbSubRubrics.focus()
      alert('Необхідно вибрати хоча б одну рубрику!');
      return false;
   }

   return true;
}

function checkForm(maxPhone, maxRubric)
{
   var res1, res2, res3, res4;

   res1 = checkBaseField();

   if ( res1 == true ) {
      res2 = checkPhoneRubricField(maxPhone, maxRubric);

      if (res2 == true) {
        res3 = checkEmails();
        res4 = checkRusValues();
        return res1 && res2 && res3 && res4;
      }
   }
   else return res1;
}

function checkRusValues() {
    var tfNameRus = $('#firmNameRu');
    if ( tfNameRus.val().length == 0 ) {
        tfNameRus.focus()
        alert('Поле Назва (рус.) порожнє!');
        return false;
    }

    return true;
}

function checkEmails() {
    var pattern = /^[\w\-\.\_]{1,100}\@[\w\-\.]{1,100}\.\w{2,10}$/;

    var tfEmail = $('#tfEmail');
    if ( pattern.exec(tfEmail.val()) == null ) {
        tfEmail.focus()
        alert('Поле E-Mail містить некоректний адрес!');
        return false;
    }

    return true;
}

function payTypeField(level1, level2)
{
   switch (level1)
   {
      case 1:
        document.getElementById('payTypeEMail').checked = true;
        document.getElementById('payTypeAddress').checked = false;
        document.getElementById('payTypeWm').checked = false;
        disablePayType(2);

        switch(level2)
        {
          case 1:
            document.getElementById('emailForm').checked = true;
          break;

          case 2:
            document.getElementById('emailOther').checked = true;
            document.frm.tfOrderEMail.focus();
          break;
        };
      break;

      case 2:
        document.getElementById('payTypeEMail').checked = false;
        document.getElementById('payTypeAddress').checked = true;
        document.getElementById('payTypeWm').checked = false;
        disablePayType(1);

        switch(level2) {
          case 1:
            document.getElementById('addressForm').checked = true;
          break;

          case 2:
            document.getElementById('addressOther').checked = true;
            document.frm.tfOrderAddress.focus();
          break;
        };
      break;

      case 3:
          document.getElementById('payTypeEMail').checked = false;
          document.getElementById('payTypeAddress').checked = false;
          document.getElementById('payTypeWm').checked = true;
          disablePayType(1);
          disablePayType(2);
          break;
   }
}

function disablePayType(mode)
{
  switch(mode)
  {
    case 1:
      document.frm.rbEMailType[0].checked = false;
      document.frm.rbEMailType[1].checked = false;
    break;

    case 2:
      document.frm.rbAddressType[0].checked = false;
      document.frm.rbAddressType[1].checked = false;
    break;
  }
}

function checkOrder()
{
  var addressOther = document.getElementById('addressOther');
  /*var emailOther = document.getElementById('emailOther');

  if (emailOther.checked == true)
  {
    var email = document.frm.tfOrderEMail;
    var pattern = /^[\w\-\.\_]{1,100}\@[\w\-\.]{1,100}\.\w{2,5}$/i;

    if ( pattern.exec(email.value) == null )
    {
      email.focus()
      alert('Поле E-Mail містить некоректний адрес!');
      return false;
    }
  }*/

  if (addressOther.checked == true && document.frm.tfOrderAddress.value.length == 0)
  {
    document.frm.tfOrderAddress.focus();
    alert("Введіть адрес.");
    return false;
  }

  return true;
}

// *** show thumbnail ***

var offsetFromMouse = [15, 25];
var timerLoad = setInterval(startAnimate,20);
var pos = 0;
var dir = 2;
var len = 0;
var defaultImageHeight = 40;
var defaultImageWidth = 40;

function showThumb(path, title, width, height, obj)
{
  width += 30;
  height += 50;

  defaultImageWidth = width;
  defaultImageHeight = height;

  obj.onmousemove = followMouse;

  boxHtml = '<div class="borderPreview" style="width:' + width + 'px;height:' + height + 'px"><div id="boxLoader"><div id="loader"><div align="center">Завантажується ...</div><div id="bgLoader"><div id="progress"> </div></div></div></div>';
  boxHtml = boxHtml + '<h2>' + ' ' + title + '</h2>'

  boxHtml = boxHtml + '<div class="tempPreview"><img onload="javascript:stopAnimate();" src="' + path + '" border="0"></div>';
  boxHtml = boxHtml + '</div>';

  thumb().innerHTML = boxHtml;
  thumbStyle().display="block";
  obj.onmouseout = hideThumb;
}

function hideThumb()
{
  thumbStyle().display= "none";
  thumbStyle().left="-500px"
}

function followMouse(e){

	var x = offsetFromMouse[0];
	var y = offsetFromMouse[1];

	var boxWidth = document.all ? objBody().scrollLeft + objBody().clientWidth : pageXOffset + window.innerWidth - 15;
	var boxHeight = document.all ? Math.min(objBody().scrollHeight, objBody().clientHeight) : window.innerHeight;

	if (typeof e != "undefined")
    {
	  if ( boxWidth - e.pageX < defaultImageWidth + 2 * offsetFromMouse[0]) x = e.pageX - x - defaultImageWidth;
	  else x += e.pageX;

	  if ( boxHeight - e.pageY < defaultImageHeight + 2 * offsetFromMouse[1]) y += e.pageY - Math.max(0,(2 * offsetFromMouse[1] + defaultImageHeight + e.pageY - boxHeight - objBody().scrollTop));
	  else y += e.pageY;
	}
    else if (typeof window.event != "undefined")
    {
	  if ( boxWidth - event.clientX < defaultImageWidth + 2 * offsetFromMouse[0]) x = event.clientX + objBody().scrollLeft - x - defaultImageWidth;
	  else x += objBody().scrollLeft + event.clientX;

      if ( boxHeight - event.clientY < (defaultImageHeight + 2 * offsetFromMouse[1]) ) y += event.clientY + objBody().scrollTop - Math.max(0,(2 * offsetFromMouse[1] + defaultImageHeight + event.clientY - boxHeight));
	  else y += objBody().scrollTop + event.clientY;
	}
	thumbStyle().left = x + "px";
	thumbStyle().top = y + "px";
}

function objBody()
{
  return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function thumbStyle()
{
  if (document.getElementById) return document.getElementById("divPreview").style;
}

function thumb()
{
  if (document.getElementById) return document.getElementById("divPreview");
}

function startAnimate()
{
  var progressBar = document.getElementById('progress');
  if(progressBar != null)
  {
    if (pos==0) len += dir;
    if (len>32 || pos>79) pos += dir;
    if (pos>79) len -= dir;
    if (pos>79 && len==0) pos=0;
    progressBar.style.left = pos;
    progressBar.style.width = len;
  }
}

function stopAnimate()
{
  clearInterval(timerLoad);
  var elLoader = document.getElementById('boxLoader');
  elLoader.style.display = 'none';
  elLoader.style.visibility = 'hidden';
  var timerLoad = setInterval(startAnimate, 60);
}

function checkAgent()
{
  if ( document.frmReg.tfLoginReg.value.length == 0 )
  {
    document.frmReg.tfLoginReg.style.backgroundColor = "#FFCCCC";
    document.frmReg.tfLoginReg.focus()
    alert('Поле Логін порожнє!');
    return false;
  }

  pattern = /^[\w\-\.\_]{1,20}\@[\w\-\.]{2,20}\.\w{2,3}$/i;
  email = document.frmReg.tfEMail.value;
  if ( pattern.exec(email) == null )
  {
    document.frmReg.tfEMail.style.backgroundColor = "#FFCCCC";
    document.frmReg.tfEMail.focus()
    alert('Поле E-Mail містить некоректний адрес!');
    return false;
  }

  if ( existAgent() == 1 )
  {
    alert('Агент з таким логіном чи EMail вже є!');
    return false;
  }

  pattern = /^U\d{12,}$/i;
  wm = document.frmReg.tfWm.value;
  if ( pattern.exec(wm) == null )
  {
    document.frmReg.tfWm.style.backgroundColor = "#FFCCCC";
    document.frmReg.tfWm.focus()
    alert('Поле WebMoney містить некоректний номер гаманця!');
    return false;
  }

  if ( document.frmReg.chkAccept.checked == false )
  {
    document.frmReg.chkAccept.focus()
    alert('Якщо ти згодний з "Умовами співпраці" постав відмітку!');
    return false;
  }

  return true;
}

function checkEditAgent()
{
  if ( document.frmEdit.tfPassw.value.length == 0 )
  {
    document.frmEdit.tfPassw.style.backgroundColor = "#FFCCCC";
    document.frmEdit.tfPassw.focus()
    alert('Поле Пароль порожнє!');
    return false;
  }

  pattern = /^[\w\-\.\_]{1,20}\@[\w\-\.]{2,20}\.\w{2,3}$/i;
  email = document.frmEdit.tfEMail.value;
  if ( pattern.exec(email) == null )
  {
    document.frmEdit.tfEMail.style.backgroundColor = "#FFCCCC";
    document.frmEdit.tfEMail.focus()
    alert('Поле E-Mail містить некоректний адрес!');
    return false;
  }

  pattern = /^U\d{12}$/i;
  wm = document.frmEdit.tfWm.value;
  if ( pattern.exec(wm) == null )
  {
    document.frmEdit.tfWm.style.backgroundColor = "#FFCCCC";
    document.frmEdit.tfWm.focus()
    alert('Поле WebMoney містить некоректний номер гаманця!');
    return false;
  }

  return true;
}

function createRequest()
{
  var req = false;
  try
  {
    req = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {
    try
    {
      req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e2)
    {
      req = false;
    }
  }

  if ( !req && typeof XMLHttpRequest != 'undefined')
  {
    req = new XMLHttpRequest();
    if (req.overrideMimeType) req.overrideMimeType("text/html");
  }

  if ( req == null ) alert("Для повноцінної роботи даної сторінки необхідна більш нова версія браузера.");

  return req;
}

function existAgent()
{
  var req = createRequest();
  var login = document.frmReg.tfLoginReg.value;
  var email = document.frmReg.tfEMail.value;
  var url = '/existagent/' + login + '/' + email;
  var result = 0;

  req.open("GET", url, false);
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) result = req.responseText;
  }

  req.send(null);

  return result;
}

// *** RSS ***

function getRss(type)
{
  var req = createRequest();
  var url = "/getrss/" + type + "/";
  var rssBlock = (type == 1 ? document.getElementById('rssUnian') : document.getElementById('rssWeather'));

  req.open("GET", url, true);
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) rssBlock.innerHTML = req.responseText;
  }

  req.send(null);
}

function checkFieldLogin()
{
  if ( document.frmLostPassw.tfLogin.value.length == 0 )
  {
    document.frmLostPassw.tfLogin.style.backgroundColor = "#FFCCCC";
    document.frmLostPassw.tfLogin.focus()
    alert('Поле Логін порожнє!');
    return false;
  }

  return true;
}

function countPassage()
{
  var req = createRequest();
  var url = "/outlinks/2/";

  req.open("GET", url, true);
  req.onreadystatechange = function(){}

  req.send(null);
}

function closeFirmPreview()
{
  document.getElementById("boxCard").style.display = "none";
}

function showFirmPreview()
{
   if (packet == null) packet = 4;

   // verify
   switch(packet)
   {
     case 1:
       if (!checkForm(10, 10)) return false;
     break;

     case 2:
       if (!checkForm(5, 5)) return false;
     break;

     case 3:
       if (!checkForm(2, 3)) return false;
     break;

     case 4:
       if (!checkFirm()) return false;
     break;
   }

   // fill preview card
   var theRubric, listRubric, cntRubric = 0, cntPhone = 0, listPhone, thePhoneCode, thePhoneNum, thePhoneDesc, listEMail = "", listWww = "";
   document.documentElement.scrollTop = 0;
   document.body.scrollTop = 0;
   document.getElementById("boxCard").style.display = 'block';

   switch(packet)
   {
     case 1:
       // emails
       var cntEMails = parseInt(document.getElementById("cntEMail").value);

       listEMail = document.frm.tbEMail.value;
       listEMail += cntEMails > 0 ? ", " : "";

       for (var i = 1; i <= cntEMails; i++)
       {
         theEMail = document.getElementById("idEMail" + i).value;;
         listEMail += theEMail + (i < cntEMails ? ", " : "");
       }

       // www
       var cntWww = parseInt(document.getElementById("cntWww").value);

       listWww = document.frm.tbWWW.value;
       listWww += cntWww > 0 ? ", " : "";

       for (var i = 1; i <= cntWww; i++)
       {
         theWww = document.getElementById("idWww" + i).value;;
         listWww += theWww + (i < cntWww ? ", " : "");
       }

       var desc = document.frm.tfDescription.value.substring(0, 500);

     case 2:
       if (packet == 2)
       {
         desc = document.frm.tfDescription.value.substring(0, 250);
         listEMail = document.frm.tbEMail.value
         listWww = document.frm.tbWWW.value
       }

       if (listWww.length == 0) listWww = "-";
       if (desc.length == 0) desc = "-"; 

     case 3:
       listRubric = "";
       listPhone = "";
	   
	   desc = document.frm.tfDescription.value.substring(0, 100);

       // rubrics

       var cntRubric = parseInt(document.all.hdnRubricCnt.value);
       for (var i = 1; i <= cntRubric; i++)
       {
         theRubric = eval("document.all.tfRubricName"+i+".value");
         listRubric += theRubric + (i < cntRubric ? "<br />" : "");
       }

       // phones

       listPhone = "(" + $('#tfPhoneCode').val() + ")" + $('#tfPhoneNum').val() + ($('#tfPhoneDesc').val().length > 0 ? " [" + document.frm.tfPhoneDesc.value + "]" : "");

       cntPhone = document.getElementById("cntPhone").value;
       listPhone += cntPhone > 0 ? ", " : "";

       for (var i = 1; i <= cntPhone; i++)
       {
         thePhoneCode = document.getElementById("idPhoneCode" + i).value;
         thePhoneNum = document.getElementById("idPhoneNum" + i).value;
         thePhoneDesc = document.getElementById("idPhoneDesc" + i).value;
         thePhoneDesc = thePhoneDesc.length > 0 ? " [" + thePhoneDesc + "]" : "";
         listPhone += "(" + thePhoneCode + ")" + thePhoneNum + thePhoneDesc + (i < cntPhone ? ", " : "");
       }

     case 4:
       if (packet == 4) {
           listRubric = document.frm.cbMainRubrics[document.frm.cbMainRubrics.selectedIndex].text + " &raquo; " + document.frm.cbSubRubrics[document.frm.cbSubRubrics.selectedIndex].text;
           listPhone = "(" + document.frm.tfPhoneCode.value + ")" + document.frm.tfPhoneNum.value;
           desc = document.frm.tfDescription.value.substring(0, 30);
           document.getElementById("firmDesc").innerHTML = desc;
       }
       else {
	       if (document.getElementById("firmEMail") != null) document.getElementById("firmEMail").innerHTML = listEMail;   
           if (document.getElementById("firmWww") != null) document.getElementById("firmWww").innerHTML = listWww;
           document.getElementById("firmDesc").innerHTML = desc.replace(/\r\n|\r|\n/g, "<br />");
       }

       document.getElementById("firmTitle").innerHTML = $('#firmName').val();
       document.getElementById("firmAddress").innerHTML = $('#tfAddressIndex').val() + ", " + $('#tfAddressCity').val() + ", " + $('#tfAddressAnother').val();
       document.getElementById("firmPhone").innerHTML = listPhone;
       document.getElementById("firmRubrics").innerHTML = listRubric;
       document.getElementById("firmLicence").innerHTML = document.frm.tfLicence.value;
     break;
   }
}

function checkContact()
{
  if ( document.frm.frmName.value.length == 0 )
  {
    document.frm.frmName.style.backgroundColor = "#FFCCCC";
    document.frm.frmName.focus()
    alert("Поле Ім'я  порожнє!");
    return false;
  }

  pattern = /^[\w\-\.\_]{1,100}\@[\w\-\.]{1,100}\.\w{2,5}$/i;
  email = document.frm.frmEMail.value;
  if ( pattern.exec(email) == null )
  {
    document.frm.frmEMail.style.backgroundColor = "#FFCCCC";
    document.frm.frmEMail.focus()
    alert('Поле E-Mail містить некоректний адрес!');
    return false;
  }

  if ( document.frm.frmSubject.value.length == 0 )
  {
    document.frm.frmSubject.style.backgroundColor = "#FFCCCC";
    document.frm.frmSubject.focus()
    alert("Поле Тема порожнє!");
    return false;
  }

  if ( document.frm.frmContent.value.length == 0 )
  {
    document.frm.frmContent.style.backgroundColor = "#FFCCCC";
    document.frm.frmContent.focus()
    alert("Поле Текст повідомлення порожнє!");
    return false;
  }

  if (parseInt(tfVerify.value) != val1 + val2) {
      tfVerify.focus()
      alert("Введена невірна сумма чисел!");
      return false;
  }    


  $('form[name=frm]').attr('action', 'contact');
  $('form[name=frm]').submit();

  return true;
}

function selectPacket(packet)
{
  switch (packet)
  {
    case 1:
      document.frm.rbPacket[2].checked = true;
    break;

    case 2:
      document.frm.rbPacket[1].checked = true;
    break;

    case 3:
      document.frm.rbPacket[0].checked = true;
    break;
  }
}

var packet, currPacket;
var aMainRubrics, aSubRubrics;

function getTpl(num)
{
  var req = createRequest();
  var url = '/gettpl/' + num + '/';
  var returnText = "";

  req.open("GET", url, true);
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) returnText = req.responseText;
  }

  req.send(null);

  return returnText;
}

function initRubrics() {
    var req = createRequest();
    var url = '/gettpl/4/';

    req.open("GET", url, false);
    req.send(null);
    var rubricsList = eval('(' + req.responseText + ')');
    aMainRubrics = rubricsList[0];
    aSubRubrics = rubricsList[1];
}

function goStep(numStep) {
    switch(numStep) {
        case 1:
            highlightStep(1);
            document.getElementById('step1').style.display = 'block';
            //document.getElementById('goFreeBlock').style.display = 'block';
            document.getElementById('step2').style.display = 'none';
            document.getElementById('step3').style.display = 'none';
            break;

        case 2:
            highlightStep(2);
            var divStep2 = document.getElementById('step2');

            //document.getElementById('goFreeBlock').style.display = 'none';
            document.getElementById('step1').style.display = 'none';
            document.getElementById('step3').style.display = 'none';
            divStep2.style.display = 'block';

            if (document.frm.rbPacket[0].checked) packet = 3;
            else if (document.frm.rbPacket[1].checked) packet = 2;
            else packet = 1;

            if (currPacket == packet) document.getElementById('step2').style.display = 'block';
            else
            {
                currPacket = packet;
                // загрузка шаблона

                var req = createRequest();
                var url = '/gettpl/' + currPacket + '/';

                req.open("GET", url, true);

                req.onreadystatechange = function()
                {
                    if (req.readyState == 4)
                    {
                        document.getElementById('packetForm').innerHTML = req.responseText;
                        document.getElementById('loadingPacket').style.display = 'none';
                        document.getElementById('firmName').focus();
                        initRubrics();
                        viewMainRubricsById();
                        viewSubRubricsById();
                    //agentsList();
                    }
                    else document.getElementById('loadingPacket').style.display = 'block';
                }

                req.send(null);
            }
            break;

        case 3:
            var lsPayPeriod = [0, 12, 12, 12];

            switch(currPacket)
            {
                case 1:
                    if (!checkForm(10, 10)) return false;
                    $('#pakcetName').html("Преміум");
                    $('#payPeriod').html(lsPayPeriod[currPacket] + " місяців");
                    break;

                case 2:
                    if (!checkForm(5, 5)) return false;
                    $('#pakcetName').html("Стандарт");
                    $('#payPeriod').html(lsPayPeriod[currPacket] + " місяців");
                    break;

                case 3:
                    if (!checkForm(2, 3)) return false;

                    if ($.browser.msie) {
                        $('#rowTestReg').css('display', 'block');
                    } else {
                        $('#rowTestReg').css('display', 'table-row');
                    }
                    
                    $('#pakcetName').html("Безкоштовний");
                    $('#payPeriod').html(lsPayPeriod[currPacket] + " місяців");
                    break;
            }

            highlightStep(3);

            document.getElementById('step2').style.display = 'none';
            document.getElementById('step3').style.display = 'block';
            document.getElementById('pakcetPrice').innerHTML = calcPrice(currPacket);

            return true;
            break;

        case 4:
            if (checkOrder()) document.frm.submit();
            break;
    }
}

function highlightStep(num)
{
  switch(num)
  {
    case 1:
      document.getElementById('titleStep1').style.color = "#FF6500";
      document.getElementById('titleStep1').style.fontWeight = "bold";

      document.getElementById('titleStep2').style.color = "#CCCCCC";
      document.getElementById('titleStep2').style.fontWeight = "normal";

      document.getElementById('titleStep3').style.color = "#CCCCCC";
      document.getElementById('titleStep3').style.fontWeight = "normal";
    break;

    case 2:
      document.getElementById('titleStep1').style.color = "#CCCCCC";
      document.getElementById('titleStep1').style.fontWeight = "normal";

      document.getElementById('titleStep2').style.color = "#FF6500";
      document.getElementById('titleStep2').style.fontWeight = "bold";

      document.getElementById('titleStep3').style.color = "#CCCCCC";
      document.getElementById('titleStep3').style.fontWeight = "normal";
    break;

    case 3:
      document.getElementById('titleStep1').style.color = "#CCCCCC";
      document.getElementById('titleStep1').style.fontWeight = "normal";

      document.getElementById('titleStep2').style.color = "#CCCCCC";
      document.getElementById('titleStep2').style.fontWeight = "normal";

      document.getElementById('titleStep3').style.color = "#FF6500";
      document.getElementById('titleStep3').style.fontWeight = "bold";
    break;
  }
}

function calcPrice(packet) {
  var packetPrice = new Array(4);
  packetPrice[1] = 500;
  packetPrice[2] = 150;
  packetPrice[3] = 0;

  return packetPrice[packet];
}

function viewSubRubricsById()
{
   selectedMain = document.getElementById('mainRubrics').selectedIndex

   var oSubRubricList = document.getElementById('subRubrics')
   var oSubRubricListCnt = aSubRubrics[selectedMain].length
   oSubRubricList.length = 0
   for (i = 0; i < oSubRubricListCnt; i++)
   {
      aParts = aSubRubrics[selectedMain][i].split("|")
      sText = aParts[1]
      sValue = aParts[0]

      if (document.createElement)
      {
         var newRubricListOption = document.createElement("OPTION");
         newRubricListOption.text = sText;
         newRubricListOption.value = sValue;
         (oSubRubricList.options.add) ? oSubRubricList.options.add(newRubricListOption) : oRubricList.add(newRubricListOption, null);
      }
      else oSubRubricList.options[i] = new Option(sText, sValue, false, false)
   }
}

function viewMainRubricsById()
{
  var mainRubrics = document.getElementById('mainRubrics');
  var row, text, value;

  for (var i = 0; i < aMainRubrics.length; i++)
  {
    row = aMainRubrics[i].split("|");
    text = row[1];
    value = row[0];

    if (document.createElement)
    {
      var newRubricListOption = document.createElement("OPTION");
      newRubricListOption.text = text;
      newRubricListOption.value = value;
      (mainRubrics.options.add) ? mainRubrics.options.add(newRubricListOption) : mainRubrics.add(newRubricListOption, null);
    }
    else mainRubrics.options[i] = new Option(text, value, false, false)
  }
}

function agentsList()
{
  var req = createRequest();
  var url = '/gettpl/5/';

  req.open("GET", url, false);
  req.send(null);
  var list = eval('(' + req.responseText + ')');

  var agentSelect = document.getElementById('lstAgents');

  for (var i = 0; i < list.length; i++)
  {
    row = list[i].split("|");
    id = row[0];
    name = row[1];

    if (document.createElement)
    {
      var theAgent = document.createElement("OPTION");
      theAgent.text = name;
      theAgent.value = id;
      theAgent.style.backgroundColor = i % 2 == 0 ? "#EFFAFF" : "";
      (agentSelect.options.add) ? agentSelect.options.add(theAgent) : oRubricList.add(theAgent, null);
    }
    else agentSelect.options[i] = new Option(name, id, false, false)
  }
}

function checkPacket()
{
  return false;
}

function switchCss(type)
{
    switch(type) {
        case 2:
            document.getElementById('cssFile').href = '/templates/print.css';
            var saitName = $("#header img").attr("alt");
            var pRubric = $(".path:eq(1)").text();
            var sRubric = $(".path:eq(2)").text();
            $("#header").before('<div id="printHeader"><h3>' + saitName + '</h3><b>Рубрика:</b> ' + pRubric + ' &raquo; <b>' + sRubric + '</b> <p><span onclick="switchCss(1)">Повернутися до каталогу</span></p></div>');
            $('.cardFree tr td.desc:has(a)').css('display', 'none');
            
            if ($('#cssOwner')) $('#cssOwner').attr('href', '');
            if ($('#cssWare')) $('#cssWare').attr('href', '');

            break;

        case 1:
        default:
            if ($.browser.msie) {
                document.location.href = document.location.href;
            } else { 
                $("#printHeader").remove();
                $('.cardFree tr td.desc:has(a)').css('display', 'table-cell');
                document.getElementById('cssFile').href = '/templates/style.css';

                if ($('#cssOwner')) $('#cssOwner').attr('href', '/templates/owner.css');
                if ($('#cssWare')) $('#cssWare').attr('href', '/templates/ware.css');

            }
    }
}

function checkLinksBaseField()
{
	var tbName = document.getElementById('tbName'); 
//	var tfEMail = document.getElementById('tfEMail');
	var tfUrl =	document.getElementById('tfUrl');
	
    if (tbName.value.length == 0) {
		tbName.focus()
		alert("Поле <Назва> порожнє!");
		return false;
	}

//    if (tfEMail.value.length > 0) {
//		var pattern = /^[\w\-\.]{1,100}\@[\w\-\.]{1,100}\.\w{2,5}$/i;
//        if ( pattern.exec(tfEMail.value) == null ){
//      		tfEMail.focus()
//      		alert('Поле <Контактний E-Mail> містить некоректний адрес!');
//      		return false;
//    	}
//	}

    if (tfUrl.value.length == 0) {
		tfUrl.focus()
		alert("Поле <URL> порожнє!");
		return false;
	}

	return true;
}

function showLinkPreview()
{
	if (packet == null) packet = 5;

	// verify
	switch(packet) {
		case 5:
			if (!checkLinksBaseField()) return false;
			break;
	}

	// fill preview card
	var theTitle, theRubric, theUrl, theDesc;
	document.documentElement.scrollTop = 0;
	document.body.scrollTop = 0;
	document.getElementById("boxCard").style.display = 'block';
	theRubric = document.getElementById('cbRubrics');

	theUrl = document.getElementById('tfUrl').value;
	pattern = /^http:\/\//;
	if (pattern.exec(theUrl) == null) {
		theUrl = 'http://' + theUrl;
	}

	switch(packet) {
		case 1:
		case 2:
		case 3:
		case 5:
			document.getElementById("linkTitle").innerHTML = document.getElementById('tbName').value;
			document.getElementById("linkRubric").innerHTML = theRubric.options[theRubric.selectedIndex].text;
			document.getElementById("linkURL").innerHTML = theUrl;
			document.getElementById("linkDesc").innerHTML = document.getElementById('desc').value.replace(/\r\n|\r|\n/g, "<br />");;
			break;
   }
}

function countJump(idLink)
{
  var req = createRequest();
  var url = '/links/countme/' + idLink + '/';

  req.open("GET", url, true);
  req.onreadystatechange = function() {};

  req.send(null);
}

function bannerJump(id)
{
  var req = createRequest();
  var url = '/bannerjump/' + id + '/';

  req.open("GET", url, true);
  req.onreadystatechange = function() {};

  req.send(null);
}

// page onload
var searchPrompt;

$(document).ready(function() {
    // main search
    
    var searchField = $("#tfSearch");
    searchPrompt = searchField.attr('value'); 
    
    searchField.focus( function () { 
        if (searchField.attr("value") == searchPrompt) {
            searchField.attr("value", ""); 
            searchField.css({textAlign:"left"}); 
        }    
    });
            
    searchField.blur( function () { 
        if (searchField.attr("value") == null || searchField.attr("value").length == 0) {
            searchField.attr("value", searchPrompt); 
            searchField.css({textAlign:"left"}); 
        }
    });
    
   $("#tfSearch").autocomplete('ac/', {minChars: 2, selectFirst: false});

    // news search
    
    var newsSearch = $("#tfNews");
    newsPrompt = newsSearch.attr('value'); 
    
    newsSearch.focus( function () { 
        if (newsSearch.attr("value") == newsPrompt) {
            newsSearch.attr("value", ""); 
            newsSearch.css({textAlign:"left"}); 
        }    
    });
            
    newsSearch.blur( function () { 
        if (newsSearch.attr("value") == null || newsSearch.attr("value").length == 0) {
            newsSearch.attr("value", newsPrompt); 
            newsSearch.css({textAlign:"left"}); 
        }
    });

    // tooltip
    $("a[title]").wTooltip({
        style: {
            border: '1px solid #000',
            background: '#FFFFE1',
            padding: '7px'
        }
    }); 

    $("img.wtip").wTooltip({
        style: {
            border: '1px solid #000',
            background: '#FFFFE1',
            padding: '7px'
        },
        clickAction: null
    }); 

});

function checkSearch()
{
    var searchField = $("#tfSearch");
    
    if (searchField.attr("value") == null || searchField.attr("value") == searchPrompt || searchField.attr("value").length == 0) {
        alert("Введіть запит для пошуку.");
        searchField.focus();
        return false;
    }
    
    return true;
}

/* comments */

var val1, val2;

function checkComment()
{
	var tfName = document.getElementById('tfName'); 
	var tfEMail = document.getElementById('tfEMail');
	var tfText = document.getElementById('tfText');
    var tfVerify = document.getElementById('tfVerify');
    var idFirm = document.getElementById('idFirm').value;
	
    if (tfName.value.length == 0) {
		tfName.focus()
		alert("Поле <Ім'я> порожнє!");
		return false;
	}

    if (tfEMail.value.length > 0) {
		var pattern = /^[\w\-\.]{1,100}\@[\w\-\.]{1,100}\.\w{2,5}$/i;
        if ( pattern.exec(tfEMail.value) == null ){
      		tfEMail.focus()
      		alert('Поле <E-Mail> містить некоректний адрес!');
      		return false;
    	}
	}

    if (tfText.value.length == 0) {
		tfText.focus()
		alert("Поле <Відгук> порожнє!");
		return false;
	}
    
    if (parseInt(tfVerify.value) != val1 + val2) {
		tfVerify.focus()
		alert("Введена невірна сумма чисел!");
		return false;
	}    

   $("#frmAdd").attr('action', '/addcomment/' + idFirm);
   return true;
}

function genClause()
{
   val1 = Math.abs( Math.round( (Math.random() * 10) - 5 ) );
   val2 = Math.abs( Math.round( (Math.random() * 10) - 5 ) );
   
   return val1 + ' + ' + val2 + ' = ';
}

function addAddress(count, langType){
    var langTitle = langType == 1 ? "" : "Ru";
    var hdnAddress = $('#cntAddress'+langTitle);
    var quantity = parseInt(hdnAddress.val()), i = 0, num = 0;
    var divBranch = $("#address"+langTitle);

    quantity++;

    if ( quantity > count ) {
        alert("Ви можете додати не більше " + count + " адресів!");
        return;
    }

   // перебор свободных номеров для имен полей Phone
   while ( ++i <= count) {
      if (document.getElementById("address" + langTitle + i) == null) {
          num = i;
          break;
      }
   }

    // lang array
    var lang = [
        [{index: 'Індекс:', city: 'Населений пункт:', street: 'Вулиця та ін.:', vinnica: 'м. Київ', desc: 'Опис'}],
        [{index: 'Индекс:', city: 'Населенный пункт:', street: 'Улица и т.д.:', vinnica: 'г. Киев', desc: 'Описание'}]
    ];

    // lang index
    var li = langType - 1;

   divBranch.append("<div class='address_add_row' id='address"+langTitle+num+"'>" +
       "<a href=javascript:delAddress("+num+","+langType+") class='align_right' title='Видалити адрес'><img src='/images/building_delete.png' alt='Зайва' /></a>" +
       "<p><label for='address"+num+"Index'>"+lang[li][0].index+"</label> <input type='text' name='tfAddressIndex"+langTitle+"[]' id='address"+num+"Index"+langTitle+"' size='15' maxlength='15' class='textfield' value='79000' /></p>" +
       "<p><label for='address"+num+"City'>"+lang[li][0].city+"</label> <input type='text' name='tfAddressCity"+langTitle+"[]' id='address"+num+"City"+langTitle+"' size='25' maxlength='255' class='textfield' value='"+lang[li][0].vinnica+"' /></p>" +
       "<p><label for='address"+num+"Street'>"+lang[li][0].street+"</label> <input type='text' name='tfAddressAnother"+langTitle+"[]' id='address"+num+"Street"+langTitle+"' size='35' maxlength='255' class='textfield' value='' /></p>" +
       "<p><label for='address"+num+"Desc'>"+lang[li][0].desc+"</label> <input type='text' name='tfAddressDesc"+langTitle+"[]' id='address"+num+"Desc"+langTitle+"' size='35' maxlength='255' class='textfield' value='' /></p>" +
   "</div>");

   hdnAddress.val(quantity);
}

function delAddress(num, langType) {
    var langTitle = langType == 1 ? "" : "Ru";
    $('#address'+langTitle+num).remove();

    var hdnAddress = $('#cntAddress'+langTitle);
    var quantity = parseInt(hdnAddress.val());
    hdnAddress.val(--quantity);
}




