var movesmade=0;
var cturn= "Computer's Turn";
var uturn= "Your Turn";
var d1used=d2used= false;
var srcd1;  //die 1 src
var d1;         //die 1 value
var srcd2;  //die 2 src
var d2;         //die 2 value
var wclicks = new Array(); //holds ids for white moves
var bclicks = new Array(); //holds ids for black moves
var wi = parseInt("0");    //ptr for wclicks array
var bi = parseInt("0");     //ptr for bclicks array
function clone(obj){
    for(var key in obj)
    {
      if(typeof obj[key]=='object')
      {
        this[key] = new clone(obj[key]);
      }
      else
      {
       this[key]= obj[key];
      }
    }
}

//This is encapsulates the backgammon board
function Board()
{
  this.p1 = "human";
  this.p2 = "cpu";
  this.turn = this.p1; 
  this.wbar= new Array("0");   
  this.bbar= new Array("0");   
                 //pts  bgl  1   2   3   4   5   6   7   8   9  10   11  12
  this.wtop = new Array("0","2","0","0","0","0","0","0","0","0","0","0","5");
  this.wbot = new Array("0","0","0","0","3","0","5","0","0","0","0","0","0");
                // pts  13  14  15  16  17  18  19  20  21  22  23  24 wgl
                        
 
                 //pts  bgl  1   2   3   4   5   6   7   8   9  10   11  12 
  this.btop = new Array("0","0","0","0","0","0","5","0","3","0","0","0","0");
  this.bbot = new Array("5","0","0","0","0","0","0","0","0","0","0","2","0");
                // pts   13  14  15  16  17  18  19 20  21   22  23  24 wgl
  this.count; //number of pieces removed+pcs ready
}

