var variablesDivStateCmplxFrm =  false;
var isIE	= navigator.userAgent.toLowerCase().indexOf('msie') > -1;
var isOpera	= navigator.userAgent.toLowerCase().indexOf('opera') > -1;
var ver = parseInt(navigator.appVersion);
var hospiceListCmplxFrm = new Array();
var selectedLineCmplxFrm = -1;
var curHospiceCmplxFrm = "";
var intervalIDCmplxFrm;
var curKeyCodeCmplxFrm = "";
var isRealHospiceCmplxFrm = false;
var mouseInVarDivCmplxFrm = false;
var mouseInOneOfVariantCmplxFrm = false;
var iframeEl;
var hostName = "";
var inputIDCmplxFrm = "srch_region_cmplx_frm";//!!ID инпута с контекстным поиском!! 
var variantsIDCmplxFrm = "variantsCmplxFrm";//ID выпадающего списка, дива с вариантами
var wrongDivIDCmplxFrm = "wrongHospiceWarningDivCmplxFrm";//ID предупреждающего об ошибке дива
var inoutDivIDCmplxFrm = "hospiceDivCmplxFrm";//ID дива содержащего инпут с контекстным поиском
var oneVariantIDCmplxFrm = "variantCmplxFrm";//"общая часть" ID одного варианта из выпадающего списка
var realEnterCmplxFrm = true;
var shAllVrntsClickCmplxFrm = false;
var blurFlagCmplxFrm = false;
var focusTimeCmplxFrm;       // 

function mouseInVariantsDivCmplxFrm(flag)
{
  mouseInVarDivCmplxFrm = flag;
}

window.onload = function ()
{
  /*var variantsDiv = document.getElementById("variants");
  iframeEl = document.createElement("IFRAME");
  iframeEl.frameBorder = 0;
  iframeEl.src = "javascript:false;";
  iframeEl.style.display = "none";
  iframeEl.style.position = "absolute";
  iframeEl.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
  variantsDiv.parentNode.insertBefore(iframeEl, variantsDiv);*/

  try 
  {
    onloadSmplFrm();
  }
  catch(e)
  {  
  }

  try 
  {
    onloadOrderFrm();
  }
  catch(e)
  {  
  }
  curHospiceCmplxFrm = document.getElementById(inputIDCmplxFrm).value;
  document.getElementById(inputIDCmplxFrm).disabled = "";
  

  document.getElementById(variantsIDCmplxFrm).style.width = document.getElementById(inputIDCmplxFrm).clientWidth + (isIE ? 2 : 0);
  document.getElementById(inoutDivIDCmplxFrm).style.width = document.getElementById(inputIDCmplxFrm).clientWidth + 2;
  document.getElementById(variantsIDCmplxFrm).style.height = "300px";
  document.getElementById(variantsIDCmplxFrm).style.overflow = "auto";

  if (isIE)
  {
    document.getElementsByTagName("body")[0].attachEvent("onmousedown", onUserClickCmplxFrm);     
  }
  else
  {
    document.getElementsByTagName("body")[0].addEventListener("mousedown", onUserClickCmplxFrm, false);
  }

  hostName = document.getElementById("hostName").value;
};

function onloadCmplxFrm()
{
  /*var variantsDiv = document.getElementById(variantsIDCmplxFrm);
  iframeEl = document.createElement("IFRAME");
  iframeEl.frameBorder = 0;
  iframeEl.src = "javascript:false;";
  iframeEl.style.display = "none";
  iframeEl.style.position = "absolute";
  iframeEl.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
  variantsDiv.parentNode.insertBefore(iframeEl, variantsDiv);*/
  curHospiceCmplxFrm = document.getElementById(inputIDCmplxFrm).value;
  document.getElementById(inputIDCmplxFrm).disabled = "";
  

  document.getElementById(variantsIDCmplxFrm).style.width = document.getElementById(inputIDCmplxFrm).clientWidth + (isIE ? 2 : 0);
  document.getElementById(inoutDivIDCmplxFrm).style.width = document.getElementById(inputIDCmplxFrm).clientWidth + 2;
  document.getElementById(variantsIDCmplxFrm).style.height = "300px";
  document.getElementById(variantsIDCmplxFrm).style.overflow = "auto";

  if (isIE)
  {
    document.getElementsByTagName("body")[0].attachEvent("onmousedown", onUserClickCmplxFrm);     
  }
  else
  {
    document.getElementsByTagName("body")[0].addEventListener("mousedown", onUserClickCmplxFrm, false);
  }

  hostName = document.getElementById("hostName").value;
}

