function show_hide(elmnt)
{
 document.getElementById(elmnt).style.display=(document.getElementById(elmnt).style.display != 'block' ? 'block' : 'none');
}

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 chang_img(div1,div2)
{
  $(div1).style.display='none';
  $(div2).style.display='block';
}

function show_phone_stat()
{
  new Ajax.PeriodicalUpdater('phone_stat', './phone_stat.inc.php',
      {
        frequency: 15,
        decay: 5
      });
}

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 leftmenu(imgid,status)
{
  if(status==0)clas="left_menu_0";else clas="left_menu_1";
  document.getElementById(imgid).className=clas;
}
function topmenu(imgid,status)
{
  if(status==0)clas="top_menu_0";else clas="top_menu_1";
  document.getElementById(imgid).className=clas;
}

//Калькулятор Эрланга

      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

         }
      }
//Калькулятор эрланга

