function init_option_selector(items, target) {
  /*
  /  items => the jquery obj pointing to the dom listing of products
  /  target => contains the order form and the selects
  */
  function get_products() {//loop through the dom items and compose a list of products
    var products = Array();
    items.each(function() {
      var obj = {};
      $(this).children().each(function() {
        var val = $(this).text();
        $.each($(this).attr('class').split(' '), function() {
          obj[this] = val
        });
      });
      products.push(obj);
    });
    return products;
  }
  
  function select_option(index) {
    var selections = Array();
    var possible_products = Array();
    for(var i = 1; i <= index; i++) {//compose a list of the currently selected options
      selections.push(target.find('.product_option'+i).val());
    }
    $.each(products, function() {//filter products that match the selected options
      for(var i in selections) {
        var j = parseInt(i) + 1;
        if (this['option'+j] != selections[i]) return;
      }
      if(this['in_stock'] == 'False'){
        return;
      }
      possible_products.push(this);
    });
    var i = index;
    while(1) {
      i += 1;
      var selector = target.find('.product_option'+i);
      if (!selector.length) break;
      selector.children().each(function() { //remove previous options
        if ($(this).val()) $(this).remove();
      });
      var added_options = {};
      $.each(possible_products, function() {//loop through possible products and add possible options
        var val = this['option'+i];
        if (added_options[val]) return;
        added_options[val] = true;
        selector.append('<option value="'+val+'">'+val+'</option>');
      });
    }
    if (i==index+1) { //person selected the last option
      if (possible_products.length > 1) {
        alert('More then one possible product matched the criteria');
        return;
      }
      var product = possible_products[0];//we have our product, update the form and send the signal
      for(key in product) {
        target.find('form input[name="'+key+'"]').val(product[key]);
      }
      target.trigger('product-selected', [product, (product.in_stock == 'True' || product.in_stock == '1')]);
    }
  }
  
  function init_selectors() {
    var index = 0;
    while(1) {
      index += 1;
      var selector = target.find('.product_option'+index);
      if (!selector.length) break;
      selector.data('index', index); //need to duplicate index
      selector.change( function () {
        select_option($(this).data('index'));
      });
    }
  }

  var products = get_products(items);
  init_selectors();
  select_option(0);
}