function userUpKeyCmplxFrm(e)
{
  e = (window.event) ? event : e;
  var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

  var hospiceStr = document.getElementById(inputIDCmplxFrm).value;
  var variantsDiv = document.getElementById(variantsIDCmplxFrm);

  if (hospiceStr != curHospiceCmplxFrm && hospiceStr != "" && keyCode != 38 && keyCode != 40 && keyCode != 27 && keyCode != 13 && keyCode != 39 && keyCode != 37)
  {
    curHospiceCmplxFrm = hospiceStr;
    isRealHospiceCmplxFrm = false;

    /*var listStr = httpRequest(hostName + "ajaxResponse.asp",
                                           "action=rgInptSrchFrmChng" +
                                           "&hospice=" + escape(String(hospiceStr).substr(0,200)));*/
                                           
    fillHospiceListCmplxFrm(hospiceStr); 

    if (hospiceListCmplxFrm.length > 0)
    {
      showVariantsCmplxFrm()
    }
    else
    {
      hideVariantsCmplxFrm();
      if (!isRealHospiceCmplxFrm)
        showWarningDivCmplxFrm();
    }
  }

  if (hospiceStr == "" && curHospiceCmplxFrm != hospiceStr)
  {
      hideVariantsCmplxFrm();
      hideWarningDivCmplxFrm();
      curHospiceCmplxFrm = "";
  }

  if ((keyCode == 38 || keyCode == 40)  && variablesDivStateCmplxFrm && isIE)//отпущена клавиша вверх (вниз) в браузере IE
  {
    curKeyCodeCmplxFrm = "";              //останавливаем периодическое выполнение ф-ии moveChoicedLineCmplxFrm
    clearInterval(intervalIDCmplxFrm);
  }

  if (keyCode == 27) //отпущена клавиша Esc
  {
    if (!isIE && !isOpera)//и браузер есм FireFox or something like that, то бишь любой Gecko-браузер
    {
      if (variablesDivStateCmplxFrm)
      {
        hideVariantsCmplxFrm();
        if (!isRealHospiceCmplxFrm)
          showWarningDivCmplxFrm();
      }
      else
      {
        document.getElementById(inputIDCmplxFrm).value = "";
        document.getElementById(inputIDCmplxFrm).blur();
      }
        
    }
  }
}

function userPressKeyCmplxFrm(e)
{
  e = (window.event) ? event : e;
  var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

  if (!isIE && variablesDivStateCmplxFrm && (keyCode == 38 || keyCode == 40) && !e.shiftKey)
  {
    if (keyCode == 38)//нажата клавиша вверх
    {
      if (-1 == selectedLineCmplxFrm)
      {
        selectedLineCmplxFrm = hospiceListCmplxFrm.length - 1;
        document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
      }
      else
        if (0 == selectedLineCmplxFrm)
        {
          selectedLineCmplxFrm = - 1;
          document.getElementById(inputIDCmplxFrm).value = curHospiceCmplxFrm;
        }
        else
        {
          selectedLineCmplxFrm -= 1;
          document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
        }
    }
    else//клавиша вниз
    {
      if (-1 == selectedLineCmplxFrm)
      {
        selectedLineCmplxFrm = 0;
        document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
      }
      else
        if (hospiceListCmplxFrm.length - 1 == selectedLineCmplxFrm)
        {
          selectedLineCmplxFrm = - 1;
          document.getElementById(inputIDCmplxFrm).value = curHospiceCmplxFrm;
        }
        else
        {
          selectedLineCmplxFrm += 1;
          document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
        }
    }
    colorVariantCmplxFrm();
  }

  if (keyCode == 27 && (isIE || isOpera))//нажата клавиша Esc
  {
    var variantsDiv = document.getElementById(variantsIDCmplxFrm);
    if (variablesDivStateCmplxFrm)
    {
      hideVariantsCmplxFrm();
      document.getElementById(inputIDCmplxFrm).value = curHospiceCmplxFrm;
      
      if (!isRealHospiceCmplxFrm)
        showWarningDivCmplxFrm();
    }
    else
    {     
      document.getElementById(inputIDCmplxFrm).value = "";
      document.getElementById(inputIDCmplxFrm).blur();
      hideWarningDivCmplxFrm();
    }
    e.cancelBubble = true;
  }
}

