
var ___EASY_SEARCH = 'easySearch';
var ___EXP_SEARCH = 'expSearch';
var ___UNI_SEARCH = 'uniSearch';
var ___EXT_SEARCH = 'extQuerySearch';

var ___DEFAULT_FORM = 'defaultForm';



var ___DEBUG = false;
// Показ формы поиска, в зависимости от настроек
function condChange(obj, id, flag) {
  try {
    if (flag) {
      if (obj.value == "[]") {
        $(id).style.display = "";
      } else {
        $(id).style.display = "none";
		if (obj.getAttribute("tip")=="date") {
			clearEndDateField(obj.getAttribute("attrName"));
		}
      }
    } else {
      if ((obj.value == "[]") || (obj.value != "not empty" && obj.value != "empty")) {
        $(id).style.display = "";
      } else {
        $(id).style.display = "none";
      }
    }
  } catch(e) {
    if(___DEBUG) {
      alert(e);
    }
  }
}
function clearStartDateField(attrName) {
  var obj;
  obj = getObjById("value(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("date(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("hh(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("mm(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("ss(" + attrName + ")");
  if (obj != null) obj.value = "";
}
function clearEndDateField(attrName) {
  var obj;
  obj = getObjById("value2(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("v2date(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("v2hh(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("v2mm(" + attrName + ")");
  if (obj != null) obj.value = "";
  obj = getObjById("v2ss(" + attrName + ")");
  if (obj != null) obj.value = "";
}
function viewSearchForm(type) {
  var search_1 = $(___EASY_SEARCH);
  var search_2 = $(___EXP_SEARCH);
  var search_3 = $(___UNI_SEARCH);
  var search_4 = $(___EXT_SEARCH);
  var defaultForm = $(___DEFAULT_FORM);

  var idlink = "";
  if(___DEBUG) {
    alert(defaultForm.value);
  }
  if (type == null || type == "") {
    idlink = (defaultForm != null) ? defaultForm.value : "";
  } else {
    idlink = type;
    defaultForm.value = idlink;
  }

  if (search_1 != null) {
    search_1.style.display = "none";
    search_1.parentNode.style.display = "none";
  }
  if (search_2 != null) {
    search_2.style.display = "none";
    search_2.parentNode.style.display = "none";
  }
  if (search_3 != null) {
    search_3.style.display = "none";
    search_3.parentNode.style.display = "none";
  }
  if (search_4 != null) {
    search_4.style.display = "none";
    search_4.parentNode.style.display = "none";
  }

  switch (idlink) {
    case ___EASY_SEARCH:
      if (search_1 != null) {
        search_1.style.display = "";
        search_1.parentNode.style.display = "";
      }
      break;
    case ___EXP_SEARCH:
      if (search_2 != null) {
        search_2.style.display = "";
        search_2.parentNode.style.display = "";
      }
      break;
    case ___UNI_SEARCH:
      if (search_3 != null) {
        search_3.style.display = "";
        search_3.parentNode.style.display = "";
      }
      break;
    case ___EXT_SEARCH:
      if (search_4 != null) {
        search_4.style.display = "";
        search_4.parentNode.style.display = "";
      }
      break;
    default:if (search_1 != null) {
      search_1.style.display = "";
      search_1.parentNode.style.display = "";
    }
  }
}
function saveLoadedSearchForm(fdiv, goToType) {
  if (fdiv == null) {
    fdiv = $("searchFormType");
    if (fdiv == null) {
      return false;
    }
  }
  if (goToType == null || goToType == "") {
    goToType = sfName;
  }
  var sfName = fdiv.getAttribute("sfname");
  var sfObj = $("div_" + sfName);
//	alert("current="+sfName+"    sfObj="+sfObj+"\ngoToType="+goToType);
  if (sfObj == null && (sfName == ___EASY_SEARCH || sfName == ___EXP_SEARCH || sfName == ___UNI_SEARCH || sfName == ___EXT_SEARCH)) {
    fdiv.setAttribute("id", "div_" + sfName);
    fdiv.removeAttribute("sfname");
    var span = fdiv.parentNode;
    var div = document.createElement("div");
    span.appendChild(div);
    div.setAttribute("id", "searchFormType");
    div.setAttribute("sfname", goToType);
  } else {
    fdiv.setAttribute("sfname", goToType);
    if (sfObj != null) {
      sfObj.style.display = "none";
    }
  }
  fdiv.style.display = "none";
  return true;
}

function getSFTypeFromFormName(formName) {
  var sftype = -1;
  switch (formName) {
      case ___EASY_SEARCH:
        sftype = 1;
        break;
      case ___EXP_SEARCH:
        sftype = 2;
        break;
      case ___UNI_SEARCH:
        sftype = 3;
        break;
      case ___EXT_SEARCH:
        sftype = 4;
        break;
      default:
        sftype = 1;
        formName = ___EASY_SEARCH;
    }
  return {type:sftype, name: formName};
}

// Смена форм поиска по закладкам
function switchSearchType(type) {

  var formTypeObj = getSFTypeFromFormName(type);

  var search_1 = $(___EASY_SEARCH);
  var search_2 = $(___EXP_SEARCH);
  var search_3 = $(___UNI_SEARCH);
  var search_4 = $(___EXT_SEARCH);

  if (search_1 && search_2 && search_3 && search_4) {
    viewSearchForm(type);
  } else {
    var defaultForm = $(___DEFAULT_FORM);
    if (type == null) {
      type = defaultForm.value;
    }
    var sftype = formTypeObj.type;
    defaultForm.value = formTypeObj.name;

    var formtypeDiv = $("searchFormType");
    if ($("div_" + type) != null || $(type) != null) {
      saveLoadedSearchForm(formtypeDiv, type);
      viewSearchForm(type);
      return;
    }

//		var link=(typeof(self.refreshUrl)!="undefined")?self.refreshUrl:self.location.href;
    var qp = $("urlParams");
    var link = (qp != null && qp != "") ? self.location.protocol + "//" + self.location.host + self.location.pathname + "?" + qp.value : self.location.href;
    if (link.indexOf("?") == -1) {
      link += "?sftype=" + sftype;
    } else if (link.indexOf("sftype") == -1) {
      link += "&sftype=" + sftype;
    } else {
      var ind1 = (link.indexOf("?sftype") != -1 ) ? link.indexOf("?sftype") : (link.indexOf("&sftype") != -1 ) ? link.indexOf("&sftype") : link.indexOf("sftype");
      var ind2 = link.indexOf("&", (ind1 + 1));
      if (ind2 < 0) {
        ind2 = link.length;
      }
      var ch = link.charAt(ind1);
      ch = (ch == "?" || ch == "&") ? ch : "";
      link = link.substring(0, ind1) + ch + "sftype=" + sftype + link.substring(ind2, link.length);
    }
    if(___DEBUG) {
      alert(link);
    }
    var ifr = $("preloadSearchForm");
    if (ifr) {
      var typeName = formtypeDiv.getAttribute("sfname");
      var sf_head = $("sf_shapka_" + ((typeName == ___EXP_SEARCH) ? 2 : (typeName == ___UNI_SEARCH) ? 3 : (typeName == ___EXT_SEARCH) ? 4 : 1));
      var sf_fake_head = $("sf_fake_shapka");
      var justwait = $("justyouwait");
      if (sf_head && sf_fake_head && justwait && formtypeDiv) {
        var sf_tabs=sf_head.innerHTML;
        sf_fake_head.innerHTML = sf_tabs.replace(/[\s]*switchSearchType[\s]*\([^\)]*\)[\s]*[;]*[\s]*/img,"");
        var sh_op = $("showingOptions");
        if (sh_op != null) {
          if (sh_op.checked) sh_op.click();
          sh_op.setAttribute("disabled", "true");
        }
        var ssb = $("searchSubmitButtons");
        if (ssb != null) ssb.style.display = "none";
			
				/// ----------------- если форма поиска уже загружена - сохраняем ее в DIV  с id = типу форму поиска --------
        saveLoadedSearchForm(formtypeDiv);
				///---------------------------------------------------------------------------------------------------------------------------------------
        justwait.style.display = "";
      }
      ifr.src = link;
    }
	//	window.location.href=link;
  }
}

function moveCalendarToParentFrame(parent, formName) {
	if (!parent) parent=self.parent;
  if (parent && parent != self) {
    var sp=parent;
    var ff = parent.document.forms[formName];
    if (self.cals.length > 0 && ff != null) {
      for (var x = 0; x < self.cals.length; x++) {
        var calendar = self.cals[x];
		if (sp.addCalendar) {
			sp.addCalendar(calendar.title, calendar.attrName, ff,calendar.message,calendar.dataFieldPrefix,calendar.fieldPrefix);
		}
      }
    }
	sp.cleanFR();
  }
}


function cleanFR() {
	var fr = self.frames["preloadSearchForm"];
	if(!fr)  return;
	var frDoc = fr.document;
	if (frDoc == null) return;
	var formType = frDoc.getElementById("searchFormType");
	if (formType == null) return;
	formType.innerHTML="";
}

var addCondition = null;
var getCondValues = null;
function preloadFormType() {
  var fr = self.frames["preloadSearchForm"];
  if (fr == null) return;
  var frDoc = self.frames["preloadSearchForm"].document;
  if (frDoc == null) return;
  var formType = frDoc.getElementById("searchFormType");
  if (formType == null) return;
  var formtypeDiv = $("searchFormType");
  if (formtypeDiv == null) return;

  var justwait = $("justyouwait");
  if (justwait) justwait.style.display = "none";
  var sh_op = $("showingOptions");
  if (sh_op != null) {
    sh_op.removeAttribute("disabled");
  }
  var ssb = $("searchSubmitButtons");
  if (ssb != null) ssb.style.display = "";

  var f = "";
  /*перенос JS-функции addCondition в основной фрейм*/
  var func = fr.addCondition;
  if (func != null) {
    func += " ";
    f = func.substring(func.indexOf("{") + 1, func.lastIndexOf("}") - 1);
  }
  addCondition = new Function(f);
  /*перенос JS-функции getCondValues в основной фрейм*/
  func = fr.getCondValues;
  if (func != null) {
    func += " ";
    f = func.substring(func.indexOf("{") + 1, func.lastIndexOf("}") - 1);
  }
  getCondValues = new Function(f);
  formtypeDiv.innerHTML = formType.innerHTML;

  //Для мозилы переносим значения полей формы из ифрейма ..... (при переносе через innerHTML значения полей теряются под Мозиллой)
  if (window.addEventListener){
    copyFormToForm(frDoc.getElementById("find"), $("find"));
  }
  formtypeDiv.setAttribute("sfname", formType.getAttribute("sfname"));
  formtypeDiv.style.display = "";
}

// Смена форм поиска по закладкам - используется только для поддержки старого функционала....
function swap(id1ink) {
  var search_1 = $(___EASY_SEARCH);
  var search_2 = $(___EXP_SEARCH);
  var search_3 = $(___UNI_SEARCH);
  var search_4 = $(___EXT_SEARCH);
  var defaultForm = $(___DEFAULT_FORM);

  defaultForm.value = id1ink;

  if (search_1 != null) search_1.style.display = "none";
  if (search_2 != null) search_2.style.display = "none";
  if (search_3 != null) search_3.style.display = "none";

  if (id1ink == ___EASY_SEARCH) {
    search_1.style.display = "";
  } else if (id1ink == ___EXP_SEARCH) {
    search_2.style.display = "";
  } else if (id1ink == ___UNI_SEARCH) {
    search_3.style.display = "";
  } else if (id1ink == ___EXT_SEARCH) {
    search_4.style.display = "";
  }
}

// Меняет поля для ввода значений дат (явное указание даты или шаблоны)--%>
function changeDateValueSpan() {
  var oAttrList = $("attrName");
  var attrName = oAttrList.options[oAttrList.selectedIndex].value
  var spanConcreteDate = $("spanConcreteDateF" + attrName);
  var spanTemplateDate = $("spanTemplateDateF" + attrName);
  if (spanConcreteDate && spanTemplateDate) {
    var temp = spanConcreteDate.style.display;
    if (temp == 'none') {
      spanConcreteDate.style.display = '';
      spanTemplateDate.style.display = 'none';
    } else {
      spanConcreteDate.style.display = 'none';
      spanTemplateDate.style.display = '';
    }
  }
}

// Установка показа дополнительных настроек поиска по умолчанию
function showingOption(show) {
  var showOptions = $("showingOptions");
  var options = $("Options");
  if (show == 'true') {
    showOptions.checked = true;
    options.style.display = "";
  } else {
    showOptions.checked = false;
    options.style.display = "none";
  }
}

// Показ дополнительных настроек поиска
function showOptions() {
  var show = $("showingOptions");
  var options = $("Options");
  var showOption = $("showOption");

  if (show.checked) {
    options.style.display = "";
    showOption.value = 'true';
  } else {
    options.style.display = "none";
    showOption.value = 'false';
  }
}

// Показывает форму для поиска по атрибутам ссылочных классов
function setLinked(List) {
  try {
    var Name = List.id.substr(4);
    oTR = $("linkAttrRow_" + Name);
    oDC = $("divC_" + Name);
    oDL = $("divL_" + Name);
    oValue = $("id_" + Name);
    oView = $("title_" + Name);
    if (oTR) {
      oTR.style.display = "none";
      if (List.options[List.selectedIndex].value == "linked") {
        oTR.style.display = "";
      } else {
        if (List.options[List.selectedIndex].getAttribute("type") == "list") {
          if (List.options[List.selectedIndex].value == "contains" ||
              List.options[List.selectedIndex].value == "not contains") {
            if (oDC.style.display != "") {
              oValue.value = '';
              oView.value = '';
            }
            oDC.style.display = "none";
            oDL.style.display = "";
          } else if (List.options[List.selectedIndex].value == "empty") {
            oDC.style.display = "none";
            oDL.style.display = "none";
          } else {
            oDC.style.display = "";
            oDL.style.display = "none";
          }
        } else {
          if (List.options[List.selectedIndex].value == "contains" ||
              List.options[List.selectedIndex].value == "not contains" ||
              List.options[List.selectedIndex].value == "equal" ||
              List.options[List.selectedIndex].value == "equals case sensitive" ||
              List.options[List.selectedIndex].value == "start" ||
              List.options[List.selectedIndex].value == "start case sensitive" ||
              List.options[List.selectedIndex].value == "end") {
            if (oDC.style.display != "") {
              oValue.value = '';
              oView.value = '';
            }
            oDC.style.display = "";
            oDL.style.display = "none";
          } else {
            oDC.style.display = "none";
            oDL.style.display = "";
          }
        }
      }
    }
  } catch(e) {
    if(___DEBUG) {
      alert(e);
    }
  }
}


// Показывает ошибки в условии выборки
function showError(text) {
  var oList = $('errorTable');
  if (text == "") {
    oList.style.display = "none";
  } else {
    oList.style.display = "";
  }
}

// Добавляет короткие названия атрибутам
function addShortTitle() {
  var oAttrList = $("attrName");
  for (var i = 0; i < oAttrList.length; i++) {
    var tempString = oAttrList.options[i].text;
    var shortTitle = '';
    if (oAttrList.options[i].text) {
      oAttrList.options[i].data = tempString;
      while (tempString.search(':') != -1) {
        tempString = tempString.substr(tempString.search(':') + 1);
        shortTitle = shortTitle + '--';
      }
      shortTitle = shortTitle + tempString;
      oAttrList.options[i].text = shortTitle;
    }
  }
}

// Добавляет в список условий objCriteria запись
function addText(list, text) {
  var oList = $(list);
  oList.value = oList.value + text;
}

// Очищает список условий objCriteria
function clearCondition() {
  var oList = $("objCriteria");
  var oListRUS = $("objCriteriaRUS");
  oList.value = '';
  oListRUS.value = '';
}

// В зависимости от типа атрибута, выводим форму для ввода значений
function getInputForm() {    
  var oAttrList = $("attrName");
  var oCondList = $("condType");
  var span_unisearch_value = document.getElementById("span_unisearch_value");
  // Сначала скрываем все
  if (span_unisearch_value) {
    span_unisearch_value.style.display = "none";
  }
  var oAttrDiv = null;
  for (var i = 0; i < oAttrList.length; i++) {
    if (oAttrList.options[i].value) {
      oAttrDiv = $("div_F" + oAttrList.options[i].value);
      if (oAttrDiv) {
        oAttrDiv.style.display = "none";
      }
    }
  }
  var cond = oCondList.options[oCondList.selectedIndex].value;
  if (oAttrList.options.length > 0 &&
      oAttrList.options[oAttrList.selectedIndex].value &&
      cond != '' && cond != 'empty' && cond != 'not empty') {
    oAttrDiv = $("div_F" + oAttrList.options[oAttrList.selectedIndex].value);
    if (oAttrDiv) {
      oAttrDiv.style.display = "";
    }
    if (span_unisearch_value) {
      span_unisearch_value.style.display = "";
    }    
  }
}
