/*
--------------------------------------------------------------------------------
7NoTrumps

Main JavaScript validation for contribute screen

---------------------------------------------------------------------------------
   Version        Date         Name          Desc
      1.0          09/08/2001   AEK          First version
      1.04         21/08/2001   AEK          Introduce validation of lead & contract
---------------------------------------------------------------------------------
*/
//function===========================================================

function ChangeDealer(form)
{
  var tempvalue = '';
  var idx = form.Dealer.selectedIndex;
  var hyphens = '--'
  var HowManyBiddingCells = 40;  
 // alert('idx ' + idx );

  for(var k = 1; k < 4; k++) {
     if (idx +1 > k) {
        PopulateMe(eval("form.B" + k ), hyphens);
     }
     else {
        PopulateMe(eval("form.B" + k), "");
     }
   }
   
   for(var i = idx +1; i < (HowManyBiddingCells +1); i++) {
      PopulateMe(eval("form.B"+i), "");
   }
 return true;
}

function validate(form)
{
  var blnOK = true;
  //blnOK = validatecards(form);
  //blnOK = validatecards(form) && validatebidding(form);
  //blnOK = validatebidding(form);
 if (validatecards(form)) {
    blnOK = validatebidding(form);
    if (blnOK) {
    	blnOK = validateRest(form);
    }	
 }
 else {
    blnOK = validatebidding(form);
    blnOK = false;
 }   
 return blnOK;
}

function validateRest(form)
{
 var blnOK = true;
 var temp = '';
 var LeadValue = '';
 var ContractValue = '';
 var suits = 'CDHSN';
 var allLeads = '';
 var allpossiblebids = '';
 var all_cards = 'AKQJT98765432';
 
 temp = form.Contract.value.toUpperCase();
 PopulateMe(form.Contract, temp);
 temp = form.Lead.value.toUpperCase();
 PopulateMe(form.Lead, temp);

//================================================================================
//create a string & array with all the possible bids 
//(exclude pass, double, redouble) from 1C -> 7N
//================================================================================
  for(var i = 1; i < 8; i++) {
     for(var j = 0; j < 5; j++) {
        allpossiblebids = allpossiblebids + i + suits.charAt(j) + ',';
        if (suits.charAt(j) == 'N') {
           allpossiblebids = allpossiblebids + i + 'NT,';  
        }   	            
     }
  }
 //alert('allpossiblebids = ' + allpossiblebids);
 ContractValue = form.Contract.value;
  if (ContractValue == '') {
     alert('Please enter the contract.');
     blnOK = false;
  }
  else {     	
     if (allpossiblebids.indexOf(ContractValue +',') == -1) {
        alert('The contract ' + ContractValue + ' is not valid');
        blnOK = false;
     }   
  } 
//========================================================================
//This part of the code checks the lead against ",1C,1D,1H,1N,2C ... " etc
//========================================================================
  for(var intCount = 0; intCount < 13; intCount++) {
     for(var n = 0; n < 4; n++) {
        allLeads = allLeads + suits.charAt(n) + all_cards.charAt(intCount) + ',';
        allLeads = allLeads + all_cards.charAt(intCount) + suits.charAt(n) + ',';
        if (all_cards.charAt(intCount) == 'T') {
           allLeads = allLeads + suits.charAt(n) + '10,';  
           allLeads = allLeads + '10' + suits.charAt(n) + ',';
        }   	    
     }
  }
 //alert('allLeads = ' + allLeads);
 
  LeadValue = form.Lead.value;
  if (LeadValue == '') {
     alert('Please enter the lead.');
     blnOK = false;
  }
  else {     	
     if (allLeads.indexOf(LeadValue +',') == -1) {
        alert('The lead ' + LeadValue + ' is not valid');
        blnOK = false;
     }   
  } 

if (form.reader_name.value == '') {
    alert('Please enter your name');
    blnOK = false;
}   	

if (form.country.value == '') {
    alert('Please enter the country where you live');
    blnOK = false;
}   	

if (form.WhatHappened.value == '') {
    alert('Please enter the full text about your submitted deal.');
    blnOK = false;
}   	

 return blnOK; 
}

function showhelp()
{
 var blnOK = true;
 var help_win;
 
 help_win=window.open("ContributeHelp.html",'popup','width=375,height=285,,screenx=20,screeny=18,status=no,toolbar=no,scrollbars=yes,resizable=no,menubar=no');
 
}

