
function check_zakaz()
{ // функция проверки полей формы

  if (document.forms.zakaz.zakaz_name.value != ""){} else
  {
    alert("\nПоле \"ФИО\" не заполенно. \n\nПожалуйста, Представьтесь!");
    document.forms.zakaz.zakaz_name.focus();
    return false;
  }

  if (document.forms.zakaz.zakaz_company.value != ""){} else
  {
    alert("\nПоле \"Компания\" не заполенно. \n\nПожалуйста, заполните!");
    document.forms.zakaz.zakaz_company.focus();
    return false;
  }

  if (document.forms.zakaz.zakaz_kolvo.value != ""){} else
  {
    alert("\nПоле \"Кол-во\" не заполенно. \n\nПожалуйста, заполните необходимое кол-во товара!");
    document.forms.zakaz.zakaz_kolvo.focus();
    return false;
  }

 var phonehome=document.forms.zakaz.zakaz_tel.value;
 if(phonehome != "")
 {
  if(phonehome.length<7 || phonehome.length>20)
  {
    alert("\nНомер телефона введен неверно. \n\nПожалуйста, введите правильный номер телефона!");
    document.forms.zakaz.zakaz_tel.focus();
    return false;
  }
 }
 else
 {
    alert("\nНомер введен неверно. \n\nПожалуйста, введите правильный номер телефона!");
    document.forms.zakaz.zakaz_tel.focus();
    return false;
 }
}


function stock_search(caption,money,div)
{
		var url = 'stock_search.php';
		var pars = 'div' + div + '&caption=' + caption + '&money=' + money;
		var myAjax = new Ajax.Request(
					url,
					{method: 'post', parameters: pars, onComplete: showResponse}
					);

    function showResponse(originalRequest)
    {
		  //put returned XML in the textarea
		  $(div).innerHTML = originalRequest.responseText;
    }
}

function price_search(id,money,div,table)
{
		var url = 'price_search.php';
		var pars = 'div' + div + '&id=' + id + '&table=' + table+ '&money=' + money;
		var myAjax = new Ajax.Request(
					url,
					{method: 'post', parameters: pars, onComplete: showResponse}
					);

    function showResponse(originalRequest)
    {
		  //put returned XML in the textarea
		  $(div).innerHTML = originalRequest.responseText;
    }
}

function selectAll(Element,Name)
{
  DOM=(typeof(document.getElementById)!='undefined');var top={};var quote_sign='>';
  if(DOM)
  {
    var form_elements=Element.form.elements;
    for(var i=1,l=form_elements.length;i<l;i++)
    {
      if(form_elements[i].id==Name)
      {
        form_elements[i].checked=Element.checked;
      }
    }
  }
}


function unsubscribe(umail,cod,div)
{
		var url = 'unsubscribe.inc.php';
		var pars = 'div' + div + '&umail=' + umail + '&cod=' + cod;
		var myAjax = new Ajax.Request(
					url,
					{method: 'post', parameters: pars, onComplete: showResponse}
					);

    function showResponse(originalRequest)
    {
		  //put returned XML in the textarea
		  $(div).innerHTML = originalRequest.responseText;
    }
}

//backup базы стоков и структуры каталога начало
function restore_stocks()
{

  var url = './restore_stocks.php';

  var pars = 'mode=script';
	var myAjax = new Ajax.Request(
					url,
					{method: 'post', parameters: pars, onComplete: showResponse}
					);
    function showResponse(originalRequest)
    {
		  //put returned XML in the textarea
		  //$(div).innerHTML = originalRequest.responseText;
      //alert(originalRequest.responseText);
      //alert("Загрузил данные!");
    }
}
//backup базы стоков и структуры каталога конец

function subscribe(mail)
{

  //$('subscribe').innerHTML = "dddd";
  new Ajax.Request('./subscribe.php',
  {
    method: 'get',
    parameters: {email: mail},
    onComplete: finish_request,
    div: 'subscribe'
  });

  /*var myAjax = new Ajax.Request("./subscribe.php",
  {
    method: 'get',
    parameters: "email="+mail,
    onComplete: finish_request,
    div: 'subscribe'
  });*/
}

function finish_request(request)
{
	alert(request.responseText);
}

