function addtnlItems(){
  var upgrades = document.getElementById("productUpgrades");
  if(upgrades){
    var theForm = document.getElementById("addform");
    addtnlItems = document.createElement('input');
    addtnlItems.name = "upsoldProductIds";
    upgradesChosen = upgrades.getElementsByTagName("input");
    for(var x = 0; x < upgradesChosen.length; x++){
      if(upgradesChosen[x].checked){
        if(addtnlItems.value != ""){
        addtnlItems.value  = addtnlItems.value + "," + upgradesChosen[x].value;
        }else{
          addtnlItems.value  = upgradesChosen[x].value;
        } 
      }
    }
    theForm.appendChild(addtnlItems);  
  }
}
 
function verifyUpsoldIds(){
  var uplsoldProductIds  = document.getElementsByName("upsoldProductIds");
  for(var x = 0; x < uplsoldProductIds.length; x++){
    if(uplsoldProductIds[x].checked){
      if(uplsoldProductIds[x].value == "" ){
        alert(productSummaryCms['product.javascript.addItem.error']);
        return false;
      }
    }    
  }
  return true;
}

function verifyAttributes() {
  var div = document.getElementById('productAttributesDiv');
  if ( !div ) return true;
  var elements = div.getElementsByTagName('TEXTAREA');
  for ( var i = 0; i < elements.length; i++ ) {
    if ( elements[i].value.trim() == '' ) {
      alert(productSummaryCms['product.javascript.addItem.error']);
      return false;
    }
  }
  return true;
}

function addTo( theForm, action, id ) {
  if ( verifyAmountById( id ) ) {
    if ( addToGlobals.purchaseStateIsCheckout ) { 
      disableAddToButtons(theForm);
      location.replace("javascript: " + submitname); // this is to keep people from going back to add more gifts.
    } else {
      theForm.action = action;
      if ( verifyAttributes() ) {
        if ( document.addform ) {
          if ( document.addform.add_product_id.value == '' || document.addform.add_product_id.value == 'NULL' ) {
            alert(productSummaryCms['product.javascript.addItem.error']);
            return;
          }
        }
        if ( typeof validateOnSubmit != 'function' || validateOnSubmit() ) {
          addtnlItems();
          if(verifyUpsoldIds()) {
            disableAddToButtons(theForm);
            theForm.submit();
          }
        }
      }
    }
  }
}
  
function disableAddToButtons(theForm) {
  var formElements = theForm.elements;
  for (i = 0; i < formElements.length; i++) {
    if ( formElements[i].type == 'button' ) {
      formElements[i].disabled = true;
    }
  }
}

function verifyAmountById( id ) {
  amt = document.getElementById(id).value
/*  if ( parseInt( amt ) > 500 ) {
    if ( !window.confirm( productSummaryCms['product.javascript.verifyAmount.1.1.error'] + amt + ' ' + productSummaryCms['product.javascript.verifyAmount.1.2.error'] + '?' ) ) {
      return false;
    }
  }*/
  return true;    
}