function validatebidding(form)
{
 var allpossiblebids = '';
 var RemainingPossibleBids = ''; 
 var allpossiblebidsSaved = '';
 var allPossBidsArray = new Array();
 var allbids = new String(""); //= '';
 var userProcessedBids = new Array();
 var userOrigBids = new Array();
 var userBidsTotal = 0;
 var allbidsSaved = '';
 var NBDBRD = ',NB,DB,RD'; //no bid, double, redouble
 var blnOK = true;
 var suits = 'CDHSN';
 var stringTest = new String("CDHSN");
 var regexNo = /No/ig;
 var regexNB = /NB/ig;
 var regexNT = /NT/ig;
 var regexPass = /Pass/ig;
 var regexP = /P/ig;
 var regexD = /D/ig;
 var regexDb = /Db/ig;
 var regexDbl = /Dbl/ig;
 var regexDble = /Dble/ig;
 var regexX = /X/ig;
 var regexXX = /XX/ig;
 var regexR = /R/ig;
 var regexRDble = /RDble/ig;
 var regexRDbl = /RDbl/ig;
 var regexRDb = /RDb/ig;
 var regexRD = /RD/ig;
 var regexXX = /XX/ig;
 var regexBB = /BB/ig;
 var regexRR = /RR/ig; 
 var regexNB = /NB/ig; 
 //to here!! need to change plain N to No (regex probs),
 //also need to check the messages with DB and RD
 var bidscount = 0;
 var bid = '';
 var n = 0;
 var restofbids = '';
 var HowManyBiddingCells = 40;
 var posn1 = 0;
 var posn2 = 0;
 var len = 0;
 var currentpos = 0;
 var totalprevbids = new String("");
 var temp = '';
 var tempstr = new String("");
 var nextcellvalue = '';
 var auctionbegun = false;
 var check = false;
 var prevbid = '';
 var Bid2prev = '';
 var Bid3prev = '';
 var errors = new Array();
 var errnum = 0;  
 var allerrors = '';
 var stillleadinghyphens = true;
 var totalleadinghyphens = 0;
 var PrevHighestBidPosn = 0; //position in the array

/*
form.B1.value = '1C';   
form.B2.value = '1H';   
form.B3.value = 'Dble'; 
form.B4.value = 'Pass'; 
form.B5.value = 'NB';   
form.B6.value = '2C';   
form.B7.value =  '2NT'; 
form.B8.value =  '4H';  
form.B9.value = '4N';
form.B10.value = '5C';
form.B11.value = 'dble';
form.B12.value = 'rdbl';
form.B13.value = 'Pass';
form.B14.value = '5S';
form.B15.value = 'Pass';
form.B16.value = '7NT';
form.B17.value = 'Pass';
form.B18.value = 'Pass';
form.B19.value = 'Pass';


form.B1.value = '1C';
form.B2.value = 'RDbl';
form.B3.value = 'Dble';
form.B4.value = 'Pass';
form.B5.value = 'Dble';
form.B6.value = '3N+';
form.B7.value = '4&C';
form.B8.value = 'Pass';
form.B9.value = 'Dble';
form.B10.value = '2NT';
form.B11.value = 'RD';
form.B12.value = 'Pass';
*/

//================================================================================
//Firstly, populate any "leading" empty cells with "--"
//================================================================================

   for(var i = 1; i < (HowManyBiddingCells +1); i++) {
       temp = eval("form.B"+i+ ".value");
       if ( temp == '') {
          PopulateMe(eval("form.B"+i), '--');
       }
       else {
          break; //exit loop
       }
   }


//================================================================================
//create a string & array with all the possible bids 
//(exclude pass, double, redouble) from 1C -> 7N
//================================================================================
  for(var i = 1; i < 8; i++) {
     for(var j = 0; j < 5; j++) {
        allpossiblebids = allpossiblebids +',' + i + suits.charAt(j);
        allPossBidsArray[(5*(i-1))+(j+1)] = i + suits.charAt(j);
        //alert('allPossBidsArray(' + ((5*(i-1))+(j+1)) +') ' + allPossBidsArray[(5*(i-1))+(j+1)]);
        
     }
  }
  
//alert('Hello2'); 
//================================================================================
//create a string of ALL the user entered bids, but take out the crap first
//and uppercase it.
//================================================================================

  for(var i = 1; i < (HowManyBiddingCells + 1); i++) {
     temp = extractcrap(eval("form.B"+i+ ".value.toUpperCase()"));
     PopulateMe(eval("form.B"+i), temp);
  }  

//================================================================================
//If there are other empty cells, shunt them up - they won't do it again
//================================================================================

   for(var i = 1; i < (HowManyBiddingCells +1); i++) {
       temp = eval("form.B"+i+ ".value");
       if (temp == '') {
          n = i + 1
          while (n <= HowManyBiddingCells) {
             nextcellvalue = eval("form.B"+n+ ".value");
             if (nextcellvalue != '') {
                PopulateMe(eval("form.B"+i), nextcellvalue); //bung in the next cell
                PopulateMe(eval("form.B"+n), '');            //clear it down
                break; //exit loop
             }
             n++
          }
       }
   } 


//================================================================================
//populate array, and a string of ALL the user entered bids
//================================================================================

  stillleadinghyphens = true;
  totalleadinghyphens = 0;

  for(var i = 1; i < (HowManyBiddingCells + 1); i++) {
     temp = eval("form.B"+i+ ".value");
     if (temp == '') {
        break;
     }   
     if (temp == "--") {
        if (stillleadinghyphens) {
            totalleadinghyphens++;
        }
     }   
     else {   
        userProcessedBids[i - totalleadinghyphens] = temp;
        userOrigBids[i - totalleadinghyphens] = temp;     
        stillleadinghyphens = false;
        allbids = allbids + ',' + temp;
        userBidsTotal++;
     }      
 
  }

//remove trailing commas  
while (get_right_char(allbids) == ',') {
    totallength = allbids.length;
    allbids = allbids.substring(0,totallength-1);
 }
 

for(var i = 1; i < userBidsTotal + 1; i++) {
   if (userProcessedBids[i] == 'N') {
      userProcessedBids[i] = 'No';
   }
   if (userProcessedBids[i] == 'n') {
      userProcessedBids[i] = 'No';
   }   
   if (userProcessedBids[i] == 'D') {
      userProcessedBids[i] = 'DB';
   }
   if (userProcessedBids[i] == 'd') {
      userProcessedBids[i] = 'DB';
   }   
   if (userProcessedBids[i] == 'R') {
      userProcessedBids[i] = 'RD';
   }
   if (userProcessedBids[i] == 'r') {
      userProcessedBids[i] = 'RD';
   }         
   userProcessedBids[i] = userProcessedBids[i].replace(regexPass,"NB"); //Pass->NB                               
   userProcessedBids[i] = userProcessedBids[i].replace(regexP,"NB"); //P->NB                                     
   userProcessedBids[i] = userProcessedBids[i].replace(regexNo,"NB"); //No->NB                                   
   userProcessedBids[i] = userProcessedBids[i].replace(regexNB,"P"); //NB->P //temporarily before N->NT          
   userProcessedBids[i] = userProcessedBids[i].replace(regexNT,"N"); //NT->N                                     
   userProcessedBids[i] = userProcessedBids[i].replace(regexP,"NB"); //P->NB // so now N, NT & NB don't conflict 
/*
   userProcessedBids[i] = userProcessedBids[i].replace(regexRDbl,"R"); //RDbl->RR                                
   userProcessedBids[i] = userProcessedBids[i].replace(regexRDb,"R"); //RDb->RR                                  
   userProcessedBids[i] = userProcessedBids[i].replace(regexRD,"R"); //RD->RR                                    
   userProcessedBids[i] = userProcessedBids[i].replace(regexR,"RR"); //R->RR                                     
   userProcessedBids[i] = userProcessedBids[i].replace(regexXX,"RR"); //Redouble->RR                             
   userProcessedBids[i] = userProcessedBids[i].replace(regexDble,"BB"); //Dble->BB                               
   userProcessedBids[i] = userProcessedBids[i].replace(regexDbl,"BB"); //Dbl->BB                                 
   userProcessedBids[i] = userProcessedBids[i].replace(regexDb,"BB"); //Db->BB                                   
   userProcessedBids[i] = userProcessedBids[i].replace(regexX,"BB"); //Dble->BB  
*/   
   userProcessedBids[i] = userProcessedBids[i].replace(regexRDbl,"R"); //RDbl->R                                
   userProcessedBids[i] = userProcessedBids[i].replace(regexRDb,"R"); //RDb->R                                  
   userProcessedBids[i] = userProcessedBids[i].replace(regexRD,"R"); //RD->R                                    
   userProcessedBids[i] = userProcessedBids[i].replace(regexR,"RD"); //R->RD                                     
   userProcessedBids[i] = userProcessedBids[i].replace(regexXX,"RD"); //Redouble->RD                             
   userProcessedBids[i] = userProcessedBids[i].replace(regexDble,"DB"); //Dble->DB                               
   userProcessedBids[i] = userProcessedBids[i].replace(regexDbl,"DB"); //Dbl->DB                                 
   userProcessedBids[i] = userProcessedBids[i].replace(regexX,"DB"); //Dble->DB  
 }

      
allbids = allbids.replace(regexPass,"NB"); //Pass->NB
allbids = allbids.replace(regexP,"NB"); //P->NB
allbids = allbids.replace(regexNo,"NB"); //No->NB
allbids = allbids.replace(regexNB,"P"); //NB->P //temporarily before N->NT

allbids = allbids.replace(regexNT,"N"); //NT->N
//allbids = allbids.replace(regexN,"NT"); //N->NT

allbids = allbids.replace(regexP,"NB"); //P->NB // so now N, NT & NB don't conflict
/*
allbids = allbids.replace(regexRDbl,"R"); //RDbl->RR
allbids = allbids.replace(regexRDb,"R"); //RDb->RR
allbids = allbids.replace(regexRD,"R"); //RD->RR
allbids = allbids.replace(regexR,"RR"); //R->RR
allbids = allbids.replace(regexXX,"RR"); //Redouble->RR

allbids = allbids.replace(regexDble,"BB"); //Dble->BB
allbids = allbids.replace(regexDbl,"BB"); //Dbl->BB
allbids = allbids.replace(regexDb,"BB"); //Db->BB
allbids = allbids.replace(regexX,"BB"); //Dble->BB
*/
allbids = allbids.replace(regexRDbl,"R"); //RDbl->R
allbids = allbids.replace(regexRDb,"R"); //RDb->R
allbids = allbids.replace(regexRD,"R"); //RD->R
allbids = allbids.replace(regexR,"RD"); //R->RD
allbids = allbids.replace(regexXX,"RD"); //Redouble->RD

allbids = allbids.replace(regexDble,"DB"); //Dble->DB
allbids = allbids.replace(regexDbl,"DB"); //Dbl->DB
allbids = allbids.replace(regexX,"DB"); //Dble->DB

  allbidsSaved = allbids;
  restofbids = allbids;
  bidscount =  CountOccurrences(allbids,",");
 

//Check2CharsLong goes here

//========================================================================
//This part of the code checks each bid against ",1C,1D,1H,1N,2C ... " etc
//========================================================================
// alert('here7 = ');  
 
  for(var intCount = 1; intCount < userBidsTotal; intCount++) {
     bid = userProcessedBids[intCount];
     //alert('bid = >' + bid + '<');
     for(var n = 1 ; n < 36; n++) {
     	if (bid.length > 1) {
           if (allpossiblebids.indexOf(bid) != -1) {
              //OK
           }
           else {
              if (NBDBRD.indexOf(bid) == -1) {
                 //alert('Bid ' + bid  + ' not valid');
                 errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 11);
                 errnum++;              
                 blnOK = false;
                break; //out of inner loop
              }  
           }   
        }   
        else {
           if (bid.length == 1) {
              errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 11);
              errnum++;              
              blnOK = false;
              break; //out of inner loop
           }
        }      
     }
  }
 
 