Board.prototype={
  roll:function()
  {
  var num= Math.round(Math.random()*5)+1;
  document.getElementById("die1").src="die"+num+".gif";
  srcd1 = document.getElementById("die1").src;
  d1 = parseInt(srcd1.charAt(srcd1.length-5));
  num= Math.round(Math.random()*5)+1;
  document.getElementById("die2").src="die"+num+".gif";
  srcd2 = document.getElementById("die2").src;
  d2 = parseInt(srcd2.charAt(srcd2.length-5));
  },
  turnswitch:function()
  {
   if(this.wbot[12]==15)
   {document.getElementById("error").innerHTML="WHITE WINS!";}
   else if(this.btop[0]==15)
   {document.getElementById("error").innerHTML="BLACK WINS!";}
   else{
   document.getElementById("dieo1").src=srcd1;;
   document.getElementById("dieo2").src=srcd2;
   this.roll();
   movesmade=0;
   d2used=false;
   d1used=false;
   if(this.turn==this.p1)
   {
    if(bclicks.length!=0){
      for(key in bclicks)
      {
        document.getElementById(bclicks[key]).className="pt";
      }
     }
    bclicks = new Array();
    bi=parseInt("0");
    this.turn=this.p2;
    document.getElementById("turn").innerHTML=cturn;
    this.move('pt1');
   }
   else
   {
    if(wclicks.length!=0){
    for(wkey in wclicks)
    {
     document.getElementById(wclicks[wkey]).className="pt";
     if(bclicks.length!=0)
     {
      for(bkey in bclicks)
      {
       if(bclicks[bkey]==wclicks[wkey])
        {
         document.getElementById(wclicks[wkey]).className="click";
         break;}
      }
     }
    }
   }
    wclicks = new Array();
    wi=parseInt("0");
    this.turn=this.p1;
    document.getElementById("turn").innerHTML=uturn;
   }
   }
  },
  getval:function()//returns the value of a black move
  {
    var value=(2*this.btop[0])-parseInt(this.bbar[0])+parseInt(2.5*this.wbar[0]);
    for(z=0;z<=12;z++)
    {
      if(0<z<=6)
      {value+=parseInt(this.btop[z]);}
      if(z>0 && this.btop[z]==1)
      {value--;}
      else if(z>0 && this.btop[z]>1)
      {value+=parseInt("2");}
      if(this.bbot[z]==1)
      {value--;}
      else if(this.bbot[z]>1)
      {value++;} 
    }
    if((movesmade!=1 && d1!=d2) || (movesmade!=3 && d1==d2))
    {
      this.checkmoves('no');
      if(this.turn==this.p1)
	{value-=100;}
    }
    return parseInt(value);
  },
  checkmoves:function(flag)
  { //check if any moves are possible
      var moveposs = false;                             //flag to determine if moves are possible
      for(i=1;i<=24;i++)
      {
        if(this.turn==this.p1){
        var a= d1+i;
        var b= d2+i;
        var top= this.wtop;
        var bot= this.wbot;
        var opt= this.btop;
        var opb= this.bbot;
        }
        else{
        var top= this.btop;
        var bot= this.bbot;
        var opt= this.wtop;
        var opb= this.wbot;
        var a= i-d1;
        var b= i-d2;}
        if(d1used!=true){
        if((a>0 && a<25)||((a==0||a==25)&& this.count==15)){
          if(a<=12 && opt[a]<=1 && top[i]>0)
          {
           moveposs=true;
           break;
          }
          else if(a>12 && opb[a-13]<=1 && bot[i-13]>0)
          {
           moveposs=true;
           break;
          } 
         }
        }//end check of die1 usage
        if(d2used!=true){
        if((b>0 && b<25)||((b==0||b==25)&& this.count==15)){
          if(b<=12 && opt[b]<=1 && top[i]>0)
          {           
           moveposs=true;
           break;
          }
          else if(b>12 && opb[b-13]<=1 && bot[i-13]>0)
          {
           moveposs=true;
           break;
          }
        } 
       }
      }//end check of die2 usage
      if(moveposs==false)
      {
       if(flag=="no")
       {
         if(this.turn==this.p1)
         {
          this.turn=this.p2;
         }
         else
         {
          this.turn=this.p1;
         }
       }
       else{
        this.turnswitch();
        }
      }
  },//end of check for any possible moves
  move:function(point)
  {
   if(this.wbot[12]==15)
     {document.getElementById("error").innerHTML="WHITE WINS!";}
   else if(this.btop[0]==15)
     {document.getElementById("error").innerHTML="BLACK WINS!";}
   else{

  if(this.turn==this.p1){//set up move for white
  var top= this.wtop;
  var bot= this.wbot;
  var opt= this.btop;
  var opb= this.bbot;
  var opbar= this.bbar;
  var bar= this.wbar;
  var prefix = "w";
  var opre = "b";
  }
  else{
  var top= this.btop;
  var bot= this.bbot;
  var opt= this.wtop;
  var opb= this.wbot;
  var opbar= this.wbar;
  var bar= this.bbar;
  var prefix = "b";
  var opre = "w";
  }
  var moved= false;                                       //flag to tell if a move was made
  this.count=0;                                           //number of pieces removed+pcs ready
  var pcs=0;                   //number of pieces on the point clicked
  if(this.turn==this.p2)
    {
      for(i=6;i>=0;i--)
        {
         this.count+=parseInt(top[i]);
        }
    }
    else
    {
      for(i=6;i<=12;i++)
         {
          this.count+=parseInt(bot[i]);
         }
    }
      var possclicks = new Array(); //hold boards
   var possclicksi= new Array(); //hold move values
   if(prefix=="b")
   {
    if(bar[0]==0){
    var value=parseInt("-100");
    var arrind = parseInt("0"); //location for next element in array
    for(j=1;j<13;j++)
    {
     if(top[j]>0)
      {
       if(d1used==false){
         var apoint = parseInt(j)-d1;}
       else
        {var apoint = parseInt(j)-d2;}
       if(0<apoint && opt[apoint]<2)
         {
          var copy= new clone(this);
          copy.btop[j]--;
          if(opt[apoint]==1)
          {copy.wbar[0]++;
           copy.wtop[apoint]--;
          }
          copy.btop[apoint]++;
          possclicks[arrind]=copy;
          possclicksi[arrind]=j;
          arrind++;
         }//end 0<apoint if
       else if(this.count==15 && 0>=apoint)
         {
          var spot = j+parseInt("1");
          while(spot<7)
          {
           if(top[spot]==0)
             {spot++;}
            else
             {break;}
           }
           if(spot==7){ 
             var copy= new clone(this);
             copy.btop[j]--;
             copy.btop[0]++;
             possclicks[arrind]=copy;
             possclicksi[arrind]=j;
             arrind++;
             }
            if(j==6)
            {break;}
         }
       }//end if top[j]>0
     }//end for loop
    for(i=0;i<12;i++)
    {
     if(bot[i]>0)
      {
        if(d1used==false)
        {
          var apoint = parseInt("13")+parseInt(i)-parseInt(d1);
        }
        else
        {var apoint = parseInt("13")+parseInt(i)-parseInt(d2);}
        if(apoint<=12 && opt[apoint]<2)
         {
          var copy= new clone(this);
          copy.bbot[i]--;
          if(opt[apoint]==1)
          {copy.wbar[0]++;
           copy.wtop[apoint]--;}
          copy.btop[apoint]++;
          possclicks[arrind]=copy;
          possclicksi[arrind]=parseInt("13")+parseInt(i);
         arrind++;}//end apoint < 12
        else if(12<apoint && opb[apoint-13]<2)
         {
          var copy= new clone(this);
          copy.bbot[i]--;
          if(opb[apoint-13]==1)
          {copy.wbar[0]++;
           copy.wbot[apoint-13]--;}
          copy.bbot[apoint-13]++;
          possclicks[arrind]=copy;
          possclicksi[arrind]=parseInt("13")+parseInt(i);
         arrind++;}//end else if
      }//end if bot[i] > 0
     }//end fpr loop
    if(possclicks.length!=0){
     var fl =false;
     if(d1used==false)
     {d1used=true;
      fl=true;}
     for(x in possclicks)
     {
      var tempval = possclicks[x].getval();
      if(tempval>=value)
       {
        value=tempval;
        pt=possclicksi[x];
       }
     }
      if(fl==true)
      {d1used=false;}
    }
    else if(d1used==false && d1!=d2)
    {
       swap();
       pt=parseInt("1");
    }
    else{
       this.turnswitch();
     }
    }//end if bar[0]==0
    else
    {
     point="barb";
    }
   }//end if prefix is b
   if(bar[0]==0)
   { 
   if(prefix!="b"){
   var pt = parseInt(point.substr(2,point.length-1));}      //the point that was clicked
   if(((pt<=12) && (top[pt]>0) && (pcs=top[pt])) || ((pt>=13)&&(bot[pt-13]>0)&&(pcs=bot[pt-13]))) 
      //are there pieces to be moved? if so set pieces
   {
    var legal = true;
    if(d1==d2 ||movesmade==0 ||d2used==true){//there are doubles or no moves yet. We focus on die 1
        if(this.turn==this.p1){   //white turn?
    	   var tomv = pt+d1;}  //pt that piece will be added to
        else{                   //black turn
            var tomv = pt-d1;}  //pt for piece to move if black
     } //end of handling for die 1
    else{                       //no doubles 
        if(this.turn==this.p1){   //white turn?
    	     var tomv = pt+d2;}  //pt that piece will be added to
        else{                   //black turn
             var tomv = pt-d2;} //pt for piece to move if black
    } //end of setting point pc will be added to
       if(tomv>25 && this.count==15 && this.turn==this.p1)
            {
             var spot = pt-14;
             while(spot>4)
             {
              if(bot[spot]==0)
               {spot--;}
              else
               {break;}
             }
             if(spot==4){
              tomv=25;}
            } 
       else if(tomv<0 && this.count==15 && this.turn==this.p2)
            {
             tomv=0;
            } 
       if(tomv==0 || tomv==25)//can't bear off til all piece in home zone
       {
        if(this.count!=15)
         {legal=false;} 
       }
    if(((tomv<=12 && opt[tomv]<=1) || (tomv>=13 && opb[tomv-13]<=1)) &&legal==true) //can the                                                                                  //pieces be moved?
    {                                                                              //pcs be moved
      if((d1==d2 && movesmade<4) || (d1!=d2 && movesmade<2)) //doubles were rolled
      {
        if(pcs>=2){            //is there more than 1 piece on point
          if(pt>12){
            document.getElementById("pt"+pt).src=prefix+(parseInt(pcs)-1)+".gif";}
          else{
            document.getElementById("pt"+pt).src="u"+prefix+(parseInt(pcs)-1)+".gif";}
         } //end of mult. pc. check
        else                   //there is only 1 pc.
        {
         document.getElementById("pt"+pt).src="clrpc.gif";
        } //end of 1 pc situation
        document.getElementById("pt"+pt).className="click"; //highlight piece that was clicked
        if(prefix=="w")
        {
         wclicks[wi]="pt"+pt;
         wi++;
        }
        else
        {
         bclicks[bi]="pt"+pt;
         bi++;
        }
        movesmade++;           //increment # of moves made
        moved=true;            //set flag to true
        if(d1!=d2 && movesmade==1){
          d1used=true;
        }
      }//move made if block/doubles rolled
      if(moved==true){               //was move made?
       if(pt<=12)
       {
        top[pt]--;                 //decrement point moved from
       }
       else
       {
        bot[pt-13]--;               //decrement point moved from
       }
       if(tomv<=12)                 //top half of board
       {
         top[tomv]++;             //increment point moved to
         document.getElementById("pt"+tomv).src="u"+prefix+top[tomv]+".gif";
         if(opt[tomv]==1){       //handle putting opponent on bar
           opt[tomv]--;          //remove opponent from point
           opbar[0]++;              //add opponent to bar
           document.getElementById("bar"+opre).src=opre+opbar[0]+".gif";
       }//end of handling putting opponent on bar
    }//end of handling move in the top half of the board
    else  //handle move in bottom half of the board
      {
       bot[tomv-13]++;                     //increment pt moved to                                
       document.getElementById("pt"+tomv).src= prefix+bot[tomv-13]+".gif";
       if(opb[tomv-13]==1){               //handle putting opponent on bar
         opb[tomv-13]--;
         opbar[0]++;
         document.getElementById("bar"+opre).src=opre+opbar[0]+".gif";
         }//end handling putting opp on bar
      }//end handling move in bottom half of the board
        document.getElementById("pt"+tomv).className="click"; //highlight move made
        if(prefix=="w")
        {
         wclicks[wi]="pt"+tomv; 
         wi++;
        }
        else
        {
         bclicks[bi]="pt"+tomv;
         bi++;
        }
      if((movesmade==2 && d1!=d2) || (movesmade==4 && d1==d2))  //check for end of turn
   	{
   	  this.turnswitch();
        }//end of check for end of turn
         if(this.wbot[12]==15)
          {document.getElementById("error").innerHTML="WHITE WINS!";}
         else if(this.btop[0]==15)
          {document.getElementById("error").innerHTML="BLACK WINS!";}
      }//end of moved==true block
     }//end of can pcs be moved block
      else{
        this.checkmoves();
      }//end of check for possible moves
    }//end of are there pcs to be moved block
    else{
     this.checkmoves();
    }//end of check for possible moves
  }//end of bar check
  else if(bar[0]!=0 && (point=="bar"+prefix))//handle attempt to move off bar
  {
    moved=false;
    var d2mv=d1mv=false;
    if(d1==d2 || movesmade==0 || d2used==true){
      var ind = d1;
      d1mv=true;}
    else{
     var ind= d2;
     d2mv=true;}
     if(this.turn==this.p1)
     {
       var ophome = this.btop; //location opponent debars
       var plhome = this.wtop;  //location plyr debars
       var spot = ind;         //location according to points
     }
     else
     {
       var ophome = this.wbot; //location opponent debars
       var plhome = this.bbot;  //location plyr debars
       var indy = ind;
       ind= parseInt("12")-indy;//location in black bottom array
       var spot= parseInt("25")-indy; //location according to points
     }
     if(ophome[ind]<=1 || ((d2used==false)&&(d1!=d2)&& (((prefix=="w")&&(ind=d2)&&(spot=d2))||((prefix=="b")&&(ind=parseInt("12")-d2)&&(spot=parseInt("25")-d2)))&&(ophome[ind]<=1)&&(d2mv=true)))
     {
       if(ophome[ind]==1)
       {
        opbar[0]++;                                           //add opponent pc to bar
        ophome[ind]--;
        document.getElementById("bar"+opre).src= opre+opbar[0]+".gif";
       }
       plhome[ind]++;
       if(prefix=="w"){
          document.getElementById("pt"+spot).src= "u"+prefix+plhome[ind]+".gif";
          document.getElementById("pt"+spot).className="click"; //highlight move made
          wclicks[wi]="pt"+spot;                             //add id to array of highlighted mvs
          wi++;                                              //update ptr
       } //move pc off bar
       else{
          document.getElementById("pt"+spot).src=prefix+plhome[ind]+".gif";
          document.getElementById("pt"+spot).className="click"; //highlight move made
          bclicks[bi]="pt"+spot;                              //add id to array of highlighted mvs
          bi++;                                             //update ptr
       }
       bar[0]--;
       if(bar[0]==0){
          document.getElementById("bar"+prefix).src= "clrpc.gif";}
       else{
          document.getElementById("bar"+prefix).src= prefix+bar[0]+".gif";}
       movesmade++;
       moved=true;
       if(d2mv==true )      //was d2 used?
       {d2used=true;}
       else if(d1mv==true && d1!=d2)  //was d1 used?
       {d1used=true;}
    }//end of poss getting off bar 
    if(movesmade==0 || (movesmade==2 && d1!=d2)|| movesmade==4 || moved==false)
    {
     this.turnswitch();
    }
  } // end of attempt to handle getting off of bar
    if(this.turn==this.p2)
    {
      this.move("pt1");
    }
  }
 }//end of move method
};

var brd= new Board();

function swap()
{
 if(d1used==false && d2used==false){
  document.getElementById("die1").src=srcd2;
  document.getElementById("die2").src=srcd1;
  srcd1= document.getElementById("die1").src;
  srcd2= document.getElementById("die2").src;
  d1=parseInt(srcd1.charAt(srcd1.length-5));
  d2=parseInt(srcd2.charAt(srcd2.length-5));
 }
 //else swap is no longer possible
}
