
// attach checkSum() to all input elements "itemQuantity" onkeyup
function initQuota(){
//  msg='carel.length= '+carel.length+'\n';
  for(var i=0; i < carel.length; i++){
//    msg+=i + ' : '
    try{
//      msg+= carel[i] +'\n';
      if(    typeof carel[i]=='object'
          && typeof carel[i].name!='undefined'
          && carel[i].name.indexOf('itemQuantity')==0){
        carel[i].onkeyup=checkSum;
//        msg+= i + ' - ' + typeof(carel[i]) + ' name:' +carel[i].name +'\n';
      }
    }
    catch(e){}
  }
//  alert(msg);
}



function checkSum(me){
  var total=0;
  var totalQty=0;

  if(!cartChanged){
    setRequestUpdate();
  }

  for(var i=0; i < carel.length; i++){
    try{
      if( typeof carel[i].name!='undefined'
          && carel[i].name.indexOf('itemQuantity')==0 ){
  //      print ('add '+carel[i].name+' = '+carel[i].value);
        var pid = carel[i].name.match(/\[([^\]]+)\]/)[1]; 
        sums[pid] = sum = carel[i].value * carel[ 'itemPrice[' + pid + ']' ].value;
        total += sum;
        totalQty += Number(carel[i].value);
        
        document.getElementById('sum_'+pid).innerHTML = monetize(sum);  
      }
    }
    catch(e){}
  }

  totalField.innerHTML = monetize(total);  
  totalQtyField.innerHTML = totalQty;

  if(total > maxTotal){
    totalField.style.textDecoration='blink';
    
    msgBoxText.innerHTML = msg.totalExceeded;
    msgBox.style.display = 'block';
    keepMsgBox=false;

    if(this.name && (1)){
      pid=this.name.match(/\[([^\]]+)\]/)[1];
      if(total-sums[pid] < maxTotal){
        var rest = maxTotal - (total - sums[pid]);
        var itpr = carel[ 'itemPrice[' + pid + ']' ].value
        var qty = Math.floor(rest / itpr);
        var newTotal = rest+itpr*qty;
        
        if( confirm( msg.itemQtyReduced.replace(/~newQty~/,qty) ) ){
          this.value= qty;
          total = checkSum();
        
        }
      }
    }    
  }
        
  if(total > maxTotal){
    return false;
  }
  else{
    totalField.style.textDecoration='none';
    if(!keepMsgBox) msgBox.style.display = 'none';
    return total;
  }
}


function setRequestUpdate(){
  document.cart.requestRefreshCart[1].className+=' hilite';
  
  msgBox.style.display = 'block';
  msgBoxText.innerHTML = msg.requestUpdate;
  cartChanged=true;

  keepMsgBox=true;

  var liba=document.getElementsByTagName('A');
  for(var i=0; i < liba.length; i++){
    try{
      if(liba[i].parentNode.className.indexOf('linkBack') >= 0){
        liba[i].onclick=requestUpdate;
      }
    }
    catch(e){}
  }
}


function requestUpdate(){
  if(cartChanged && confirm(msg.confirmUpdate)){
    document.cart.redirectHeader.value = this.href;
    document.cart.submit();
    return false;
  }
  return true;
}


function monetize(num){
  var C=Math.round((num % 1) * 100);
//  var E=(num-C).toString().reverse().replace(/(.{3})/g,'$1.').reverse();
  var E=Math.round(num- C/100 );
  
  return E+','+ (C ? C : '00');    
}