function plus_minus(imgid,host)
{
  minus=host+'/images/minus2.jpg';
  plus=host+'/images/plus2.jpg';
  if(document.getElementById(imgid).src==plus)document.getElementById(imgid).src=minus; else document.getElementById(imgid).src=plus;
}
function calc_dalee(imgid,host)
{
  minus=host+'/images/'+imgid+'_on.jpg';
  plus=host+'/images/'+imgid+'_off.jpg';
  if(document.getElementById(imgid).src==plus)document.getElementById(imgid).src=minus; else document.getElementById(imgid).src=plus;
}
function selectStatus() {
if (document.registration.status.value == '1') menu2.style.display = "none";
if (document.registration.status.value == '2') menu2.style.display = "";
}

function show_hide(elmnt)
{
 document.getElementById(elmnt).style.display=(document.getElementById(elmnt).style.display != 'block' ? 'block' : 'none');
}

function showLogin(){
 document.getElementById('login').style.display=(document.getElementById('login').style.display != 'block' ? 'block' : 'none');
}

function showdate()
{
  today=new Date();// Build an array initializer
  function isnArray()
  {
    argnr=isnArray.arguments.length
    for (var i=0;i<argnr;i++)
    {
      this[i+1] = isnArray.arguments[i];
    }
  }
  // And months and day arrays
  var isnMonths=new   isnArray("Января","Февраля","Марта","Апреля","Мая","Июня","Июля","Августа","Сентября","Октября","Ноября","Декабря");
  var thisyear = today.getFullYear(); // varies in JavaScript and JScript

  var isnDays=new   isnArray("Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота");
  var thisday = today.getDay(); // varies in JavaScript and JScript

  document.write(" "+isnDays[today.getDay()+1]+",  "+today.getDate()+" "+isnMonths[today.getMonth()+1]+"  "+thisyear+" г.")
}

function ChangeImg() {
 if(document.images) {
  eval("document."+ChangeImg.arguments[0]+
  ".src=('"+ChangeImg.arguments[1]+"')");
 }
}

function showmenu(elmnt)
{
document.getElementById(elmnt).style.visibility="visible"
}
function hidemenu(elmnt)
{
document.getElementById(elmnt).style.visibility="hidden"
}

v=0;

function ShowMap(path,w,h)
{
	if (v!=0) v.close();
	h+=30;
	v=window.open ('', 'view', 'scrolling=no,height='+h+',width='+w);
	with (v.document)
	{
	    open ();
	       write('<html><head><title>Карта проезда</title></head><body topmargin=0 leftmargin=0 marginheight=0 marginwidth=0 ><table cellspacing="0" cellpadding="0" border="0"><tr><td align><img src="'+path+'" border=0></td></tr><tr><td align="center" valign="middle" height="30"><a href="javascript:;" onClick="window.close()">[ закрыть окно ]</a></td></tr></table></body></html>');
	    close ();
	}
	return false;
}

v=0;
function ShowPhoto(path,w,h,name)
{
  if (v!=0) v.close();
  //h=130;
  v=window.open ('', 'view', 'scrolling=no,height='+h+',width='+w);
  with (v.document)
{
 open ();
  write('<html><head><title>'+name+'</title></head><body topmargin=0 leftmargin=0 marginheight=0 marginwidth=0 bgcolor="white"><table cellspacing="0" cellpadding="0" border="0"><tr><td align><img src="'+path+'"     border=0></td></tr></table></body></html>');
  close ();
}
	return false;
}

function popup(fileUrl, winW, winH, winN, scrollB) {
var winWidth = (winW)? winW : 200;
var winHeight = (winH)? winH : 200;
var winName = (winN)? winN : 'popupWin';
var scrollBars = (scrollB)? scrollB : 'auto'
posX = Math.round((screen.width - winWidth) / 2);
posY = Math.round((screen.height - winHeight) / 2);
posCode = "left="+posX+",top="+posY;
var popupWin = window.open(fileUrl, winName,"menubar=no,toolbar=no,scrollbars=" + scrollBars + ",status=yes,width=" + winWidth + ",height=" + winHeight + "," + posCode);
if (popupWin) popupWin.focus();
}

function makedate()
            {
              document.forms.booking.dd.value = document.forms.booking.outDay.value +"/"+ document.forms.booking.outMonth.value +"/"+document.forms.booking.outYear.value
              document.forms.booking.ad.value = document.forms.booking.inDay.value +"/"+ document.forms.booking.inMonth.value +"/"+document.forms.booking.inYear.value
              document.forms.booking.inYear.value=''
              document.forms.booking.inDay.value=''
              document.forms.booking.inMonth.value=''
              document.forms.booking.outYear.value=''
              document.forms.booking.outDay.value=''
              document.forms.booking.outMonth.value=''
            }
