/*
   This code is used for validating the inputs on the 'subscriptions' page
   to make sure that (a) at least one item has been selected, and (b) the 
   'delivery/rate' options have been chosen for any selected journals. 
   Should work with both individual drop-down lists per item and with a 
   separate table of radio buttons which apply to all selections.
*/

function validateForm(theForm)
{

  // var theForm = document.forms.shopform;

  // check that we have selected a journal to subscribe to
  var itemSelected = false;
  var chosenDelivery = true;
  for (var i = 0; i < theForm.elements.length; i++) {
    if(theForm.elements[i].type == 'checkbox'){
	var s = theForm.elements[i].name
	if (s.indexOf("item_") > -1){
	   if (theForm.elements[i].checked) { 
	      itemSelected = true; 
	      // if a dropdown price option exists, check it is selected...
	      s = s.replace("item_", "op2_");
	      if (theForm(s)) {
                 if (theForm(s).type == 'select-one') {
		    if (theForm(s).selectedIndex == 0) chosenDelivery = false;
		}
	      }
	   }
 	}
    }
  }

  if (!itemSelected) {
     alert("Please choose one of the items");
     return(false);
  }

  if (!chosenDelivery) {
     alert("Please choose a delivery/rate option for all selections");
     return(false);
  }

  if (theForm.deliveryoption) { // have we got a radio button array of options?
    var NewOpt = rValue(theForm.deliveryoption);
    if (NewOpt == null) {
	alert("Please choose one of the delivery/rate options");
	return(false); 
    }
  }

  // copy the selected radio option to each item's 'hidden' price option if it exists
  for (var i = 0; i < theForm.elements.length; i++) {
    if(theForm.elements[i].type == 'hidden'){
	var s = theForm.elements[i].name
	if (s.indexOf("op2_") > -1){
	   theForm.elements[i].value = NewOpt ;
 	}
    }
  }
  return(true);

}


function rValue(rGroup)
{
	// return the selected value from a radio group (or null if none chosen)
	if(rGroup) {
		var c = -1;
		for (var i=0; i<rGroup.length; i++) {
			if(rGroup[i].checked) { c = i; }
		}
		if (c > -1) {
			return(rGroup[c].value);
		} else { return(null); }

	}
}