(function($) {
/*======== Настройки =========*/
var max_discount = 10;  // максимальная скидка
var min_discount = 0;   // минимальная скидка
var max_step_discount = 2;  // максимальная скидка на шаге
var min_step_discount = -3;   // минимальная скидка на шаге
var dummy_count = 39;   // колличество цифр-болванок на барабане
var change_time = 1000;  // время «прыганья» цифр
var fall_time = 1000;   // время «падения»

var messages = {        // cообщения, выбирается случайное
  'positive': [         // если текущее значение на которое изменяется скидка положительное
    'Мы вас балуем',
    'Жми еще, удача впереди!',
    'И это еще не предел',
    'Удача преследует вас'
  ],
  'negative': [        // если текущее значение на которое изменяется скидка отрицательное
    'Не отчаивайтесь, все еще впереди',
    'Еще один раз, все получится',
    'Утешительный приз всё равно будет'
  ]
}

/*======== Хранение временных значений =========*/
var clickable = true;
var currentVal = 0;
var colorChange;

Array.prototype.random = function() {
  return this[Math.floor(Math.random()*this.length)];
}

var randomXToY = function(minVal, maxVal) {
  return minVal+(Math.random()*(maxVal-minVal));
}

var changeColor = function() {
  $('.slot-machine .screen .current').toggleClass('negative');  
}

var getDiscountStep = function() {
  if (currentVal + min_step_discount < min_discount) {
    min_cur_step_discount = min_discount - currentVal;
  } else {
    min_cur_step_discount = min_step_discount;
  }
  if (currentVal + max_step_discount > max_discount) {
    max_cur_step_discount = max_discount - currentVal;  
  } else {
    max_cur_step_discount = max_step_discount;
  }
  step = randomXToY(min_cur_step_discount, max_cur_step_discount);
  return step.toFixed(1);
}

var setRandom = function() {
  step = getDiscountStep();
 
  fillItem(step*1);
  
  colorChange = setInterval(changeColor, 100);
  
  $('.slot-machine .handle').addClass('active').frameAnimation({hoverMode: false, reverse:false, imageHeight:395, delay: Math.round((change_time)/25)});
  
  $('.slot-machine .screen .current .f').animate({top: -29*dummy_count}, change_time, 'linear', function() {
    clearInterval(colorChange);
    if (step > 0) {
      $('.slot-machine .screen .current, .slot-machine .screen .sign').removeClass('negative').addClass('positive');
    } else {
      $('.slot-machine .screen .current, .slot-machine .screen .sign').removeClass('positive').addClass('negative');
    }
    $('.slot-machine .screen .current .f').effect('bounce', {distance: 5, times: 3, speed: 50}, 100);
  });
  
  $('.slot-machine .screen .current .w').animate({top: -29*dummy_count}, change_time+change_time*0.4, 'linear', function() {
    $('.slot-machine .screen .current .w').effect('bounce', {distance: 5, times: 3, speed: 50}, 100, function() {
      if (step > 0) {
        $('.slot-machine').addClass('done').find('.description').html(messages.positive.random());
      } else {
        $('.slot-machine').addClass('done').find('.description').html(messages.negative.random());      
      }
      setTimeout(function() {setTotal(step)}, 1000);
    });
  });
}

var setTotal = function(step) {
  $('.slot-machine .handle').frameAnimation({hoverMode: false, delay: Math.round((fall_time)/25)});
  if (step > 0) {
    $('.slot-machine .screen .total .w').animate({top: -1*$('.slot-machine .screen .total .w').height()+29}, fall_time, 'linear');    
    $('.slot-machine .screen .total .f').animate({top: -1*$('.slot-machine .screen .total .f').height()+29}, fall_time, 'linear');    
  } else {
    $('.slot-machine .screen .total').find('.w, .f').animate({top: 0}, fall_time, 'linear');     
  }
  $('.slot-machine .screen .current').animate({color: '#D4D3D3'}, fall_time, 'linear', function() {
    $('.slot-machine .screen .current, .slot-machine .screen .sign').removeAttr('style').removeClass('positive  negative');
  });
  $('.slot-machine .screen .current .w').animate({top: -1*$('.slot-machine .screen .current .w').height()+29}, fall_time, 'linear');
  $('.slot-machine .screen .current .f').animate({top: -1*$('.slot-machine .screen .current .f').height()+29}, fall_time, 'linear', function() {
    $('.slot-machine .handle').removeClass('active');
    var clicks = $('.order #clicks').val();
    clicks++;
    $('.order #clicks').val(clicks);
    $('.order #discount').val(currentVal.toFixed(1));
    clickable = true;
  });
}

var fillItem = function(step) {
  
  $('.slot-machine .screen .current').find('.f, .w').css('top', 0).html('<i>0</i>');
  $('.slot-machine .screen .total').find('.f, .w').html('');      

  count = dummy_count - 1;
  for (i = 0; i < count; i++) {
    $('.slot-machine .screen .current .w').append('<i>'+Math.abs(Math.round(Math.random()*10)-1)+'</i>');
    $('.slot-machine .screen .current .f').append('<i>'+Math.abs(Math.round(Math.random()*10)-1)+'</i>');
  }
  
  part_1 = Math.floor(Math.abs(step));
  part_2 = Math.round((Math.abs(step) - Math.floor(Math.abs(step)))*10);
  
  for (i = part_2; i >= 0; i--) {
    $('.slot-machine .screen .current .f').append('<i>'+i+'</i>');
  }
  
  for (i = part_1; i >= 0; i--) {
    $('.slot-machine .screen .current .w').append('<i>'+i+'</i>');
    if (i != 0) {
      for (j = 9; j >= 0; j--) {
        $('.slot-machine .screen .current .f').append('<i>'+j+'</i>');
      }
    }  
  }

  final = currentVal + step;  
  cur_part_1 = '';
  cur_part_2 = '';
  
  while(currentVal.toFixed(1)*1 != final.toFixed(1)*1) {  
    new_cur_part_1 = Math.floor(Math.abs(currentVal));
    cur_part_2 = Math.round((Math.abs(currentVal) - Math.floor(Math.abs(currentVal)))*10);
    if (cur_part_2 == 10) {
      cur_part_2 = 0;
    }
    if (step > 0) {
      if (new_cur_part_1 !== cur_part_1) {
        cur_part_1 = new_cur_part_1;
        $('.slot-machine .screen .total .w').append('<i>'+cur_part_1+'</i>'); 
      }
      $('.slot-machine .screen .total .f').append('<i>'+cur_part_2+'</i>');
      currentVal += 0.1;    
    } else {
      if (new_cur_part_1 !== cur_part_1) {
        cur_part_1 = new_cur_part_1;      
        $('.slot-machine .screen .total .w').prepend('<i>'+cur_part_1+'</i>');        
      }
      $('.slot-machine .screen .total .f').prepend('<i>'+cur_part_2+'</i>');
      currentVal -= 0.1;  
    }
  }
  
  new_cur_part_1 = Math.floor(Math.abs(currentVal));
  cur_part_2 = Math.round((Math.abs(currentVal) - Math.floor(Math.abs(currentVal)))*10);
  if (cur_part_2 == 10) {
    cur_part_2 = 0;
  }
  if (step > 0) {
    if (new_cur_part_1 !== cur_part_1) {
      cur_part_1 = new_cur_part_1;
      $('.slot-machine .screen .total .w').append('<i>'+cur_part_1+'</i>'); 
    }
    $('.slot-machine .screen .total .f').append('<i>'+cur_part_2+'</i>');
  } else {
    if (new_cur_part_1 !== cur_part_1) {
      cur_part_1 = new_cur_part_1;      
      $('.slot-machine .screen .total .w').prepend('<i>'+cur_part_1+'</i>');        
    }
    $('.slot-machine .screen .total .f').prepend('<i>'+cur_part_2+'</i>');
  }
  
  
  if (step > 0) {
    $('.slot-machine .screen .total').find('.w, .f').css('top', 0);
  } else {
    $('.slot-machine .screen .total .w').css('top', -1*$('.slot-machine .screen .total .w').height()+29);      
    $('.slot-machine .screen .total .f').css('top', -1*$('.slot-machine .screen .total .f').height()+29);    
  }
  
}

jQuery(document).ready(function($) {
  $('.slot-machine .handle').click(function(e) {
    e.preventDefault();
    if (clickable) {
      clickable = false;
      setRandom();
    }
  });
});
})(jQuery);