function userDownKeyCmplxFrm(e)
{
  e = (window.event) ? event : e;
  var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

  if (variablesDivStateCmplxFrm && (keyCode == 38 || keyCode == 40) && isIE)
  {
    moveChoicedLineCmplxFrm(keyCode);
    curKeyCodeCmplxFrm = keyCode;
    intervalIDCmplxFrm = setInterval('moveChoicedLineCmplxFrm()', 500, '38')
  }

  if (keyCode == 13) //отпущена клавиша Enter
  {
    if (variablesDivStateCmplxFrm)
    {
      if (selectedLineCmplxFrm > -1)
        document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
      else
        if (!isRealHospiceCmplxFrm)
          showWarningDivCmplxFrm();
      hideVariantsCmplxFrm();
      realEnterCmplxFrm = false;
    }
  }
}

function onUserClickCmplxFrm(e)
{
  var clickTime = (new Date()).getTime();
  
  if (!(shAllVrntsClickCmplxFrm && ((clickTime - focusTimeCmplxFrm) < 50)))//исправление неправильно поведения в Opere при обработке события onFocus для всемогущего нашего инпута с контекстным поиском 
  {
    if (variablesDivStateCmplxFrm)//если список вариантов имеет место быть
    {
      if (mouseInVarDivCmplxFrm)//если щелчок внутри списка вариантов
      {
        if (mouseInOneOfVariantCmplxFrm)//и внутри одного из вариантов
        {
          var variantsDiv = document.getElementById(variantsIDCmplxFrm);
    
          document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
          curHospiceCmplxFrm = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
          isRealHospiceCmplxFrm = true;
        }
      }
      else
        if (!(blurFlagCmplxFrm && ((clickTime - focusTimeCmplxFrm) < 50)))
          document.getElementById(inputIDCmplxFrm).value = curHospiceCmplxFrm;
          

      if (mouseInOneOfVariantCmplxFrm || !mouseInVarDivCmplxFrm)
      {
        hideVariantsCmplxFrm();      
    
        if (document.getElementById(inputIDCmplxFrm).value > "" && !isRealHospiceCmplxFrm && !(blurFlagCmplxFrm && ((clickTime - focusTimeCmplxFrm) < 50)))
          showWarningDivCmplxFrm();
      }    
    }
  } 

  shAllVrntsClickCmplxFrm = false;
  blurFlagCmplxFrm = false; 
}

function moveChoicedLineCmplxFrm(keyCode)
{
  keyCode = arguments[0] ? arguments[0] : curKeyCodeCmplxFrm;

  if (keyCode == 38)//нажата клавиша вверх
  {
    if (-1 == selectedLineCmplxFrm)
    {
      selectedLineCmplxFrm = hospiceListCmplxFrm.length - 1;
      document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
    }
    else
      if (0 == selectedLineCmplxFrm)
      {
        selectedLineCmplxFrm = - 1;
        document.getElementById(inputIDCmplxFrm).value = curHospiceCmplxFrm;
      }
      else
      {
        selectedLineCmplxFrm -= 1;
        document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
      }
  }
  else//клавиша вниз
  {
    if (-1 == selectedLineCmplxFrm)
    {
      selectedLineCmplxFrm = 0;
      document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
    }
    else
      if (hospiceListCmplxFrm.length - 1 == selectedLineCmplxFrm)
      {
        selectedLineCmplxFrm = - 1;
        document.getElementById(inputIDCmplxFrm).value = curHospiceCmplxFrm;
      }
      else
      {
        selectedLineCmplxFrm += 1;
        document.getElementById(inputIDCmplxFrm).value = removePathFromRegion(hospiceListCmplxFrm[selectedLineCmplxFrm]);
      }
  }
  colorVariantCmplxFrm();
}

function leaveVariantCmplxFrm(numb)
{
  mouseInOneOfVariantCmplxFrm = false;
}