//===============================================================
//This part of the code checks if any bid has been used twice
//===============================================================
  allbidsSaved = allbids;
  restofbids = allbids;
  
  //alert('bidscount ' + bidscount + '\n allbids =' + allbids);
  //alert('userBidsTotal = ' + userBidsTotal); 
  for(var intCount = 1; intCount < userBidsTotal + 1; intCount++) {

     //alert('restofbids ' + restofbids);
     bid = userProcessedBids[intCount];
    // alert('bid = ' + bid);
     for(var n = 1 ; n < intCount + 1; n++) {
    // for(var n = (intCount+1) ; n < userBidsTotal + 1; n++) {     
        if ((userProcessedBids[n] == bid) && (NBDBRD.indexOf(bid) == -1) 
         && (allpossiblebids.indexOf(bid) != -1)
         && (n != intCount) ) {
           errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 13);
           errnum++;             
           blnOK = false;
           break;
        }   
     }
  }

//================================================================================
//This part of the code ensures all bids are higher than the previous highest bid
//================================================================================
 
  restofbids = allbids;
  allpossiblebidsSaved = allpossiblebids;
  RemainingPossibleBids = allpossiblebids;

  for(var intCount = 1; intCount < userBidsTotal + 1; intCount++) {
     bid = userProcessedBids[intCount]; 
     PrevBid = userProcessedBids[intCount -1];
     posn1 = GetPos(bid, allPossBidsArray, 1); 
     posn2 = GetPos(PrevBid, allPossBidsArray, posn2);
     //alert('bid =' + bid + '\nPrevBid = ' + PrevBid +'\nposn1 =' + posn1 + '\nposn2 = ' + posn2 
     //       + '\nPrevHighestBidPosn = ' + PrevHighestBidPosn + '\nintCount = ' +intCount);     
     if (posn1 > 0) {  //bid is a valid one

        if (posn1 > PrevHighestBidPosn) { //it's OK - it is higher
             //alert('HIGHER! \nPrevHighestBidPosn1 = ' + PrevHighestBidPosn);
           PrevHighestBidPosn = posn1;

        }
        else {
           //alert('bid =' + bid + '\nintCount = ' + intCount);
     //      alert('\nPrevHighestBidPosn2 = ' + PrevHighestBidPosn);
     //alert('XXXXXXXX bid =' + bid + '\nPrevBid = ' + PrevBid +'\nposn1 =' + posn1 + '\nposn2 = ' + posn2 
     //       + '\nPrevHighestBidPosn = ' + PrevHighestBidPosn + '\nintCount = ' +intCount);           
           errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 4);
           errnum++;
           blnOK = false;
        }
     }

  }
  allpossiblebids = allpossiblebidsSaved; //restore the value - need again
 
