cCity = {
 Orel:{ 
        // проекты первого типа
        price1: 90,      // оплата промоутеру
        price2: 170,     // оплата супервайзеру
        price3: 250,     // оплата за координацию проекта
        
        // проекты второго типа
        price4: 90,      // оплата мерчендайзера, аудитора, тайного покупателя
        price5: 250,     // координация проекта
        
        // дополнительные взаимоисключающие коэффициенты для проектов первого типа
        k1: 1,   // стандартный промоутер         
        k2: 1.2, // промоутер 21+
        k3: 1.5, // промоутеры модельной внешности
        k4: 4,   // модели
        k5: 2,   // ростовые фигуры
        
        // дополнительный коэффициент для проектов первого типа 
        k6: 1.5,  // работа в ночное время 
        
        // дополнительные взаимоисключающие коэффициенты для проектов первого типа
        k7: 1,  // супервайзер на автомобиле
        k8: 0.8,  // супервайзер пеший
        
        // дополнительные взаимоисключающие коэффициенты для проектов второго типа          
        k9: 1,    // контроль от 1 до 5 товарных позиций
        k10: 1.2, // контроль от 6 до 15 товарных позиций
        k11: 1.5, // контроль от 16 до 30 товарных позиций  
        
        // дополнительные не взаимоисключающие коэффициенты для проектов второго типа       
        k12: 1.2,  // фотоотчет
        k13: 1.5   // вручение призов, заполнение анкет
      },
 
 Bryansk:{ price1:100, price2:20, price3:30, price4:50, price5:55,
        k1:1, k2:2, k3:3, k4:4, k5:15, k6:89, k7:7, k8:8, k9:9, k10:10, k11:11, k12:12, k13:13
      }     
};


function calculate() {
  document.getElementById('result1').innerHTML = '&nbsp;';
  document.getElementById('result2').innerHTML = '&nbsp;';
  
  var form = document.calc;
  var sum  = 0;
  var formulaNumber = form.formula_nomer.value;
  var cityPrice = 0;
  var i = 0;
  var valid = false;
  var formula = '';
  var employes = '';
  var num_cities = 0;   
  for(i=0; i < form.in_city.length; i++) {
    if(form.in_city.item(i).checked && cCity[form.in_city.item(i).value] ) {
      num_cities++;
    }   
  }
  
  if( formulaNumber == 1 ) {
    var input1 = form.inp1.value;
    var input2 = form.inp2.value;
    var input3 = form.inp3.value;
    var input4 = form.inp4.value;
    
    var option = false;
    for( i=0; i < form.dopoptions.length ; i++) {
       if(form.dopoptions.item(i).checked) option = form.dopoptions.item(i).value;
    }

    var skidka = false;
    if(form.skidka.checked) skidka = form.skidka.value;  
    
    var paymethod = false;
    for( i=0; i < form.paymethod.length ; i++) {
       if(form.paymethod.item(i).checked) paymethod = form.paymethod.item(i).value;
    }
    
    valid   = input1.search(/^[0-9]+$/i) != -1 && input2.search(/^[0-9]+$/i) != -1 && input3.search(/^[0-9]+$/i) != -1 && input4.search(/^[0-9]+$/i) != -1;
    formula = "cityPrice = ( input1 * input2 * input3 * input4 * city['price1'] * city[option] * (skidka ? city[skidka] : 1) " +
                  "+ Math.ceil( input1 / 5) * input3 * input4 * city['price2'] * city[paymethod] "+
                  "+ input4 * city['price3'] ) * 1.25 ;";
    employes = rus_numeric( (input1 * input2 * num_cities ) , "промоутеров", "промоутер", "промоутера", "промоутеров" ) + "<br>" + 
               rus_numeric( (Math.ceil(input1 / 5)*num_cities), "супервайзеров", "супервайзер", "супервайзера", "супервайзеров" ) + "<br>" +  "1 координатор";               
  }
  
  if( formulaNumber == 2 ) {
    var input5 = form.inp5.value;
    var input6 = form.inp6.value;
    var input7 = form.inp7.value;
    
    valid   = input5.search(/^[0-9]+$/i) != -1 && input6.search(/^[0-9]+$/i) != -1 && input7.search(/^[0-9]+$/i) != -1 ;  
    
    var option = false;
    for( i=0; i < form.controls.length; i++ ) {
       if(form.controls.item(i).checked) option = form.controls.item(i).value;
    }
    
    var fotoreport = false;
    if(form.fotoreport.checked) fotoreport = form.fotoreport.value;  
    
    var ankets = false;
    if(form.ankets.checked) ankets = form.ankets.value;  
    formula = "cityPrice = (input6 * input7 * city['price4'] * city[option] * (fotoreport ? city[fotoreport] : 1) * (ankets ? city[ankets] : 1) + input5 * city['price5'] ) *1.25 ;";
    
    var akc = form.formula_nomer.options[ document.calc.formula_nomer.selectedIndex ].text;
    
    var combien = input6 * input7 * num_cities; 
    
    if( akc == 'Мерчандайзинг' ) 
       employes = rus_numeric( combien , "мерчандайзеров", "мерчандайзер", "мерчандайзера", "мерчандайзеров" );
    
    if( akc == 'Аудит' ) 
       employes = rus_numeric( combien , "аудиторов", "аудитор", "аудитора", "аудиторов" );   
    
    if( akc == 'Тайный покупатель' ) 
       employes = rus_numeric( combien , "тайных покупателей", "тайный покупатель", "тайных покупателя", "тайных покупателей" );   
    
    employes += "<br>1 координатор";   
  }    
  
  if( !valid ) {
    return;
  }
  
  for(i=0; i < form.in_city.length; i++) {
    if(form.in_city.item(i).checked) {
      if(!cCity[form.in_city.item(i).value]) continue;
      city = cCity[form.in_city.item(i).value];
      eval(formula);
      sum += cityPrice;
    }   
  }
  if(!sum) return;
  
  sum2 = sum * 1.18;
  
  document.getElementById('result1').innerHTML = currencyFormat(sum, 10);
  document.getElementById('result2').innerHTML = currencyFormat(sum2, 0.01);
  document.getElementById('employes').innerHTML = employes;
  
  document.getElementById('price_area').style.display = 'block';
  
}