function colorVariantCmplxFrm()
{
  mouseInOneOfVariantCmplxFrm = true;

  var sltdLine = (arguments[0] == undefined) ? selectedLineCmplxFrm : arguments[0];
  
  for (i = 0; i < hospiceListCmplxFrm.length; i++)
  {
    var variant = document.getElementById(oneVariantIDCmplxFrm + i);
    if (i == sltdLine)
    {
      variant.className = "cmplxSrc_variant cmplxSrc_selectedVariant"
      selectedLineCmplxFrm = i;
    }
    else
      variant.className = "cmplxSrc_variant"
  }
}

function httpRequest(url, params)
{
   var httpR = false;
   if (window.XMLHttpRequest && !(window.ActiveXObject))
   {
       try
       {
          httpR = new XMLHttpRequest();
       }
       catch(e)
       {
          httpR = false;
       }
   }
   else
     if(window.ActiveXObject)
     {
         try
         {
            httpR = new ActiveXObject("Msxml2.XMLHTTP");
         }
         catch(e)
         {
             try
             {
                httpR = new ActiveXObject("Microsoft.XMLHTTP");
             }
             catch(e)
             {
                httpR = false;
             }
         }
     }

   httpR.open("POST", String(url), false);
   httpR.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
   httpR.send(params);
   return String(httpR.responseText);
}

//ф-ция делает видимым список вариантов-подстановок.
function showVariantsCmplxFrm()
{
  hideWarningDivCmplxFrm();//сперва убираем warning div

  var variantsDiv = document.getElementById(variantsIDCmplxFrm);

  variablesDivStateCmplxFrm = true;
  variantsDiv.innerHTML = "";
  
  var tmpInnerHtml = "";
  
  for (var i = 0; i < hospiceListCmplxFrm.length; i++)
  {
    tmpInnerHtml += "<div id='" + oneVariantIDCmplxFrm + i + "' class='cmplxSrc_variant' onMouseOut='leaveVariantCmplxFrm(" + i + ")' onMouseOver='colorVariantCmplxFrm(" + i + ")'>" + markPrintLettersCmplxFrm(hospiceListCmplxFrm[i]) + "</div>";
  }

  variantsDiv.innerHTML = tmpInnerHtml;

  if (iframeEl)
  {
    iframeEl.style.left    = variantsDiv.style.left;
    iframeEl.style.top     = variantsDiv.style.top;
    iframeEl.style.width   = variantsDiv.offsetWidth + "px";
    iframeEl.style.height  = variantsDiv.offsetHeight + "px";
    iframeEl.style.display = "block";
  }

  variantsDiv.style.display = "block";
}

//ф-ция скрывает список вариантов-подстановок.
function hideVariantsCmplxFrm()
{
  var variantsDiv = document.getElementById(variantsIDCmplxFrm);

  variablesDivStateCmplxFrm = false;
  variantsDiv.style.display = "none";
  if (iframeEl)
    iframeEl.style.display = "none";
  selectedLineCmplxFrm = -1;
  hospiceListCmplxFrm = new Array();
}

//ф-ция делает видимым блок, предупреждающий о том, что здравницы с набранным именем не существует
function showWarningDivCmplxFrm()
{
  document.getElementById(inoutDivIDCmplxFrm).className = "cmplxSrc_wrongHospice";
  document.getElementById(wrongDivIDCmplxFrm).style.display = "block";
}

//ф-ция скрывает блок, предупреждающий о том, что здравницы с набранным именем не существует
function hideWarningDivCmplxFrm()
{
  document.getElementById(inoutDivIDCmplxFrm).className = "";
  document.getElementById(wrongDivIDCmplxFrm).style.display = "none";
}

function realComplexSearchFormSend(fl)
{
  var f = document.f;
  f.method = "get";
  f.action = hostName + "search.asp";
  
  if (realEnterCmplxFrm)
  {
    document.getElementById(inputIDCmplxFrm).disabled = true;
    document.getElementById("rg_fld_cmplx_frm").value = getRegionIDCmplxFrm(document.getElementById(inputIDCmplxFrm).value);

    return true
  } 
  else
  {
    realEnterCmplxFrm = true;
    return false;
  }
}

function getRegionIDCmplxFrm(val)
{
  for (var key in ableValuesCmplxFrm)
  {
    if (removePathFromRegion(ableValuesCmplxFrm[key]).toLowerCase() == String(val).toLowerCase())
      return String(key).replace(/\_/g, "");
  }
  
  return "";
}

