// array of boxes
// each 'box' contains [ quantity, price ]
var boxes = [
   [ 24, 18.95 ],
   [ 48, 36.95 ],
   [ 72, 54.95 ],
   [ 120, 90.95 ]
];

// array of invalid selections in the drop down list
var invalid_selections = [ 0, 1, 9, 21, 29, 32 ];

var form = document.HandSelectedChocolates;

function set_all(){
   if( !check_total() )
      return false;

   if( !set_att_names() )
      return false;

   change_form();
   form.price_per_unit_1.value = boxes[ form.productID_1.selectedIndex ][1];
   form.submit();
}

function change_form(){
   form.action = 'https://secure.eznettools.net/cgi-bin/EZCheckout/first';
}

function is_valid_selection( selected ){
   for( var i = 0; i < invalid_selections.length; ++ i )
      if( selected == invalid_selections[i] )
         return false;

   return true;
}

function set_att_names() {
   var type        = [ 'light', 'dark' ];
   var invalid_cnt = 0;

   var j = 1;
   for( var i = 1; i <= 38; ++i ){
      var selected = eval( "form.ChocolateType_" + i + ".selectedIndex" );
      var valid_selection = is_valid_selection( selected );

      var invalid = false // reset for every line
      for( var k = 0; k < type.length; ++k ){
         var qty = parseInt(
            eval( "form.attribute_" + j + "_name_1.value" )
         ) || 0;

         if( qty ){
            if( valid_selection )
               eval( "form.attribute_" + j + "_value_1.value=" +
                     "form.ChocolateType_" + i + "[selected].value " +
                     "+ ' - ' + type[k]" );
            else // only increment the invalid count once per line
               invalid = true
         }

         ++j; // don't forget to increment j
      }

      if( invalid )
         ++invalid_cnt
   }

   if( invalid_cnt ){
      alert( 'You have ' + invalid_cnt + ' quantities filled in without ' +
             'valid selections.' );
      return false;
   }

   return true;
}

function check_total() {
   sync_total(); // sanity check ... make sure it got set

   var total = parseInt( form.total_pieces.value ) || 0;
   var space = parseInt( boxes[ form.productID_1.selectedIndex ][0] ) || 0;
   if( space != total ){
      var msg = 'You have not selected the right amount of chocolate.';
      if( space > total )
         msg += '\nYou have ' + ( space - total ) + ' too few choices.';
      else if( space < total )
         msg += '\nYou have ' + ( total - space ) + ' too many choices.';

      alert( msg );

      return false;
   }

   return true;
}

function sync_total(){
   var total = 0;
   for( i = 1; i <= 76; ++i ){
      total += parseInt(
         eval( "form.attribute_" + i + "_name_1.value" )
      ) || 0; // make sure we have the or 0 ... for NaN
   }

   form.total_pieces.value = total;
}