function currencyFormat(num, dec) {
  num = Math.round( num / dec ) * dec ;
  num = new Number(num).toFixed( dec > 1 ? 0 : 2 );
  var s = 0;
  var str = '';
  for( var i=num.toString().length-1; i>=0; i-- ) {
    s++;
    str = num.toString().charAt(i) + str;
    if(num.toString().charAt(i)=='.') s=0;
    if( s > 0 && !(s % 3) ) str  = " " + str;
  } 
  str += " руб.";  
  return str;         
}

function rus_numeric(n, var1, var2, var3, var4 ) {    
    var nmod10 = n % 10;
    var nmod100 = n % 100;
    if(!n) {
      var str = var1;
    } 
    else if( (n == 1) || ( nmod10 == 1 && nmod100 != 11)) {
      var str = n + '&nbsp;' + var2;
    } 
    else if ( ( nmod10 > 1) && (nmod10 < 5) && (nmod100 != 12 && nmod100 != 13 && nmod100 != 14)) {
      var str = n + '&nbsp;' + var3;
    } 
    else {
      var str = n + '&nbsp;' + var4;
    }
    return str;
}


function city_change() {
  var form = document.calc;
  var flag = 0;   
  for(i=0; i < form.in_city.length; i++) {
    if(form.in_city.item(i).checked) {
      flag = 1;
      break;
    }   
  }
  if(flag) {
    if( form.formula_nomer.value == '1' ) {
      document.getElementById('input1_area').style.display = 'block';
      document.getElementById('input2_area').style.display = 'none';
      document.getElementById('options1_area').style.display = 'block';
      document.getElementById('options2_area').style.display = 'none';
    }
    else if(form.formula_nomer.value == '2') {
      document.getElementById('input1_area').style.display = 'none';
      document.getElementById('input2_area').style.display = 'block';
      document.getElementById('options1_area').style.display = 'none';
      document.getElementById('options2_area').style.display = 'block';
    }
    document.getElementById('calc_button').style.display = 'block';
  }
  else {
    document.getElementById('input1_area').style.display = 'none';
    document.getElementById('input2_area').style.display = 'none';
    document.getElementById('options1_area').style.display = 'none';
    document.getElementById('options2_area').style.display = 'none';
    document.getElementById('price_area').style.display = 'none';
    document.getElementById('calc_button').style.display = 'none';           
  }
}

function type_change() {
   document.getElementById('input1_area').style.display = 'none';
   document.getElementById('input2_area').style.display = 'none';
   document.getElementById('options1_area').style.display = 'none';
   document.getElementById('options2_area').style.display = 'none';
   document.getElementById('price_area').style.display = 'none';
   document.getElementById('calc_button').style.display = 'none'; 
   
   if(document.calc.formula_nomer.value) {
     document.getElementById('city_area').style.display='block';
   }
   else {
     document.getElementById('city_area').style.display='none'; 
   }
   var buf = document.calc.formula_nomer.selectedIndex;
   document.calc.reset();
   
   for(var k=0;  k < document.calc.formula_nomer.options.length;  ++k ) {
     if(k==buf)  document.calc.formula_nomer.options[k].selected = true;
   }
}

function init_calc() {
  var form = document.calc;
  for(i=0; i < form.in_city.length; i++) form.in_city.item(i).onclick = function(){city_change();};
}

function hidden_menu() {
   $.each( $('.sublist'), function(i, n){ n.style.width = ( n.parentNode.parentNode.parentNode.clientWidth  / 2 - 60) + "px" ; } );
   //$.each( $('.subsublist'), function(i, n){ n.style.width = n.clientWidth + "px" ; } );
   $(".listitem").bind("click", function(){ $(this).next().slideToggle("slow", function(){ $(this).css('height', '');} ); $(this).toggleClass("listitem"); $(this).toggleClass("listitemop"); });
   $(".sublitm").bind("click", function(){ if( !$(this).next().is(".subsublist")) return 0; $(this).next().slideToggle("slow");});
   $(".subsublist").toggle();
   $(".sublist").toggle();   
}
function hidden_menu2() {
   //$.each( $('.sublist'), function(i, n){ n.style.width = ( n.parentNode.parentNode.parentNode.clientWidth  / 2 - 60) + "px" ; } );
   //$.each( $('.subsublist'), function(i, n){ n.style.width = n.clientWidth + "px" ; } );
   $(".listitem").bind("click", function(){ $(this).next().slideToggle("slow", function(){ $(this).css('height', '');} ); $(this).toggleClass("listitem"); $(this).toggleClass("listitemop"); });
   $(".sublitm").bind("click", function(){ if( !$(this).next().is(".subsublist")) return 0; $(this).next().slideToggle("slow");});
   $(".subsublist").toggle();
   $(".sublist").toggle();   
}