function removePathFromRegion(str, direction)
{ 
  return (direction ? (str.match(/^-+/) ? str.match(/^-+/)[0] : "") : String(str).replace(/^-+/g, ""));
}

//для текстового инпута - при onBlur, если ничего не введено вставляем дефолтное зн-е dfltVal, при onFocus - убираем это же dfltVal
function setDefaultValueCmplxFrm(inpt, focus, dfltVal)
{
  shAllVrntsClickCmplxFrm = (focus && (inpt.value == dfltVal));
  blurFlagCmplxFrm = !focus && (inpt.value == "");
  
  var hdWarn = (!focus && (inpt.value == "" || inpt.value == dfltVal));
  
  if (focus)
  {
    if (inpt.value == dfltVal)
      inpt.value = ""    
  }
  else
    if (inpt.value == "")
      inpt.value = dfltVal;
       
  /*inpt.value = () ?
                 (inpt.value == dfltVal ? "" : inpt.value)
                       :
                 (inpt.value == "" ? dfltVal : inpt.value);*/

  if (hdWarn)
    hideWarningDivCmplxFrm();
  if (shAllVrntsClickCmplxFrm)
    showAllVariantsCmplxFrm();
    
  focusTimeCmplxFrm = (new Date()).getTime();
}

function showAllVariantsCmplxFrm()
{
  curHospiceCmplxFrm = "";
  isRealHospiceCmplxFrm = false;
  
  hospiceListCmplxFrm = new Array();
    
  for (var key in ableValuesCmplxFrm)
  {
    if (String(key).toLowerCase() != "popx" && String(key).toLowerCase() != "contain")//НЕчто УЖАСНОЕ творится в дебрях клиентского JavaScripta. Причем происходит это повсеместно, так сказать, кроссбраузерно, будьте осторожны!!!
    {       
      hospiceListCmplxFrm.push(ableValuesCmplxFrm[key]);
    }
  }
    
  if (hospiceListCmplxFrm.length > 0)
  {
    showVariantsCmplxFrm()
  }
}

function markPrintLettersCmplxFrm(str)
{
  if (curHospiceCmplxFrm == "")
    return str;

  var stStr = removePathFromRegion(str, 1);
  str = removePathFromRegion(str);
  
  try
  {
    var myRegExp = new RegExp("(" + String(curHospiceCmplxFrm).replace(/\(/g, "\\(").replace(/\)/g, "\\)").replace(/\./g, "\\.").replace(/\[/g, "\\[").replace(/\]/g, "\\]") + ")", "i");
    myRegExp.test(str);
  }
  catch(e)
  {
    return str;
  }
  return stStr + (RegExp.$1 ? (String(str).replace(myRegExp, "<span class=\"cmplxSrc_boldWordPart\">" + RegExp.$1 + "</span>")) : str);
}

function fillHospiceListCmplxFrm(wordPart)
{
  hospiceListCmplxFrm = new Array();

  try
  {
    var myRegExp = new RegExp(String(wordPart).replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)").replace(/\./g, "\\."), "gi");

    for (var key in ableValuesCmplxFrm)
    {
      if (myRegExp.test(removePathFromRegion(ableValuesCmplxFrm[key]))  && String(key).toLowerCase() != "popx" && String(key).toLowerCase() != "contain")
      {
        addParentCmplxFrm(parentIDsCmplxFrm[key]);
        
        hospiceListCmplxFrm.push(ableValuesCmplxFrm[key]);
        isRealHospiceCmplxFrm = isRealHospiceCmplxFrm || (removePathFromRegion(ableValuesCmplxFrm[key]).toLowerCase() == curHospiceCmplxFrm.toLowerCase());
      }
    }
  }
  catch(e)
  {  
  }  
}      

function addParentCmplxFrm(parent)
{
  if (parent == "_0")
    return;
  else
  {
    var parentInList = false;
    for (i = 0; i < hospiceListCmplxFrm.length; i++)
      parentInList = parentInList || (hospiceListCmplxFrm[i] == ableValuesCmplxFrm[parent]);
    
    addParentCmplxFrm(parentIDsCmplxFrm[parent]);
    
    if (!parentInList)
      hospiceListCmplxFrm.push(ableValuesCmplxFrm[parent]);           
  }
}
