//         Работа с 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');
    }catch ( oError ) {
       try{	// Mozilla?
           this.doc = document.implementation.createDocument("","",null);
       }catch ( oError ) { return null }
    }
    root = this.doc.createElement("root")
    this.doc.appendChild(root)
    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);
      document.getElementById("check").firstChild.nodeValue = "Соединение: " + req.statusText
      // only if "OK"
      if (req.status == 200)  document.getElementById("searchResultBlock").innerHTML = req.responseText
      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)
//   res = ob.show(response)
//   alert(res.length)
}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 txt = document.getElementById("searchedText").value
   if (txt != ""){
      document.getElementById("searchResultBlock").style.display = "block";  //отображение дивы результатов
      document.getElementById("info_blocks").style.display = "none";         //прячем инфоблоки
//      window.open("", "_blank", "width=770, height=560, location=no,menubar=no, status=no, toolbar=no",false)
      makeSearch(txt, startIndex,'')
   return false;
   }
}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;
}
function sel_summ(a)
{
	var mes=document.getElementById('mes');
    var num_summ=parseInt(a.summ.value);
    var mons=parseInt(a.mons.value);	
    var percent=parseInt(a.percent.value);	
    var tmp=0;
    if(num_summ){
		if(mons){
			if(percent){
				calc_sum(a)
				mes.innerText="";
			}
		 else{	mes.innerText="введите процентную ставку ";	}
		}else{	mes.innerText="введите количество месяцов";	}
    }    else{	mes.innerText="введите сумму депозита";		}
}

function calc_sum(a)
{


    var srok=parseInt(a.mons.value);
    var summ1=parseInt(a.summ.value);
    var proc1=parseInt(a.percent.value);
	var check=a.checkbox.checked;
    if(proc1)
    {
	    if(check)
        {
			date_s=new Date();
			var syp=date_s.getFullYear();
			var smp=date_s.getMonth();
			var sdp=date_s.getDate();
			date_e=new Date(syp,smp+srok,sdp);
			var eyp=date_e.getFullYear();
			var emp=date_e.getMonth();
			var edp=date_e.getDate();				
			rez=get_dey_num(syp,smp+1,sdp,eyp,emp+1,edp,summ1,proc1,1)
			a.plus_sum.value=rez-summ1;
            a.result_sum.value=rez;

        }
        else
        {
			date_s=new Date();
			var syp=date_s.getFullYear();
			var smp=date_s.getMonth();
			var sdp=date_s.getDate();
			date_e=new Date(syp,smp+srok,sdp);
			var eyp=date_e.getFullYear();
			var emp=date_e.getMonth();
			var edp=date_e.getDate();			
			rez=get_dey_num(syp,smp+1,sdp,eyp,emp+1,edp,summ1,proc1,0)

            a.plus_sum.value=rez;
            a.result_sum.value=summ1+rez;
	    }
    }
    else
    {
        a.plus_sum.value="";
        a.result_sum.value="";
    }
}



function isbissextile(y)
{
	date=y%4;
	if(!date)return 1;
	else return 0;
}

function getColDey(y,m)
{
	if(m==2){d=28+isbissextile(y);}else if(m==4 || m==6 || m==9 || m==11){d=30;}else{d=31;}
	return d;
}
function calc_day_percent(summ1,proc1,col_day,year)
{
			proc=summ1/100*proc1;
		//	alert(proc/(365+isbissextile(year))+','+col_day+','+proc/(365+isbissextile(year))*col_day)
			return proc/(365+isbissextile(year))*col_day;
}

function get_dey_num(syp,smp,sdp,eyp,emp,edp,summ1,proc1,check)
{
	if(check)
	{
		for(i=syp;i<=eyp;i++)
		{
			if(syp==eyp){
				summ1+=calc_day_percent(summ1,proc1,getColDey(i,smp)-sdp,i);
				for(j=smp+1;j<=emp-1;j++){
				//alert(getColDey(i,j))
					summ1+=calc_day_percent(summ1,proc1,getColDey(i,j),i);
				}
				summ1+=calc_day_percent(summ1,proc1,edp-1,i);
			}
			else if(i==syp){
				summ1+=calc_day_percent(summ1,proc1,getColDey(i,smp)-sdp,i);
				for(j=smp+1;j<=12;j++){	
					summ1+=calc_day_percent(summ1,proc1,getColDey(i,j),i);
				}
			}
			else if(i==eyp){

				for(j=1;j<=emp-1;j++){
					summ1+=calc_day_percent(summ1,proc1,getColDey(i,j),i);
				}
						
				summ1+=calc_day_percent(summ1,proc1,edp-1,i);
			}
			else{
				for(j=1;j<=12;j++){	
					summ1+=calc_day_percent(summ1,proc1,getColDey(i,j),i);
				}
			}
		}
		return summ1;		
	}
	else
	{

		var summa=0;
		for(i=syp;i<=eyp;i++)
		{
			year_deys=0
			if(syp==eyp){
				year_deys+=getColDey(i,smp)-sdp;
				for(j=smp+1;j<=emp-1;j++){
					year_deys+=getColDey(i,j);
				}
				year_deys+=edp-1;
			}
			else if(i==syp){
				year_deys+=getColDey(i,smp)-sdp;
				for(j=smp+1;j<=12;j++){	
					year_deys+=getColDey(i,j);}
			}
			else if(i==eyp){
				for(j=1;j<=emp-1;j++){
					year_deys+=getColDey(i,j);}		
				year_deys+=edp-1;
			}
			else{
				for(j=1;j<=12;j++){	
					year_deys+=getColDey(i,j);}
			}
			
			summa+=calc_day_percent(summ1,proc1,year_deys,i);
		}
		return summa;
	}

}