/* опеределение какой именно радиопереключатель выбран    */
function getRadioValue(radioN)
{
for(i=0;i<document.calc[radioN].length;i++)
{
if (document.calc[radioN][i].checked == true)
return document.calc[radioN][i].value;
}
return '';
}
    function switch_(number)
    {
      str="#to"+number;
      str2="#l"+number;
      if  ($(str).css("display")=="none")
      {
        $('#to li a').html('<img src="/images/design/close.gif" />');
        $(str2).html('<img src="/images/design/open.gif" />');
        $('#to ul').hide();
        $(str).show('slow');
      }
      else
      {
        $(str2).html('<img src="/images/design/close.gif" />');
        $(str).hide();
      }
    }
    function switch1(number)
    {
      str="#from"+number;
      str2="#fl"+number;
      str3="#i"+number;
      if  (($(str).css("display")=="none"))//||( $(str3).css("color")!="#000000"))
      {
        $('#from li a').html('<img src="/images/design/close.gif" />');
        $(str2).html('<img src="/images/design/open.gif" />');
        $('#from ul').hide();
        $(str).show('slow');
      }
      else
      {
        $(str2).html('<img src="/images/design/close.gif" />');
        $(str).hide();
      }
    }
/* очистить все */
function all_clear()
{
    clear();
    $('#total').html('&nbsp;');
    $('#order').hide("slow");
    $('#num_pallet').hide(); 
     hideC('num_km27');
     hideC('num_km28'); 
}
function showP()
{
    $('#num_pallet_p').show("slow"); 
}
function hideP()
{
    $('#num_pallet_p').hide("slow"); 
}
function showC(str)
{
    $('#'+str).show("slow"); 
}
function hideC(str)
{
    $('#'+str).hide(); 
}
/* спрятать появивщиеся елементы */
function hide()
{
     $("#num_pallet").hide();
     $("#num_konvert").hide();
     $('#num_pallet').hide(); 
     $("#num_weight").hide();
     $('#tarif_insurance').html('1');
     $('#prices').html('');
     document.calc.reset();
}

function change_city()//отображение информации, зависящей от городов
    {
    clear();
    var cA=document.calc.from.value;
    var cB=document.calc.to.value;
    /*if(cA==cB)
        {
        alert("Начальный и конечный пункты маршрута не могут совпадать.\nВыберите города заново.");
        document.calc.reset();
        hide();
        $("#to span").css("color","#000000");
        $("#to ul").hide();
        $("#from span").css("color","#000000");
        $("#from ul").hide(); 
        document.calc.from.value=0;
        document.calc.to.value=0;
        all_clear();  
        return false;
        }
        else
        {
          if(cA==0) return false;
          if(cB==0) return false;
        }  */
    }
    
 function pallet_v(type)
 {
  if (type==3)
  {
  $("#num_pallet").show("slow");
  $("#num_konvert").hide("slow");
  }
  else
  {
   $("#num_pallet").hide("slow");
  $("#num_konvert").show("slow");
  }
  $("#num_weight").hide("slow");
 }
  function pallet_h()
 {
    $("#num_pallet").hide("slow");
    $("#num_konvert").hide("slow"); 
    $("#num_weight").show("slow");
 }
 function not_num(th)
{
    if(isNaN(th.value))
    {
        var tmp=parseFloat(th.value);
        th.value=(isNaN(tmp))?0:tmp;
    }
}
function roundEx(x)
{
    return(Math.round(x*100)/100);
}
function block()
{
    document.calc.bwidth.disabled=!document.calc.bwidth.disabled;
    document.calc.bheight.disabled=!document.calc.bheight.disabled;
    document.calc.blength.disabled=!document.calc.blength.disabled;
    document.calc.bvolume.disabled=!document.calc.bvolume.disabled;
}
function plus_constant(th,num)
{
    if (th.checked){
    var sum=0;
    if (document.calc.elements["text"+num].value=='')
        sum=0;
        else
        sum=document.calc.elements["text"+num].value
    $("#item"+num).html(sum+"");
    }
      else
        $("#item"+num).html("0"); 
}
function colorFr(th,num)
{
//str='#i'+document.calc.from.value;
//alert ( str);
//alert ( $(str).css("color"));
//  $(str).css("color","blue");
  $("#from span").css("color","#000000");
  $(th).css("color","#e14658");
  document.calc.from.value=num;
}
function colorTo(th,num)
{
  $("#to span").css("color","#000000");
  $(th).css("color","#e14658");
  document.calc.to.value=num;
}
function plus_constant2(name,per,min,def)
{
    var sum=0;
    html_span='#item'+name;
    var cost=document.calc.elements["text"+name].value;
     if (document.calc.elements["item"+name].checked){
    if(cost!="")
        {
        if(cost<def) sum=min;
        if(cost>def)
         sum=cost*per;
        }
        else
        {
         sum=min;
        }
     }
        if (sum!=0) sum=roundEx(sum);
       $(html_span).html(sum+""); 
   
   }
