/* javascript routines for ers09 instrument: compute payout info after final auction round */
// the workingData must contain the results from all rounds (as downloaded from the servers results archive)
//
// the following variables are used by participants (so must be written to the client-accessible parameters files, using postCAP):
// my_rc : chosen round (only used if final_type=0
// my_earnings : earnings (sum, mean, or random round) in ebucks
// my_cashPay : real cash earnings (
// my_totalCash ; my_cashPay (cash from auctions) + my_risk_earnings (cash from risk experiment) + startup_Bonus
//
// risk_earnings[1] and risk_earnings[2] : earnings from 1st and 2nd round of risk experiment
// risk stuff is NOT in results. Use the risk_earnings submittedData variables 
// use submittedData variables (* is 1 or 2, for risk round 1 or 2)
//                      dec_chosen[*] -- 10 char string of 1 and 2 (which option chosen in the 10 choice)
//                      risk_dice1[*]  -- first dice roll. I.e.; 3 means "use third option"
//                      risk_dice2[*]  -- second dice roll. I.e.; 4 (if first dice is 5) means "use high paying result"
//                      risk_earnings[*] -- earnings (give decison and the dice rolls)

function computeFinalResults(istep) {  

if (arguments.length<1) istep=1;
var aid,zvars,i,dd,aRound,aearn,ftype,erate;
var cashPay,dd,rearn1,rearn2,rearn3,rearn4,r45 ;
var tmpo={};
var clientNames=[];
var clientIDs,roundlist;
var rearn1,rearn2,rearn3,rearn4,acash ;
var utype,pBonusV,pBonus ;

controlVars['FUNCTION_CHANGES']=0 ;              // assume no new data (no client has submitted data since last call to this function)

nround=getVarInfo('nowround.g','value');                        // current round

if (istep==2) {                                 // 2nd call: after final auction and after risk round. So sum up risk earnings
  zvars='risk_earn1 risk_earn2 my_risk_earnings my_totalCash ' ;
  zz=retrieveDO('FinalA');

  if (typeof(zz)=='undefined') {                        // the FinalA dataobject must be created first (using a call here with istep ne 2)
      writeDoStatus('Error: you must first use the End Auctions task to compute and save the final round results ');
      return 0;
   }

  acash=zz.my_cashPay ;         /* real earnings from auction rounds (as saved in FinalA) */
  var clientIDs=zz.ID ;  
  for (var i=0;i<clientIDs.length;i++) {
     aid=strip(clientIDs[i]);
     if (aid=='*') continue ;                   // don't process the default id

     utype=readUserVar(aid,'myType',0);
     pBonus=getVarInfo('p_bonus.g','value');   
     dd=extractClientData('S',aid,'$ID',0,nround) ;

     if (dd.length==0)     continue ;                   // since this may be called many times within a round, ignore if no entry for this id
     dd=extractClientData('S',aid,'RISK_EARNINGS[1]',0,nround);   rearn1=fix2(dd[0],0);
     dd=extractClientData('S',aid,'RISK_EARNINGS[2]',0,nround);   rearn2=fix2(dd[0],0);

     rearn3=fix2(mtxMath2(rearn1,rearn2,'$0 + $1 ')) ;
     rearn4=fix2(acash[i],0)  ;  
     r45=fix2(parseFloat(rearn3)+parseFloat(rearn4)+parseFloat(pBonus),-1);
     if (rearn3 > 0) {
        goob=zz.updateDOrecord(aid,[rearn1,rearn2,rearn3,r45],zvars);
        if (goob!=1) {alert('Error in computeFinalResult='+goob) ; return 0 ; }
    }
   }

   goob=zz.displayDO('*',0,1)
   writeDoStatus('Earnings for all participants<p>'+goob);
 
   goob=zz.displayDO(0,'*',1);
   writeDoStatus('Summary stats (non-client specific) <p>'+goob);
   saveDOResultsVar(zz,'ID',zvars,'xx',1);
   zz.saveDO('FinalA');
   return 1 ;
}

// else, first call (compute final round stuff, and setup FinalA dataObject )

//saveResultsVar()        ;               // clear resultsvar

var clientIDs=extractClientList('W');  
var roundlist=extractRoundList('W');

for (var i=0;i<clientIDs.length;i++) {
   aid=clientIDs[i];
   if (typeof(currentParticipants[aid])!='undefined') clientNames[i]=currentParticipants[aid].NAME;
}

ftype=strip(getVarInfo('final_type.g','value'));                // FINAL_TYPE: Type of final payment (0=single round, 1=sum, 2=average)  
erate=strip(getVarInfo('edollar_rate.g','value'));              // ebuck to real $ conversion

var zz=createDO(clientIDs);

zz.addDO(clientIDs,'ID');
zz.addDO(clientNames,'NAME');          

zvars='my_Rc my_earnings my_cashPay risk_earn1 risk_earn2 my_risk_earnings my_totalCash ' ;
zz.addDO(0,zvars);

goo=extractRoundList('w') ;      
var dd=extractClientData('W','*','$ROUND ISDEMO ','',goo);   // get rid of the  * round (so it lines up with client-specific extracts)
var nondemos=selectRows(dd,'$1 eq 0 and " $0 " ne " * " ','',2);      

for (var i=0;i<clientIDs.length;i++) {
  aid=strip(clientIDs[i]);
  if (aid=='*') continue ;
  dd=extractClientData('W',aid,'$ROUND ROUNDEARN ',0);   
  aRound=0;
  switch (ftype) {
      case '0':
        aii=choseRandomArray(1,nondemos);            // chose random row
        aearn=dd[aii[0]][1] ;                  // aii is a 1 row array pointing whose value is the row of dd to use, element [1] in this row is the earnings
        aRound=aii[0] ;
        break ;
      case '1':   
        tmp=extractRows(dd,nondemos);
        aearn=sumArray(extractCol(tmp,1)) ;     
        break ;
       case '2':  
        tmp=extractRows(dd,nondemos);
        aearn=meanArray(extractCol(tmp,1)) ;     
        break ;
  }                                  // switch

  aearn=fix2(aearn);
  cashPay=fix2(erate*aearn);

  goob=zz.updateDOrecord(aid,[aRound,aearn,cashPay,'','','','',cashPay],zvars);

}

zz.addDOc(sumArray(zz.my_earnings),'totalEarn');
zz.addDOc(sumArray(zz.my_cashPay),'totalCashPay');

goob=zz.displayDO('*',0,1)
writeDoStatus('Earnings for all participants<p>'+goob);

goob=zz.displayDO(0,'*',1)
writeDoStatus('Summary stats (non-client specific) <p>'+goob);

saveDOResultsVar(zz,'ID',zvars,'xx',1);

zz.saveDO('FinalA');

return 'done' ;
}