function check_model_questions()
{ // функция проверки полей формы

  if (document.forms.questions.name.value != "")
  {}
  else
  {
    alert("\nПоле \"Имя\" не заполенно. \n\nПожалуйста, введите Ваше имя!");
    document.forms.questions.name.focus();
    return false;
  }

  if (document.forms.questions.email.value != "")
  {}
  else
  {
    alert("\nПоле \"E-mail\" не заполенно. \n\nПожалуйста, введите адрес электронной почты!");
    document.forms.questions.email.focus();
    return false;
  }

  if (document.forms.questions.question.value != "")
  {}
  else
  {
    alert("\nПоле \"Вопрос\" не заполенно. \n\nПожалуйста, введите Свой вопрос!");
    document.forms.questions.question.focus();
    return false;
  }
}

//Калькулятор Эрланга

      var g_eps = 0.0000001;   // g_eps serves as an arbitrary lower limit
                               //  for values P(c) and rho
      var g_precision = 4;     // number sig digits when converting to exp.

      // Erlang's: algorithm 1 - Erlang
      function erlang(rho,c)
      {
        if (rho == 0) {

          // P(c) = 0.0 for a rho of 0.
          return 0.0;

        } else {

          var s = 0.0;
          for (var i = 1; i <= c; i++)
          {
            s = (1.0 + s) * (i/rho);
          }
          return (1.0/(1.0+s));

        }
      }

      // Erlang's: algorithm 2 - FindLine
      function findline(rho,p)
      {
        // NB: The following assertions are handled in validation functions
        // Assert that p is between 0 and 1
        // Assert that rho is greater than a small positive tolerance

        // Start with initial interval:
        var l = 0;
        var r = Math.ceil(rho);

        // Evaluate at the left and right endpoints.
        // var fL = erlang(rho,l);
        var fR = erlang(rho,r);

        // Find an initial interval so that fL > p and fR <= p.
        while (fR > p) {
          l = r;
          r += 32;	// arbitrary constant that corrects most cases
        //  fL = fR;
          fR = erlang(rho,r);
        }

        // Half the interval and keep (r-l) > 1  //, fL > p, and fR <= p.
        while ( (r-l) > 1 )	{

          // calculate the midpoint
          var mid  = Math.ceil((l+r)/2);

          // evaluate at the midpoint
          var fMid = erlang(rho,mid);

          // adjust the appropriate endpoint
          if (fMid > p) {
            l = mid;
          } else {
            r = mid;
          }
        }

        return (r);
      }

      function validate_lambda(textlambda)
      {
          if ((parseFloat(textlambda.value) != textlambda.value)
		|| (textlambda.value < 0))
          {
             alert("Value for lambda must be a positive integer!");
             textlambda.value = "";
             return false;
          }
        return true;
      }


      function validate_talk_time(text_talk_time)
      {
          if ((parseFloat(text_talk_time.value) != text_talk_time.value)
		|| (text_talk_time.value <= 0))
          {
             alert("Зачение средней длительности разговора должно быть положительным целым числом.");
             text_talk_time.value = "";
             return false;
          }
        return true;
      }

      function validate_prob(textProb)
      {
        with (document.F_Erlang) {
          var message = "Вероятность должна быть в пределах от 0.1e-7 до 1";
          if ((parseFloat(textProb.value) != textProb.value)
                || (textProb.value >= 1.0) )
          {
             alert(message);
             textProb.value = "";
             return false;
          } else if (textProb.value < g_eps )
          {
            message = "Алгоритм вычислений требует, чтобы значение вероятности было больше чем "
			 + g_eps + ".  Вероятность установлена в значение " + g_eps;
            alert(message);
            textProb.value = g_eps;
            return true;
          }
        }
          return true;
      }

      function isEmpty(textfield)
      {
        if (textfield.value=="") {return true}
           else {return false}
      }

      // Helper functions

      function raise(x,y)
      {
        // returns x^y
        return (Math.pow(x,y));
      }

      function RealToExp(n,p)
      {
        // takes a decimal number n and converts it to exponential form
        // xxxexx with p significant digits.  Exponents of 0 are ignored.
        // note: this function returns a string

        var x = n;    // copy of the n
        var z = 0;    // current exponent of x

        if (x == 0) {
          // "0" doesn't need exponential notation
          return ("0.0");
        }

        if (x<1) { // the exponent will be negative

          // lower the exponent until the decimal is in the right place.
          while (x<1) {
            x *= 10;
            z -= 1;
          }

          // round to the right number of significant digits.
          x = Math.round(x*(raise(10,p)))/(raise(10,p));

        } else { // the exponent will be positive

          // raise the exponent until the decimal is in the right place.
          while (x>=10) {
            x /= 10;
            z += 1;
          }

          // round to the right number of significant digits.
          x = Math.round(x*(raise(10,g_precision)))/(raise(10,g_precision));

        }

        // format the output for consistency:
        if (z==0) {
          return (x);
        } else if ((-10 < z) && (z < 0)) {
          return (x + "e-0" + Math.abs(z));
        } else if (z<10) {
          return (x + "e0" + z);
        } else {
          return (x + "e" + z);
        }

      }



    // given: arrival rate, service rate
    // Outputs the table: probability of turn away, capacity / number of lines.
    function DoCalculations()
    {
        var nNumOfLines = 0;
        var fProbability = 0.001;
		var strTable = "";
		var nNumRows = 0;

         with (document.F_Erlang)
         {
             if ( isEmpty(TEXT_arrivalrate))
             {
		   		alert("Поле  частоты возникновения звонков пустое!");
		   		return;
             }
             if (isEmpty(TEXT_average_talk_time_sec))
             {
		   		alert("Поле средней длительности звонка пустое!");
		   		return;
             }

             if (!validate_lambda(TEXT_arrivalrate) || !validate_talk_time(TEXT_average_talk_time_sec))
             {
                return;
             }

             // arrivalrate == lambda == arrival rate (calls/hour)
             // servicerate == mu == 1 hour / average_talk_time == 3600 / average_talk_time_sec;
             // Rho = lambda / mu = lambda * talk_time_sec / 3600.

             tempRho = (TEXT_arrivalrate.value * TEXT_average_talk_time_sec.value) / 3600;
             if (tempRho < g_eps )
             {
                 alert("Недопустимые значения средней длительности звонка и/или частоты возникновения звонков, задайте другие значения.");
                 return;
             }

		    strTable = "<b>Результаты:</b><br><br><table border=1 width=280 cellspacing=0 cellpadding=4 bordercolor='#C0C0C0' style='border-collapse: collapse'>";
            strTable += "<tr><td width=150 align=center><b>Вероятность услышать сигнал &quot;Занято&quot;</b></td>";
            strTable += "<td width=130 align=center><b>Количество линий</b></td></tr>";

             // calculate capacity / number of lines
             //TEXT_numoflines.value = findline(tempRho, TEXT_servicegrade.value);

	        fProbability = 0.90;
	        fDecrement = 0.10;
	        fEndValue = 0.05;
    	    while (fProbability > fEndValue)
    	    {
	    		nNumOfLines = findline(tempRho, fProbability);

 				strTable += "<tr>"
 				strTable += "<td align='center'>" + Math.round(fProbability * 100) + " %</td>"
 				strTable += "<td align='center'>" + Math.round(nNumOfLines) + "</td>"
  				strTable += "</tr>"

        	  fProbability -= fDecrement;
	        }

	        fProbability = 0.05;
	        fDecrement = 0.01;
	        fEndValue = 0.009;
    	    while (fProbability > fEndValue)
    	    {
	    		nNumOfLines = findline(tempRho, fProbability);

 				strTable += "<tr>"
 				strTable += "<td align='center'>" + Math.round(fProbability * 100) + " %</td>"
 				strTable += "<td align='center'>" + Math.round(nNumOfLines) + "</td>"
  				strTable += "</tr>"

        	  fProbability -= fDecrement;
	        }

	        //fProbability = 0.010;
	        //fDecrement = 0.001;
	        //fEndValue = 0.00099;
    	    //while (fProbability > fEndValue)
    	    //{
	    	//	nNumOfLines = findline(tempRho, fProbability);
 			//	strTable += "<TR>"
 			//	strTable += "<TD>" + fProbability * 100 + " %</TD>"
 			//	strTable += "<TD>" + Math.round(nNumOfLines) + "</TD>"
  			//	strTable += "</TR>"
    	    //
        	//  fProbability -= fDecrement;
	        //}

				strTable += "</TABLE>"
        			PlaceHolder.innerHTML = strTable

         }
      }
//Калькулятор эрланга