function calc_volume()
    {
    cargo_vol = document.calc.bwidth.value*document.calc.bheight.value*document.calc.blength.value/1000000;
    document.calc.bvolume.value = cargo_vol;
    calculate_select();
    }
function calculate_select()
    {
    var rate_v;
    var rate_w;
    if ($("#tarif_v").html()==null) 
         rate_v=0;
         else
           rate_v=parseFloat($("#tarif_v").html()); 
    if ($("#tarif_w").html()==null) 
         rate_w=0;
         else
          rate_w=parseFloat($("#tarif_w").html());
    var cost_by_weight=rate_w*document.calc.w.value;
    var cost_by_volume=rate_v*document.calc.bvolume.value;
    cost_by_volume=roundEx(cost_by_volume);
    cost_by_weight=roundEx(cost_by_weight);
    if (cost_by_weight==0)
     $("#coast_w").html('0');
    else
     $("#coast_w").html(cost_by_weight);
    if (cost_by_volume==0)
     $("#coast_v").html('0');
    else
     $("#coast_v").html(cost_by_volume);
   }
   function calculate_palet(type)
    {
    var rate_v; 
    if ($("#tarif_p").html()==null) 
         rate_v=0;
         else
           rate_v=parseFloat($("#tarif_p").html()); 

    if (type==3)
    {
    var cost_by_volume=rate_v*document.calc.num_pal.value;
    document.calc.text26.value=document.calc.num_pal.value;
    cost_by_volume=roundEx(cost_by_volume);
    if (cost_by_volume==0)
     $("#coast_p").html('0');
    else
     $("#coast_p").html(cost_by_volume);
    }
   else
    {
    var cost_by_volume=rate_v*document.calc.num_pal2.value;
    cost_by_volume=roundEx(cost_by_volume);
    if (cost_by_volume==0)
     $("#coast_k").html('0');
    else
     $("#coast_k").html(cost_by_volume);
    }
   }
function calc_per(name,per,min,def)//расчет процента от стоимости
    {
    var sum=0;
    html_span='#item'+name;
    var cost=document.calc.elements["text"+name].value;
    if(cost!="")
        {
        if(cost<=def) sum=min;
        if(cost>def)
         sum=cost*per;
        }
        else
        {
         sum=min;
        }
        if (sum!=0) sum=roundEx(sum);
       $(html_span).html(sum+"");  
     }
function clear() {
     $('#coast_w').html('0');
     $('#coast_v').html('0');
     $('#coast_p').html('0');
     $('#coast_k').html('0');
     }
     function refresh () {
      $.ajax({
        type: "POST",
        data: "task=subfrom",
        url: "/calc.php",
        success: function(msg){
//        alert(msg);
    $("#subForm").html( msg );
    } });}