//================================================================================
//Now check that if there are four consecutive passes, they come at the beginning
//If there are three consecutive passes, they must occur at the beginning or end
//================================================================================

  //alert('allbids (Check Passes) ' + allbids );
  restofbids = allbids;
//take out leading --
  while (restofbids.substr(0,3) == '--') {
     restofbids = restofbids.substr(3);
  }
  //alert('restofbids X ' + restofbids );
  posn1 = restofbids.indexOf(',NB,NB,NB,NB');
  if (posn1 != -1) {
     //alert('posn1 ' + posn1);
      if (posn1 != 0) {
         errors[errnum] = BadBid(0, '', 1); 
         errnum++;      
        // alert('Four consecutive passes can only occur at the beginning of the auction');
         blnOK = false;
      }
      else {
         if (restofbids != ',NB,NB,NB,NB') {
             errors[errnum] = BadBid(0, '', 2); 
             errnum++;      
            // alert('Four consecutive passes, if present, must be the only bids of the auction');
             blnOK = false;
          }
      }
  }
  else {
     if (restofbids == '') { 	
        errors[errnum] = BadBid(0, '', 14); 
        errnum++;      
        blnOK = false;     	
     }
     else {
        posn1 = restofbids.indexOf(',NB,NB,NB');
        if (posn1 == -1) {  //not found
           errors[errnum] = BadBid(0, '', 3); 
           errnum++;      
           //alert('Three consecutive passes must be present to complete the auction' + restofbids);
           blnOK = false;
        }
        else {
           if (posn1 != 0) {
               if (restofbids.substr(posn1) != ',NB,NB,NB') {
                  errors[errnum] = BadBid(0, '', 10); 
                  errnum++;
                  //alert('Three consecutive passes can only occur at the beginning or end of the auction');
                  blnOK = false;
               }
           }    
           else {
               restofbids = restofbids.substr(9);
               if (restofbids.indexOf(',NB,NB,NB') == -1) {
                  errors[errnum] = BadBid(0, '', 3); 
                  errnum++;
                  //alert('Three consecutive passes are required to complete the auction'  + restofbids);
                  blnOK = false;
               }            
           }
        }
     }   
  }

//alert('You have checked Passes');
 
//================================================================================
//This part of the code ensures all doubles are valid
//================================================================================

  restofbids = allbidsSaved;
  bid = ''; //initialise for comparison purposes
   //prevbid = '';
  auctionbegun = false;
  //alert('auctionbegun = ' + auctionbegun + ' bidscount = ' + bidscount);

  for(var intCount = 1; intCount < userBidsTotal + 1; intCount++) {
     prevbid = bid;
     //alert('Double ' + intCount);
     bid = userProcessedBids[intCount]; 
     posn1 = GetPos(bid, allPossBidsArray, 1); 
    //alert('bid = ' + bid + '\nposn1 = ' + posn1);
     if (posn1 > 0) {  //bid is a valid one
        auctionbegun = true; 
     }
     if (bid == 'DB') {
        if (auctionbegun == false) {
          // alert('Double1 ' + intCount + ' ' + bid);
           errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 5);
           errnum++; 
     
        }  
        else {
           if (prevbid == 'NB') { //OK, but previous two bids must be Pass and a valid bid
              Bid2prev = userProcessedBids[intCount - 2];
              if (Bid2prev != 'NB') { //bad!
                 //alert('Double2');
                 errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 12);
                 errnum++;
              }
              else {  
                 Bid3prev = userProcessedBids[intCount - 3]; 
                 posn2 = GetPos(Bid3prev, allPossBidsArray, 1);                 
                 if (posn2 == 0) {
                    // alert('Double3');
                     errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 7);
                     errnum++;  
                 }
              }                                
           }
           else {
              if (GetPos(prevbid, allPossBidsArray, 1) == 0) { //not in 1C,1D etc
                 //alert('Double4 prevbid =>' + prevbid + '< bid = >' + bid + '<' );
                  errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 6);
                  errnum++;
              }
           }   
        }
     }           
  }
  
//alert('endofdoubles');
  allpossiblebids = allpossiblebidsSaved; //restore the value - need again xxx

