$(document).ready(function(){
  //run check for auto deletion of -1 values
  //HERE
  
  var make = $('select.sub_select_fitment_make'),
  year = $('select.sub_select_fitment_year'),
  model = $('select.sub_select_fitment_model');
  
  $('select.sub_select_fitment_year').change(function(){ //triggers loading of make
    var data;
    //disable lower selects (for year, make will be switched to "Loading..." anyway so we ignore it here)
    model.attr('disabled','disabled').find('option:selected').text('Select a Model').val('-1');
    
    if(year.val() != -1){
      year.find('option[value=-1]').remove();
      
      //set data
      data = {
        type: 'year',
        id: year.val(),
        year: year.val()
      }
      
      loadFitSelect(data, make);
    }
  });
  
  $('select.sub_select_fitment_make').change(function(){ //triggers loading of model
    var data;
    //disable lower selects
    model.attr('disabled','disabled').find('option:selected').text('Select a Model').val('-1');
    
    if(make.val() != -1){
      make.find('option[value=-1]').remove();
      
      //set data
      data = {
        type: 'make',
        id: make.val(),
        year: year.val()
      }
      
      loadFitSelect(data, model);
    }
  });
  
  $('select.sub_select_fitment_model').change(function(){ //triggers fitment save
    var data;
    if(model.val() != -1){
      model.find('option[value=-1]').remove();
      
      data = {
        node_id: model.val(),
        year: year.val()
      }
      
      //process fitment selection and save it
      $.post('/fitmentSelect/chooseNode/', data, function(){ //response is un-needed because we are going to redirect to /cart/options
        if(typeof setPage == 'function') {
            setPage();
        }
      }, 'json');
    }
  });
});

//runs process selects
function loadFitSelect(data, nextSelect){
  nextSelect.find('option:selected').html('Loading...').attr('disabled','disabled');
  $.post('/fitmentSelect/processSelect/', data, function(response){ //automagic
    nextSelect.removeAttr('disabled').html($(response.content).html());
  }, 'json');
}