function send () {
     all_clear();
    var type=getRadioValue('type');
    if (document.calc.from.value==0) return false;
    if (document.calc.to.value==0) return false;
    if (!type) return false;
      $.ajax({
        type: "POST",
        data: "task=sql&from="+document.calc.from.value+"&to="+document.calc.to.value+"&type="+type,
        url: "/calc.php",
        success: function(msg){
//        alert(msg);
    $("#prices").html( msg );
    if (msg.indexOf('по даному направлению нет')!=-1)
    {
//     alert("К сожалению, перевозок по даному направлению нет!!!");
        //document.calc.reset();
//        hide();
//        all_clear();
        return false;
    }
    else
    {
    if (type==1 || type==3)
      pallet_v(type);
      else 
      pallet_h(); 
    calculate_select();
    }
  } 
        });
        //calculate_select();    
    }//);
    function check_all()//проверка заполнения всех полей перед расчетом
    {
    var err='';
    if(document.calc.from.value==0||document.calc.to.value==0)
    {
        err+='Выберите начальный и конечный пункт маршрута.\n';
    }
    if(/*document.calc.type[2].checked || */document.calc.type[1].checked)
    {
     if((!document.calc.num_pal.value || document.calc.num_pal.value==0))// && (document.calc.type[2].checked))
    {
        err+='Пожалуйста, заполните поле "Количество палет".\n';
    }
   // if((!document.calc.num_pal2.value || document.calc.num_pal2.value==0) && (document.calc.type[1].checked))
//    {
//        err+='Пожалуйста, заполните поле "Количество конвертов".\n';
//    }
    }
    if(document.calc.type[0].checked)
    {
    if((document.calc.volume[1].checked)&&(!document.calc.bvolume.value || document.calc.bvolume.value==0))
    {
        err+='Пожалуйста, заполните поле "Объем".\n';
    }
    if((document.calc.volume[0].checked)&&(!document.calc.bwidth.value||!document.calc.bheight.value||!document.calc.blength.value))
    {
        err+='Пожалуйста, заполните поля пункта "Габариты".\n';
    }
    if(!document.calc.w.value || document.calc.w.value==0)
    {
        err+='Пожалуйста, заполните поле "Вес".\n';
    }
    }
    if($("#total").html()=="") 
    {
      err+='Сначала необходимо выполнить подсчет.\n';
    }
    if (err!='')
    {
     alert('Вы допустили следующие ошибки:\n'+err);
    }
    else
    {
      total();
    }
         
}
function total()//расчет общей стоимости
    {
     var coast_w=parseFloat($("#coast_w").html());
     var coast_v=parseFloat($("#coast_v").html());
     var coast_p=parseFloat($("#coast_p").html());
     var coast_k=parseFloat($("#coast_k").html());
     var cost_cargo=Math.max(coast_w, coast_v);
     var total=0;
    for( var i=0;i<document.calc.elements.length;i++){ 
    if (document.calc.elements[i].type=='checkbox'){
     if(document.calc.elements[i].checked);
       total+=parseFloat($("#"+document.calc.elements[i].name).html());}
      }  
//     if(document.calc.type[2].checked || document.calc.type[1].checked){
       if (document.calc.type[1].checked)  /* total+=coast_k;
       else*/ 
       {
        total+=coast_p; //}
     }
     else 
       total+=cost_cargo;
     total=roundEx(total);
    if (total<10) total=10;
    string = '<h2 class="calc">Общая стоимость доставки = '+total+' грн.</h2>';

    $('#order').show("slow");  
    $('#total').html(string);     
    document.calc.all.value=total;
    }
       function calculate_hidden()
    {
     for( var i=0;i<calc.elements.length;i++){ 
      if (document.calc.elements[i].type=='checkbox'){
     if(document.calc.elements[i].checked){
     var k=0;
       k=calc.elements[i].name.substring(document.calc.elements[i].name.indexOf('item')+4);
       document.calc.elements['hid'+k].value=$('#item'+k).html();
      }
      }
    }
    return false;
    }