//================================================================================
//This part of the code ensures all redoubles are valid
//================================================================================

  restofbids = allbidsSaved;
  bid = ''; //initialise for comparison purposes
   //prevbid = '';
  auctionbegun = false;
  //alert('auctionbegun = ' + auctionbegun + ' bidscount = ' + bidscount);

  for(var intCount = 1; intCount < userBidsTotal + 1; intCount++) {
     prevbid = bid;
     //alert('Double ' + intCount);
     bid = userProcessedBids[intCount]; 
     posn1 = GetPos(bid, allPossBidsArray, 1); 
     //alert('bid = ' + bid + '\nposn1 = ' + posn1);
     if (posn1 > 0) {  //bid is a valid one
        auctionbegun = true; 
     }
     if (bid == 'RD') {
        if (auctionbegun == false) {
          // alert('Double1 ' + intCount + ' ' + bid);
           errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 5);
           errnum++; 
        }  
        else {
           if (prevbid == 'NB') { //OK, but previous two bids must be Pass and a double
              Bid2prev = userProcessedBids[intCount - 2];
              if (Bid2prev != 'NB') { //bad!
                 //alert('Double2');
                 errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 8);
                 errnum++;
              }
              else {  
                 Bid3prev = userProcessedBids[intCount - 3]; 
                 if (Bid3prev != 'DB') {
                    // alert('Double3');
                     errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 9);
                     errnum++;  
                 }
              }                                
           }
           else {
              if (prevbid != 'DB') { 
                 //alert('ReDouble4 prevbid = ' + prevbid);
                  errors[errnum] = BadBid(intCount + totalleadinghyphens, bid, 8);
                  errnum++;
              }
           }   
        }
     }           
  }
  
//alert('end of redoubles');
 
//===============================================================
//Finally, any error messages are displayed
//===============================================================
if (errnum > 0 ) {
   errors[errnum] = '\nPlease check again and press Submit';
   errnum++
   for(var i = 0; i < errnum; i++) {
       if (i > 20) {
       	  allerrors = allerrors + '\n\n' + 'More errors were found .....';
          break;
       }   	  
       allerrors = allerrors + '\n'+ errors[i];
   }
   alert('The following bidding errors were found in your deal:\n' + allerrors );
   blnOK = false;
}
else {
   for(var i = 1 ; i < (userBidsTotal + 1); i++) {
       temp = eval("form.B"+ i + ".value");
       if (temp != '') {
         //alert('userProcessedBids[i] ' + i + '   ' + userProcessedBids[i]);
          temp = userProcessedBids[i]; //Pass->NB                               
          //alert('temp' + temp);       
          PopulateMe(eval("form.B" + (i + totalleadinghyphens)), temp); 
         
       }
       else {
          break;
       }   
   }    
}

 return blnOK;
}

