//         Работа с XML
var req;          //Глобальный объект запроса

function XMLdoc(){
  var isIE = window.ActiveXObject? "yes": "";  //ie or mz
  this.doc;
 //добавить в созданный документ элемент
 this.add = function(block_mes, path, file_name)
 {
   root =  this.doc.firstChild
   m_id =  this.doc.createElement("path")
   m_txt = this.doc.createElement("mes")
   fl_name = this.doc.createElement("f_name")
   root.appendChild(m_txt)
   root.appendChild(m_id)
   root.appendChild(fl_name)
   m_txt.appendChild( this.doc.createTextNode(block_mes) )
   m_id.appendChild( this.doc.createTextNode(path) )
   fl_name.appendChild( this.doc.createTextNode(file_name) )
 }
  //----Создание нового документа----
  this.create = function()
  {
    try{    // MSIE?
        this.doc = new ActiveXObject('Msxml2.DOMDocument');
        var root = this.doc.createElement("root")
        this.doc.appendChild(root)
    }catch ( oError ) {
       try{	// Mozilla?
           this.doc = document.implementation.createDocument("","root",null);
       }catch ( oError ) { return null }
    }
    return this.doc;
  }
  //---------------------------------------
  this.show = function(pdoc)
  {
    var rez;
    if (isIE)   {
      rez = pdoc.xml;
    } else {
     // var parser  = new DOMParser;
      var serializer = new XMLSerializer();
      rez = serializer.serializeToString(pdoc);
    }
    return rez;
  }
  //---------------------------------------
  this.parse = function(xmltext)
  {
    try {  //IE
        var obj = new ActiveXObject("Msxml2.DOMDocument");
        obj.loadXML(xmltext);
        return obj;
    } catch (e) {
        try {  //Mozilla
            var obj = new DOMParser();
            return obj.parseFromString(xmltext, "text/xml");
        } catch (e) {return null;}
    }
  }
}//XMLdoc

//----Отправка документа на сервер----
function sendXML( oDoc )
{
  var serverUrl = "inc/siteSearch/!server.php"
  if (window.XMLHttpRequest)      req = new XMLHttpRequest();                                 //Mozilla
  else if (window.ActiveXObject)  req = new ActiveXObject('Microsoft.XMLHTTP');               //IE
  req.onreadystatechange = processReqChange;
  req.open( "POST", serverUrl, true );
  req.send( oDoc );
  return req.responseXML;
}

//================================================
//Елементы, которые могут изменятся размещены ниже
//================================================

//------------------ монитор состояния отправки на сервер ---------------------
function processReqChange()
{
//  document.getElementById("check").value = req.readyState
  ab = window.setTimeout("req.abort();", 5000)
  if (req.readyState == 4){
      clearTimeout(ab);
      // only if "OK"
      if (req.status == 200) {
       document.getElementById("searchResultBlock").innerHTML = req.responseText
//       alert(req.responseXML.firstChild.nodeName)
      }
      else                    alert("Не удалось получить данные:\n" + req.statusText)

  }
}

//----------------- Функция для суммирования измененных блочков для передачи данных на сервер ----------------
function makeSearch(Param1, Param2, Param3)
{
   var ob = new XMLdoc()
   ob.create()
   ob.add(Param1, Param2, Param3)
   response = sendXML(ob.doc)
}document.onkeydown=function(e){
   e=e||event
   var t=e.target||e.srcElement
   if(e.keyCode==13)  siteSearch(0);
   else if(e.keyCode==27) {
        document.getElementById("searchResultBlock").style.display = "none";
        document.getElementById("info_blocks").style.display = "block";
   }
}
//-------------------------------------------
//Вывод значения первого элемента объекта
function getTDValue(obj){
   if (obj.nodeType == 3) obj = obj.nextSibling  //for Mozilla
   return   obj.firstChild.nodeValue
}

//   Выводит на экран Свойства текущего объекта
function ObjProrerties(x){
  document.write("<table border=1 cellspacing=0 cellpadding=0>");
  document.write("<tr><td align=center><b>Свойства объекта "+x.nodeName+"</b></td></tr>");
  for (i in x){
    document.write("<tr><td style='padding-left:5px;'>"+i+"</td></tr>");
  }
  document.write("</tbody></table>");
}
//------------------------------------------
function siteSearch( startIndex ){
  var is_op = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_op) alert("К сожалению браузер Opera не поддерживает всех функций, необходимых для поиска по сайту\nВозпользуйтесь для поиска Firefox или Internet Explorer.\nПриносим извинения за неудобства. В будущем это будет исправлено")
  else {
    var txt = document.getElementById("searchedText").value
    if (txt != ""){
      document.getElementById("searchResultBlock").style.display = "block";  //отображение дивы результатов
      document.getElementById("info_blocks").style.display = "none";         //прячем инфоблоки
      makeSearch(txt, startIndex,'')
      return false;
    }
  }
}function openpage(pagenumber) {
  //отправляет постом номер выводимой страницы
  document.getElementById("startelement").value = pagenumber;
  a=document.getElementById("ProdPage");
  a.submit();
}

function getDims(winWidth, winHeight) {
	var dims = new Object();
	if (winWidth) {
		dims.width = winWidth;
		dims.scrollbars = false;
		if (screen.width < dims.width + 70) {
			dims.width = screen.width - 70;
			dims.scrollbars = true;
		}
	}

	if (winHeight) {
		dims.height = winHeight;
		if (screen.height < dims.height + 100) {
			dims.height = screen.height - 100;
			dims.scrollbars = true;
		}
	}
	dims.heightStr = (winHeight)? ',height=' + dims.height : '';
	dims.scrollbarsStr = (dims.scrollbars)? ',scrollbars=yes' : ',scrollbars=no';
	dims.width=(dims.scrollbars)? dims.width+17 : dims.width;
	dims.widthStr = (winWidth)? ',width=' + dims.width : '';
	dims.posX = Math.round((screen.width - dims.width) / 2);
	dims.posY = Math.round((screen.height - winHeight) / 2);
	dims.posCode = (document.all)? ',left=' + dims.posX + ',top=' + dims.posY : ',screenX=' + dims.posX + ',screenY=' + dims.posY;
	return dims;
}
function popupImg(imgSrc, winName, imgWidth, imgHeight, winTitle) {

	winWidth = (imgWidth)? imgWidth +0 : null;
	winHeight = (imgHeight)? imgHeight + 0 : null;
	var dims = getDims(winWidth, winHeight);
	var popupWin = window.open('', winName, 'menubar=no,toolbar=no,resizable=yes,status=yes' + dims.scrollbarsStr + dims.widthStr + dims.heightStr + dims.posCode);
	if (popupWin) {
		popupWin.document.open();
		popupWin.document.write('<html><head><title>' + winTitle + '</title></head><body bgcolor="white" style="margin: 0px 0px; padding: 0px;">')
		popupWin.document.write('<img src="' + imgSrc + '" width="' + imgWidth + '" height="' + imgHeight + '" />')
		popupWin.document.write('</body></html>')
		popupWin.document.close();
	}
	return false;
}