function validatecards(form)
{
  var blnOK = true;
  var totallen = 0;
  var regexT = /10/ig;
  var regex10 = /T/ig;
  var regexB = /\s/ig;
  var strLen = 0;
  var new_text = form.NS.value.replace(regexT,'T');
  var all_cards = 'AKQJT98765432';
  var ditto = 'AKQJT98765432';
  var sortedS = '';
  var sortedH = '';
  var sortedD = '';
  var sortedC = '';
  var allS = '';
  var allH = '';
  var allD = '';
  var allC = '';
  var players = 'NESW';
  var suits = 'SHDC';
  var i = 0;
  var j = 0;
  var k = 0;
  var totallength = 0;
  var templength = 0;
  var tempS = '';
  var tempH = '';
  var tempD = '';
  var tempC = '';
  var tempvalue = '';
  var tenvalue = '';
  var char1 = '';
  var errors = new Array();
  var NtotalCards = 0 ;
  var EtotalCards = 0 ;
  var StotalCards = 0 ;
  var WtotalCards = 0 ;      
  var errnum = 0;
  var allerrors = '';
  var posn1 = 0;
  var posn2 = 0;
/*
form.NS.value = 'aKqK* 7J 9 A';
form.NH.value = 'J160! 65k';
form.ND.value = 'A2 [1 0 +3';
form.NC.value = '$//(^^';
form.ES.value = '[1 0 8+3';
form.EH.value = '47 [Q 8+';
form.ED.value = 'j [1) 0 +68';
form.EC.value = 'A4';
form.SS.value = 'Q5642 [ +';
form.SH.value = 'A [££ +3';
form.SD.value = ' [975+';
form.SC.value = '**K&';
form.WS.value = '$0$1$';
form.WH.value = '29 [ +';
form.WD.value = '4';
form.WC.value = '2356798T0QJ1';



form.NS.value = 'KQJ';
form.NH.value = 'Q6';
form.ND.value = '86';
form.NC.value = 'K87653';
form.ES.value = 'A5432';
form.EH.value = 'J';
form.ED.value = 'A954';
form.EC.value = 'Q92';
form.SS.value = '9876';
form.SH.value = '43';
form.SD.value = 'JT732';
form.SC.value = 'AJ';
form.WS.value = '10';
form.WH.value = 'AK1098752';
form.WD.value = 'KQ';
form.WC.value = '104';
*/
//Upper case everything
//alert('lower case CRAP LOADED');
   for(var i = 0; i < 4; i++) {
      for(var j = 0; j < 4; j++) {
         tempvalue = eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value");
         PopulateMe(eval("form."+ players.charAt(i)+suits.charAt(j)), tempvalue.toUpperCase());
      }
  }


//alert('upper case CRAP LOADED');
//get rid of spaces and any other crap
   for(var i = 0; i < 4; i++) {
      for(var j = 0; j < 4; j++) {
         tempvalue = '';
         for(var k = 0; k < eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.length"); k++) {
            if (junk(eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.charAt(k)"))) {
               //alert("Space found");
            }
            else {
               tempvalue = tempvalue + eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.charAt(k)");
            }
         }
         //alert('tempvalue = ' + tempvalue);
         PopulateMe(eval("form."+ players.charAt(i)+suits.charAt(j)), tempvalue);
      }
  }
//alert('CRAP CLEARED');

//now convert any 10 to a T - temporarily
   for(var i = 0; i < 4; i++) {
      for(var j = 0; j < 4; j++) {
        tempvalue = eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.replace(regexT,'T')")
         //alert('tempvalue = ' + tempvalue + " i="+i+ " j="+j);
         PopulateMe(eval("form."+ players.charAt(i)+suits.charAt(j)), tempvalue);
      }
   }
//alert('all 10 changed to T temporarily');

//now remove any orphan 1 or 0.
   for(var i = 0; i < 4; i++) {
      for(var j = 0; j < 4; j++) {
         tempvalue = '';
         for(var k = 0; k < eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.length"); k++) {
            char1 = eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.charAt(k)");
            if (char1 != '1' && char1 != '0') {
                   tempvalue = tempvalue + eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.charAt(k)");
            }

         }
         //alert('tempvalue = ' + tempvalue);
         PopulateMe(eval("form."+ players.charAt(i)+suits.charAt(j)), tempvalue);
      }
   }
//alert('all orphan 1 & 0 REMOVED');

//ensure that they are sorted correctly
 for(var i = 0; i < 4; i++) {
    for(var j = 0; j < 4; j++) {
       SortUserInput(eval("form."+ players.charAt(i)+suits.charAt(j)));
    }
 }
//alert('CRAP SORTED');

 totallength = totallength - 0;
 templength = templength - 0;
//check the total length of all the text boxes - need to be 52!
   for(var i = 0; i < 4; i++) {
      for(var j = 0; j < 4; j++) {
         templength = eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.length");
         totallength = totallength + templength;
         if (i == 0) {
            NtotalCards = NtotalCards + templength;
         }   
         else {  
            if (i == 1) {
               EtotalCards = EtotalCards + templength;
            }  
            else {  
               if (i == 2) {
                  StotalCards = StotalCards + templength;
               }   
               else {  
                  if (i == 3) {
                     WtotalCards = WtotalCards + templength;
                  }  
               }                           
            }  
         }         
      }   
   }
   
//===============================================================
//This code checks if any player has fewer or more than 13 cards
//===============================================================
   
//alert(' North length is ' + NtotalCards + '\n East length is ' + EtotalCards +'\n South length is ' + StotalCards + '\n West length is ' + WtotalCards);   
if (NtotalCards > 13) {
   errors[errnum] = "North has too many cards:-  " + NtotalCards;
   errnum++;
}
else {
    if (NtotalCards < 13) {
       errors[errnum] = "North has too few cards:-  " + NtotalCards;
       errnum++;
    }      
}

//East
if (EtotalCards > 13) {
   errors[errnum] = "East has too many cards:-  " + EtotalCards;
   errnum++;
}
else {
    if (EtotalCards < 13) {
       errors[errnum] = "East has too few cards:-  " + EtotalCards;
       errnum++;
    }      
}
//South
if (StotalCards > 13) {
   errors[errnum] = "South has too many cards:-  " + StotalCards;
   errnum++;
}
else {
    if (StotalCards < 13) {
       errors[errnum] = "South has too few cards:-  " + StotalCards;
       errnum++;
    }      
}
//West
if (WtotalCards > 13) {
   errors[errnum] = "West has too many cards:-  " + WtotalCards;
   errnum++;
}
else {
    if (WtotalCards < 13) {
       errors[errnum] = "West has too few cards:-  " + WtotalCards;
       errnum++;
    }      
}

if (totallength != 52) {
   errors[errnum] = "The total number of cards entered is " + totallength;
   errnum++;
}
//alert("The total length is " + totallength);

//check that all the individual cards are present

//alert('form.NS.value = ' + form.NS.value );
//alert('form.ES.value = ' + form.ES.value );
//alert('form.SS.value = ' + form.SS.value );
//alert('form.WS.value = ' + form.WS.value );

//tempvalue = eval(form.NS.value + form.ES.value + form.SS.value + form.WS.value);

for(var i = 0; i < 4; i++) {
   tempvalue = '';
   for(var j = 0; j < 4; j++) {
       tempvalue = tempvalue + eval("form."+ players.charAt(j)+suits.charAt(i)+".value");
     //  alert('tempvalue = ' + tempvalue );
   }
   if (i == 0) {
      allS = tempvalue;
   }
   if (i == 1) {
      allH = tempvalue;
   }
   if (i == 2) {
      allD = tempvalue;
   }
   if (i == 3) {
      allC = tempvalue;
   }
}
//alert('allS = ' + allS +'\nallH = ' + allH + '\nallD = ' + allD + '\nallC = ' + allC);

//===============================================================
//This part of the code checks if any card is missing
//===============================================================
tempvalue = SortAllCards(allS);
sortedS = tempvalue;
//alert("The spades are " + tempvalue );
if (tempvalue != all_cards) {
  for(var intCount = 0; intCount < 14; intCount++) {
     posn1 =  tempvalue.indexOf(all_cards.charAt(intCount));
     if (posn1 == -1) {
       errors[errnum] = "Card " + all_cards.charAt(intCount) +  "S is missing";
       errnum++;
       blnOK = false;
     }
  }
}

tempvalue = SortAllCards(allH);
sortedH = tempvalue;
//alert("The hearts are " + tempvalue );
if (tempvalue != all_cards) {
  for(var intCount = 0; intCount < 14; intCount++) {
     posn1 =  tempvalue.indexOf(all_cards.charAt(intCount));
     if (posn1 == -1) {
       errors[errnum] = "Card " + all_cards.charAt(intCount) +  "H is missing";
       errnum++;
       blnOK = false;
     }
  }
}
//alert('allD= ' + allD);
tempvalue = SortAllCards(allD);
sortedD = tempvalue;
//alert("The diamonds are " + tempvalue );
if (tempvalue != all_cards) {
  for(var intCount = 0; intCount < 14; intCount++) {
     posn1 =  tempvalue.indexOf(all_cards.charAt(intCount));
     if (posn1 == -1) {
       errors[errnum] = "Card " + all_cards.charAt(intCount) +  "D is missing";
       errnum++;
       blnOK = false;
     }
  }
}

tempvalue = SortAllCards(allC);
sortedC = tempvalue;
//alert("The clubs are " + tempvalue );
if (tempvalue != all_cards) {
  for(var intCount = 0; intCount < 14; intCount++) {
     posn1 =  tempvalue.indexOf(all_cards.charAt(intCount));
     if (posn1 == -1) {
       errors[errnum] = "Card " + all_cards.charAt(intCount) +  "C is missing";
       errnum++;
       blnOK = false;
     }
  }
}

//===============================================================
//This part of the code checks if any card has been used twice
//===============================================================
tempvalue = sortedS;
//alert('tempvalue = ' + tempvalue + '\nditto = ' + ditto + '\nchar1 = ' + char1 + '\nposn1 = ' + posn1);
  for(var intCount = 0; intCount < 13; intCount++) {
     char1 = ditto.charAt(intCount);
     posn1 =  tempvalue.indexOf(char1);
    // alert('tempvalue = ' + tempvalue + '\nchar1 = ' + char1 + '\nposn1 = ' + posn1);
     if (posn1 != -1) {
       // alert('tempvalue.substring(0,posn1) = ' + tempvalue.substring(0,posn1) +
       //       '\n tempvalue.substr(posn1+1) = ' + tempvalue.substr(posn1+1) );
        tempvalue = tempvalue.substring(0,posn1) + tempvalue.substr(posn1+1)
     }
  } 

 if (tempvalue != '') {
     for(var intCount = 0; intCount < tempvalue.length; intCount++) {
        char1 = tempvalue.charAt(intCount)
        errors[errnum] = "Card " + char1 +  "S is present more than once";
        errnum++;
        blnOK = false;
     }
  }

tempvalue = sortedH;
  for(var intCount = 0; intCount < 13; intCount++) {
     char1 = ditto.charAt(intCount);
     posn1 =  tempvalue.indexOf(char1);
     if (posn1 != -1) {
        tempvalue = tempvalue.substring(0,posn1) + tempvalue.substr(posn1+1)
     }
  } 
 if (tempvalue != '') {
     for(var intCount = 0; intCount < tempvalue.length; intCount++) {
        char1 = tempvalue.charAt(intCount)
        errors[errnum] = "Card " + char1 +  "H is present more than once";
        errnum++;
        blnOK = false;
     }
 }


tempvalue = sortedD;
  for(var intCount = 0; intCount < 13; intCount++) {
     char1 = ditto.charAt(intCount);
     posn1 =  tempvalue.indexOf(char1);
     if (posn1 != -1) {
        tempvalue = tempvalue.substring(0,posn1) + tempvalue.substr(posn1+1)
     }
  } 
 if (tempvalue != '') {
     for(var intCount = 0; intCount < tempvalue.length; intCount++) {
        char1 = tempvalue.charAt(intCount)
        errors[errnum] = "Card " + char1 +  "D is present more than once";
        errnum++;
        blnOK = false;
     }
  }


tempvalue = sortedC;
  for(var intCount = 0; intCount < 13; intCount++) {
     char1 = ditto.charAt(intCount);
     posn1 =  tempvalue.indexOf(char1);
     if (posn1 != -1) {
        tempvalue = tempvalue.substring(0,posn1) + tempvalue.substr(posn1+1)
     }
  } 
 if (tempvalue != '') {
     for(var intCount = 0; intCount < tempvalue.length; intCount++) {
        char1 = tempvalue.charAt(intCount)
        errors[errnum] = "Card " + char1 +  "C is present more than once";
        errnum++;
        blnOK = false;
     }
  }

//===============================================================
//Before the final alert box - change any T back to a 10
//===============================================================
//now convert any 10 to a T - temporarily
   for(var i = 0; i < 4; i++) {
      for(var j = 0; j < 4; j++) {
        tempvalue = eval("form."+ players.charAt(i)+suits.charAt(j)+ ".value.replace(regex10,'10')")
         //alert('tempvalue = ' + tempvalue + " i="+i+ " j="+j);
         PopulateMe(eval("form."+ players.charAt(i)+suits.charAt(j)), tempvalue);
      }
   }
   
 
//===============================================================
//Finally, any error messages are displayed
//===============================================================
if (errnum > 0 ) {
   errors[errnum] = '\nPlease check again and press Submit';
   errnum++
   for(var i = 0; i < errnum; i++) {
      if (i > 20) {
         allerrors = allerrors + '\n\n' + 'More errors were found .....';
         break;
      }      	
      allerrors = allerrors + '\n'+ errors[i];
   }
   alert('The following card errors were found in your deal:\n' + allerrors );
   blnOK = false;
}


 return blnOK;
 }

//===============================================================
//========================OTHER FUNCTIONS========================
//===============================================================
function GetPos(bid, allPossBidsArray, StartPos) {
var pos = 0;
//alert ('GetPos bid = ' + bid + '\nStartPos = ' + StartPos );
   for(var i = StartPos; i < 36; i++) {
   //alert ('bid = ' + bid + '\nArray[' + i + '] = ' + allPossBidsArray[i]);
       if (allPossBidsArray[i] == bid) {
          pos = i;
          break; //found the pos
       }   
          
   }
return pos;
}


function CountOccurrences(stringtosearch, searchfor) {
 var count = 0;
 var posn1 = 0;
 //alert ('Search for:' + searchfor + ' in stringtosearch:' + stringtosearch);
  while (stringtosearch.length > 0 && posn1 != -1) {
     posn1 =  stringtosearch.indexOf(searchfor);
     if (posn1 != -1) {
        count++;
        stringtosearch =  stringtosearch.substr(posn1+1)
     }
  }
  //alert ('CountOccurrences count = ' + count);
return count;
}

function PopulateMe(obj, popval)  {
  obj.value = '';
 //alert('obj.name ' + obj.name + 'obj.value ' + popval);
  obj.value = obj.value + popval;

  //return blnOK;
 }

function get_right_char(stringIn) {
//take off the last character
    if (stringIn.length == 0) {
        return false;
    }
    var stringOut = stringIn.substring((stringIn.length - 1));

    return stringOut;
}

function BadBid(i, value, error)  {
 var players = new Array();
 var player = '';
 var n = 0;
 var messg = "";
//alert('BadBid: \ni = ' + i + '\nvalue = ' + value);
 players[1] = "South";
 players[2] = "West";
 players[3] = "North";
 players[4] = "East";

if (i != 0) { //error not assigned to any one player 
    n = i % 4;
    if (n == 0) {
        n = 4;
    }   
    player = players[n];
}


if (value == 'DB') {
    value = 'DOUBLE';
}   
else { 
   if (value == 'RD') {
       value = 'REDOUBLE'; 
   }      
   else { 
      if (value.indexOf('N') == 1) {
          value = value + 'T'; 
      }
   }       
}
 //round = i/4;
//GENERAL ERRORS
if (error == 1) {
   messg = "Four consecutive passes can only occur if they are the only bids of the auction.";
} 
if (error == 2) {
   messg = "Four consecutive passes, if present, must be the only bids of the auction.";
} 
if (error == 3) {
   messg = "Three consecutive passes must be present to complete the auction.";
} 
if (error == 10) {
   messg = "Three consecutive passes can only occur at the beginning or end of the auction.";
} 
if (error == 14) {
   messg = "Please enter the complete bidding sequence.";
}

//BID NOT SUFFICIENT
if (error == 4) {
   messg = " is invalid - the bidding has already reached a higher level.";
}
if (error == 13) {
   messg = " is invalid - duplicate bid.";
}
//          alert('Valid Bid ' + bid  + ' duplicated \nn = ' + n + '\nintCount = ' + intCount);
//DOUBLE & REDOUBLE ERRORS
if (error == 5) {
   messg = " is invalid - the auction has yet to include a valid bid in a suit.";
}
if (error == 6) {
   messg = " is invalid - the previous bid cannot be doubled.";
}
if (error == 7) {
   messg = " is invalid - only valid bids may be doubled.";
}
if (error == 8) {
   messg = " is invalid - the previous bid cannot be redoubled.";
}
if (error == 9) {
   messg = " is invalid - only a DOUBLE can be REDOUBLED.";
}
if (error == 11) {
   messg = " is invalid - no such bid exists.";
}
if (error == 12) {
   messg = " is invalid - partner's bid cannot be doubled.";
}
//Finally, display the error message in all its glory
//alert(player + "'s bid of " + value + messg);
if (i != 0) {  //if i = 0 then it's a general error message
   messg = player + "'s bid of " + value + messg;
}   
return messg;
}

function ShowPlayerSuit(player, suit) {
var ptext = '';
var stext = '';

  if (player == 'N') {
     ptext = 'North';
  }
  if (player == 'E') {
     ptext = 'East';
  }
  if (player == 'S') {
     ptext = 'South';
  }
  if (player == 'W') {
     ptext = 'West';
  }
  if (suit == 'S') {
     stext = 'spades';
  }
  if (suit == 'H') {
     stext = 'hearts';
  }
  if (suit == 'D') {
     stext = 'diamonds';
  }
  if (suit == 'C') {
     stext = 'clubs';
  }

  return ptext + ' ' + stext;
 }

function SortUserInput(textBoxName)  {
 var valu = textBoxName.value;
 var len = textBoxName.value.length;
 var a = new Array();

 for(var i = 0; i < len; i++) {
     a[i] = valu.substring(i, i+1);    //create array with chars
 }
 a.sort(correct_order);                //sort the array in required order

 textBoxName.value = a.join("");
 //return a.join("");                  //return the sorted string
 }

 function SortAllCards(cards)  {
 var valu = cards;
 var len = cards.length;
 var a = new Array();
  //alert('Hello = ' + cards );
 for(var i = 0; i < len; i++) {
     a[i] = cards.substring(i, i+1);    //create array with chars
 }
 a.sort(correct_order);                //sort the array in required order

 return a.join("");                  //return the sorted string
 }


 function correct_order(a, b)  {
 var my_order = 'AKQJT98765432';                        //
 var comparison;
 if (my_order.indexOf(a) > my_order.indexOf(b)) {       // 1st char comes before
    comparison = 1;
 }
 else {
      if (my_order.indexOf(a) < my_order.indexOf(b)) {  // 2nd char comes before
         comparison = -1;
      }
      else {                                            // chars are same!(shouldn't happen)
         comparison = 0;
      }
 }

 return comparison;
 }

 function junk(character)  {
 var validchars = 'AKQJT9876543210';                    //note the 10 at the end!
 var blnOK = false;

 if (validchars.indexOf(character) == -1) {
    blnOK = true
 }

  return blnOK;
 }

 function extractcrap(cellValue)  {
 var validchars = 'SHDCNOTXRBLEPA7654321*?-';  
 var validchars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ987654321*?-';  
 var newcellValue = '';        
 var blnOK = false;
 var thisChar = '';
 for(var i = 0; i < cellValue.length; i++) {
    thisChar = cellValue.charAt(i);
    if (validchars.indexOf(thisChar) != -1) {
       newcellValue = newcellValue + thisChar;
    }   
 }

  return newcellValue;
 }


