/*
* Copyright Sugar Publishing, Inc. 2009, All Rights Reserved
*
*/

var Slots = Class.create();

Slots.prototype= {

'BORDER_WIDTH': 3,
'BORDER_COLOR': '#000',
initialize: function(container, params) {

  params = params || {};

  this.container = container;

  this.spun = params.spun;

  this.bw=new this.verifyCompatibleBrowser();
  this.loop=true
  //		this.speed=1000
  this.numCelebs=10;
  this.stepSize=50;
  this.thumbWidth=120;
  this.thumbHeight=160;
  this.hasJoker=true;
  this.manualStop=false;
  this.lstart=-(this.numCelebs*this.thumbHeight);
  this.bet=1;
  this.scrollerSize=(this.thumbHeight*this.numCelebs);

  this.rnd.today=new Date();
  this.rnd.seed=this.rnd.today.getTime();
  img_dim = {'width' : 240, 'height' : 320};

  width: img_dim.width + 'px'

  this.width  = Math.round((img_dim.width - ((this.dimension+1) * this.BORDER_WIDTH)) / this.dimension);
  this.height = Math.round((img_dim.height - ((this.dimension+1) * this.BORDER_WIDTH)) / this.dimension);
  this.InitializeSlots();

},
InitializeSlots: function (){
  this.objContainer1=new this.ConstructObject(this,'slot1Container')
  this.objContent1=new this.ConstructObject(this,'slot1Content','slot1Container')
  this.objContainer2=new this.ConstructObject(this,'slot2Container')
  this.objContent2=new this.ConstructObject(this,'slot2Content','slot2Container')
  this.objContainer3=new this.ConstructObject(this,'slot3Container')
  this.objContent3=new this.ConstructObject(this,'slot3Content','slot3Container')
  this.objContent1.moveIt(0,this.lstart)
  this.objContainer1.css.visibility='visible'
  this.objContent2.moveIt(0,this.thumbHeight*-3)
  this.objContainer2.css.visibility='visible'
  this.objContent3.moveIt(0,this.thumbHeight*-5)
  this.objContainer3.css.visibility='visible'
},

verifyCompatibleBrowser: function() {
  this.ver=navigator.appVersion
  this.dom=document.getElementById?1:0
  this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0;
  this.ie4=(document.all && !this.dom)?1:0;
  this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
  this.ns4=(document.layers && !this.dom)?1:0;
  this.bw=(this.ie5 || this.ie4 || this.ns4 || this.ns5)
  return this
},

start:	function(bet) {


  // only set the bet if reels are stopped
  if (this.objContent1.reelStopped==true && this.objContent2.reelStopped==true && this.objContent3.reelStopped==true) {
    this.bet=bet;
  }

  if (this.bet==0 && this.objContent1.reelStopped==true && this.objContent2.reelStopped==true && this.objContent3.reelStopped==true) {
    document.getElementById('results').innerHTML="You are out of points! Try tomorrow."
    return;
  }

  // stop each reel in turn
  if (this.objContent1.reelStopped==true && this.objContent2.reelStopped==true && this.objContent3.reelStopped==true) {
    new Ajax.Updater('slotpoints','/games/slots_win',{parameters: 'score=0&why=bet&bet='+this.bet,asynchronous:false,method: 'post'});
  }

  if (this.manualStop==true && this.objContent1.reelStopped==false && this.objContent1.reelAccum>(this.scrollerSize/2)) {
    this.forceStop(this.objContent1);
    //			if (this.objContent2.reelstopped==false) {
    document.getElementById('spinbar').innerHTML="<img src='/themes/pop/imgs/slot_spin_bar_stop_2.gif'>";
    //			}
  } else if (this.manualStop==true && this.objContent1.reelStopped==true && this.objContent2.reelStopped==false) {
    this.forceStop(this.objContent2);
    //			if (this.objContent3.reelstopped==false) {
    document.getElementById('spinbar').innerHTML="<img src='/themes/pop/imgs/slot_spin_bar_stop_3.gif'>";
    //			}
  } else if (this.manualStop==true && this.objContent1.reelStopped==true && this.objContent2.reelStopped==true && this.objContent3.reelStopped==false) {
    this.forceStop(this.objContent3);
    document.getElementById('spinbar').innerHTML="<img src='/themes/pop/imgs/slots_spin_bar.gif'>";
  }

  else if (this.objContent1.reelStopped==true && this.objContent2.reelStopped==true && this.objContent3.reelStopped==true) {

    if (this.manualStop==true) {
      document.getElementById('spinbar').innerHTML="<img src='/themes/pop/imgs/slot_spin_bar_stop_1.gif'>";
    }

    document.getElementById('results').innerHTML="";
    this.objContent1.reelAccum=0;
    this.objContent1.pr_step=this.stepSize;;
    this.objContent2.reelAccum=0;
    this.objContent2.pr_step=this.stepSize;;
    this.objContent3.reelAccum=0;
    this.objContent3.pr_step=this.stepSize;;

    this.objContent1.stopReel=false;
    this.objContent2.stopReel=false;
    this.objContent3.stopReel=false;
    this.objContent1.reelStopped=false;
    this.objContent2.reelStopped=false;
    this.objContent3.reelStopped=false;

    // longer runout on manual stop
    if (this.manualStop==true) {
      increase=10;
    } else {
      increase=1;
    }
    this.objContent1.reelSizeMax=(this.scrollerSize+(Math.floor(this.rnd(2048))))*increase
    this.objContent2.reelSizeMax=(this.scrollerSize+(Math.floor(this.rnd()*4048)))*increase
    this.objContent3.reelSizeMax=(this.scrollerSize+(Math.floor(this.rnd()*6048)))*increase

    this.objContent1.reelRoll(this.objContent1.speed)
    this.objContent2.reelRoll(this.objContent2.speed)
    this.objContent3.reelRoll(this.objContent3.speed)

    // reset reel colors/status
    document.getElementById('slot1Name').style.backgroundColor="white";
    document.getElementById('slot2Name').style.backgroundColor="white";
    document.getElementById('slot3Name').style.backgroundColor="white";
    document.getElementById('celebtd1').style.backgroundColor="white"
    document.getElementById('celebtd2').style.backgroundColor="white"
    document.getElementById('celebtd3').style.backgroundColor="white"
    document.getElementById('slot1Name').innerHTML="Spinning...";
    document.getElementById('slot2Name').innerHTML="Spinning...";
    document.getElementById('slot3Name').innerHTML="Spinning...";

  }
},

rnd:  function() {
  this.rnd.seed = (this.rnd.seed*9301+49297) % 233280;
  return this.rnd.seed/(233280.0);
},

rand: function(number) {
  return Math.ceil(this.rnd()*number);
},



ConstructObject: function(c,obj,nest){
  bw=c.bw;
  nest=(!nest) ? '':'document.'+nest+'.'
  this.el=bw.dom?document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?eval(nest+'document.'+obj):0;
  this.css=bw.dom?document.getElementById(obj).style:bw.ie4?document.all[obj].style:bw.ns4?eval(nest+'document.'+obj):0;
  if (nest) {
    this.reelRoll=c.reelRoll;
    this.moveIt=c.b_moveIt; this.x; this.y;
    this.reelAccum=0;
    this.pr_step=c.stepSize;
    this.speed=Math.floor(c.rand(25)+25);
    this.obj = obj + "Object"
    this.stopReel=true;
    this.reelStopped=true;
    this.celeb=null;
    this.ver=bw.ver;
    this.reelSizeMax=5000;
    this.string=this.obj
  }
  this.c=c;
  eval(this.obj + "=this")
  return this
},

b_moveIt: function(x,y){
  this.x=x;this.y=y
  this.css.left=this.x
  this.css.top=this.y+"px"
},

forceStop: function(slotObj) {
  //			document.getElementById('logger').innerHTML="STOP";
  slotObj.stopReel=true;
  slotObj.pr_step=0;
},

reelRoll: function(speed){

  // we've hit the random length we set, time to stop the reel
  if (this.reelAccum > this.reelSizeMax) {
    this.stopReel=true;
  }


  // still spinning
  if (this.pr_step>0) {
    if(this.y < 0 ){
      // slow down the reel, decrease pr_step
      if(this.stopReel) {
        this.pr_step=this.pr_step-1;
      }
      this.moveIt(0,this.y+this.pr_step)
      setTimeout(this.obj+".reelRoll("+this.speed+")",this.speed)
    } else if (this.c.loop) {
      this.moveIt(0,this.c.lstart)
      eval(this.obj+".reelRoll("+this.speed+")")
    }
    this.reelAccum=this.reelAccum+this.pr_step;
    // stopped now, bump

  }
  else {
    this.mod=this.y % this.c.thumbHeight;
    this.prebump=this.y;

    // determine how much we need tp bump back
    if (this.mod >= -(this.c.thumbHeight/2)) {
      this.y=this.y-this.mod;
    }
    else {
      this.y=this.y-(this.c.thumbHeight+this.mod);
    }

    // rock back for forward to center
    if (this.mod >= -(this.c.thumbHeight/2)) {
      this.dot="."
      this.b=this.prebump;
      for (this.b=this.prebump;this.b<=(this.prebump-this.mod);this.b=this.b+1) {
        //					this.dot=this.dot+"."
        //					document.getElementById('logtext').innerHTML=this.dot
        //					setTimeout(this.obj+".moveIt(0,"+this.b+")",100);
        this.moveIt(0,this.b);
      }
    }
    else {
      for (this.b=this.prebump;this.b>=this.prebump-(this.c.thumbHeight+this.mod);this.b=this.b-1) {
        //					document.getElementById('logtext').innerHTML="b-"+this.b+" ("+this.prebump+")"
        //					setTimeout(this.obj+".moveIt(0,"+this.b+")",100);
        this.moveIt(0,this.b);
      }
    }

    this.reelStopped=true
    this.celeb=Math.floor(Math.abs(this.y)/this.c.thumbHeight)+1;
    // handle the overlap/wrap thing

    if (this.celeb > this.c.numCelebs) {
      this.celeb=1;
    }
    // extract slot number from obj name...ick
    this.slotnum=this.obj.substr(4,1);
    // show name at bottom

    this.pos=document.getElementById("slot"+this.slotnum+"Order").innerHTML;
    this.posArray=this.pos.split(",");
    this.posArray.push(this.posArray[0]);
    //			document.getElementById("logger").innerHTML=this.posArray[this.celeb];
    this.realID=this.posArray[this.celeb-1];
    document.getElementById("slot"+this.slotnum+"Name").innerHTML=document.getElementById("celebname"+this.realID).innerHTML;
    document.getElementById("slot"+this.slotnum+"Name").style.backgroundColor=document.getElementById("celebname"+this.realID).style.backgroundColor;
    document.getElementById("celebtd"+this.slotnum).style.backgroundColor=document.getElementById("celebname"+this.realID).style.backgroundColor;


    if (this.c.objContent1.reelStopped==true && this.c.objContent2.reelStopped==true && this.c.objContent3.reelStopped==true ) {
      document.getElementById('spinbar').innerHTML="<img src='/themes/pop/imgs/slots_spin_bar.gif'>";
      if (typeof this.c.spun == 'function') {

        points=0;
        doublep=2;
        triple=3;
        mix=2;
        bonus=5;
        // invert them
        r1=11-this.c.objContent1.realID;
        r2=11-this.c.objContent2.realID;
        //					r3=11-this.c.objContent3.celeb;
        r3=11-this.c.objContent3.realID;
        // show score debug
        //					document.getElementById('logtext').innerHTML=r1+" "+r2+" "+r3
        why="No matches"
        // triple
        if ((r1 == r2) && (r1 == r3)) {
          if (r1==10) {
            why="Triple match 4x"
            points=3*this.c.bet*4;
          } else if (r1<=4 && r1>1) {
            why="Triple match 2x"
            points=3*this.c.bet*2;
          } else if (r1>4 && r1<10) {
            why="Triple match 3x"
            points=3*this.c.bet*3;
          } else if (r1==1) {
            why="Triple joker"
            points=3*this.c.bet*4
          }
          // joker
        } else if ((this.c.hasJoker==true) && ((r1==1)||(r2==1)||(r3==1))) {
          //						document.getElementById('logger').innerHTML="In joker land..."
          // use wild to match colors
          // 2x
          if ((r1<=6 && r1>1) && (r2<=6 && r2>1) && (r1!=r2) && (r3==1)) {
            why="Mix and match 2x \+ wildcard"
            points=2*this.c.bet
          } else if ((r1<=6 && r1>1) && (r3<=6 && r3>1) && (r1!=r3) &&(r2==1)) {
            why="Mix and match 2x \+ wildcard"
            points=2*this.c.bet
          } else if ((r2<=6 && r2>1) && (r3<=6 && r3>1) && (r2!=r3) && (r1==1)) {
            why="Mix and match 2x \+ wildcard"
            points=2*this.c.bet
            // 3x
          } else if ((r1>6 && r1<10) && (r2>6 && r2<10) && (r1!=r2) && (r3==1)) {
            why="Mix and match 3x \+ wildcard"
            points=3*this.c.bet
          } else if ((r2>6 && r2<10) && (r3>6 && r3<10) && (r2!=r3) && (r1==1)) {
            why="Mix and match 3x \+ wildcard"
            points=3*this.c.bet
          } else if ((r1>6 && r1<10) && (r3>6 && r3<10) && (r1!=r3) && (r2==1)) {
            why="Mix and match 3x \+ wildcard"
            points=3*this.c.bet
            // double celeb with wildcard
          } else if ((r1==1 && r2==1 && r3!=1) || (r2==1 && r3==1 && r1!=1) || (r1==1 && r3==1 && r2!=1)) {
            if (r1==1 && r2==1) {
              if (r3<=6 && r3>1) {
                why="Double wildcard with 2x"
                points=3*this.c.bet*2
              } else if (r3>6 && r3<10) {
                why="Double wildcard with 3x"
                points=3*this.c.bet*2*2
              } else if (r3==10) {
                why="Double wildcard with 4x"
                points=3*this.c.bet*2*3
              }
            } else if (r1==1 && r3==1) {
              if (r2<=6 && r2>1) {
                why="Double wildcard with 2x"
                points=3*this.c.bet*2
              } else if (r2>6 && r2<10) {
                why="Double wildcard with 3x"
                points=3*this.c.bet*3
              } else if (r2==10) {
                why="Double wildcard with 4x"
                points=3*this.c.bet*4
              }
            } else if (r2==1 && r3==1) {
              if (r1<=6 && r1>1) {
                why="Double wildcard with 2x"
                points=3*this.c.bet*2
              } else if (r1>6 && r1<10) {
                why="Double wildcard with 3x"
                points=3*this.c.bet*3
              } else if (r1==10) {
                why="Double wildcard with 4x"
                points=3*this.c.bet*4
              }
            }

            // use wildcard to complete faces
          } else if (r1==r2 && r3==1) {
            if (r1<=6 && r1>1) {
              why="Triple match 2x \+ wildcard"
              points=3*this.c.bet*2
            } else if ((r1>6) && (r1<10)) {
              why="Triple match 3x \+ wildcard"
              points=3*this.c.bet*3
            } else if (r1==10) {
              why="Triple match 4x \+ wildcard!"
              points=3*this.c.bet*4
            }
          } else if (r1==r3 && r2==1) {
            if (r1<=6 && r1>1) {
              why="Triple match 2x + wildcard"
              points=3*this.c.bet*2
            } else if ((r1>6) && (r1<10)) {
              why="Triple match 3x + wildcard"
              points=3*this.c.bet*3
            } else if (r1==10) {
              why="Triple match 4x \+ wildcard!"
              points=3*this.c.bet*4
            }
          } else if (r2==r3 && r1==1) {
            if (r2<=6 && r2>1) {
              why="Triple match 2x \+ wildcard"
              points=3*this.c.bet*2
            } else if ((r2>6) && (r2<10)) {
              why="Triple match 3x \+ wildcard"
              points=3*this.c.bet*3
            } else if (r2==10) {
              why="Triple match 4x \+ wildcard!"
              points=3*this.c.bet*4
            }
          }


          // a mix of celebs
        } else if ((r1<=6 && r1>1) && (r2<=6 && r2>1) && (r3<=6 && r3>1)) {
          why="Mix and match 2x"
          points=2*this.c.bet
        } else if ((r1>6 && r1<10) && (r2>6 && r2<10) && (r3>6 && r3<10)) {
          why="Mix and match 3x"
          points=3*this.c.bet
        }
        if (points>0) {
          //						document.getElementById('logtext').innerHTML=why
          setTimeout("s.spun("+points+",'"+why+"',"+this.c.bet+")",200);
        } else {
          // yuck...hard-coded 's'
          setTimeout("s.spun("+points+",'"+why+"',"+this.c.bet+")",200);
          //						document.getElementById('results').innerHTML="No Points. Spin again!"
        }
      }
    }
  }
}

}

function getBetValue(slotObj) {

  if(!slotObj) return "0";
  var slotbetLength = slotObj.length;
  pts=document.getElementById('slotpoints').innerHTML;

  // remove the asterisk added if they're credits

  re=/\\*/;
  points=pts.replace(re,'');
  // important, convert string to int
  points=parseInt(points);

  if (points <= 0) {
    return 0;
  }

  if(slotbetLength == undefined) {
    if(slotObj.checked) {
      if (points <= 0) {
        return 0;
      } else {
        if (slotObj.value > points) {
          return points;
        } else {
          return slotObj.value;
        }
      }
    } else {
      return "0";
    }
  }
  for(var i = 0; i < slotbetLength; i++) {
    if(slotObj[i].checked) {
      if (slotObj[i].value>points) {
        return points;
      } else {
        return slotObj[i].value;
      }
    }
  }
  return "0";
}

if (Class) {
  var Puzzle = Class.create();

  Puzzle.prototype = {
  'BORDER_WIDTH': 3,
  'BORDER_COLOR': '#000',
  initialize: function(container, params) {
    this.is_shuffled = false;
    params = params || {};
    this.onVictory = params.onVictory;

    this.container = container;
    this.dimension = params.dim || 4;
    this.starting_state = new Array();

    this.pieces = new Array(this.dimension);
    for (var i = 0; i < this.dimension; i++) {
      this.pieces[i] = new Array(this.dimension);
    }

    // Set the bottom-right corner to the empty piece
    this.empty_piece = [this.dimension-1,this.dimension-1]
    this.clicks = 0;

    this.puzzle_img = $(this.container).getElementsByTagName('img')[0];

    img_dim = {'width' : this.puzzle_img.width, 'height' : this.puzzle_img.height};

    $(container).setStyle({
      height: img_dim.height + 'px',
      overflow: 'hidden',
      position: 'relative',
      width: img_dim.width + 'px'
    });

    this.width  = Math.round((img_dim.width - ((this.dimension+1) * this.BORDER_WIDTH)) / this.dimension);
    this.height = Math.round((img_dim.height - ((this.dimension+1) * this.BORDER_WIDTH)) / this.dimension);

    for (var i = 0; i < this.dimension; i++) {
      for (var j = 0; j < this.dimension; j++) {
        if (this.is_empty(i, j)) {
          continue;
        }

        var piece = document.createElement('div');
        Element.extend(piece);
        piece.pos_x = i;
        piece.pos_y = j;
        this.pieces[i][j] = piece;
        this.starting_state.push(piece);

        var offset_x = -(this.width + this.BORDER_WIDTH) * i;
        var offset_y = -(this.height + this.BORDER_WIDTH) * j;

        piece.setStyle({
        'border': this.BORDER_WIDTH + 'px solid ' + this.BORDER_COLOR,
        'background': 'url(' + this.puzzle_img.src + ') no-repeat ' + offset_x + 'px ' + offset_y + 'px',
        'cursor': 'pointer',
        'height': this.height + 'px',
        'left':  (-offset_x) + 'px',
        'top':  (-offset_y) + 'px',
        'overflow': 'hidden',
        'position':	'absolute',
        'width':	 this.width + 'px'
        });
      }
    }

    this.solution = this.current_configuration();
  },

  start: function(shuffle) {
    for (var i = 0; i < this.starting_state.length; i++) {
      var piece = this.starting_state[i];
      Event.observe(piece, 'mousedown', function(e) {
        var piece = Event.element(e);
        var x = piece.pos_x;
        var y = piece.pos_y;

        if (this.is_empty(x+1, y)) {
          this.move_to_empty(piece, x+1, y);
        }
        else if (this.is_empty(x-1, y)) {
          this.move_to_empty(piece, x-1, y);
        }
        else if (this.is_empty(x, y+1)) {
          this.move_to_empty(piece, x, y+1);
        }
        else if (this.is_empty(x, y-1)) {
          this.move_to_empty(piece, x, y-1);
        }
      }.bindAsEventListener(this), true);

      $(this.container).appendChild(piece);
    }

    this.puzzle_img.style.display = 'none';

    if (shuffle) {
      this.shuffle();
    }
  },

  is_empty: function(row,col) {
    return (this.empty_piece[0] == row && this.empty_piece[1] == col)
  },

  set_empty: function (row,col) {
    this.empty_piece = [row, col];
    this.pieces[row][col] = null;
  },

  move_to_empty: function(piece, x, y, duration, check_solution) {
    var width = this.width + this.BORDER_WIDTH;
    var height = this.height + this.BORDER_WIDTH;

    duration = duration || 0.1;
    new Effect.Move(piece, {
      x: width*(x - piece.pos_x),
      y: height*(y - piece.pos_y),
      transition: Effect.Transitions.linear,
      duration: duration,
      queue: 'end'
    });

    if (typeof check_solution == 'undefined') {
      check_solution = true;
    }

    this.pieces[x][y] = piece;
    this.set_empty(piece.pos_x, piece.pos_y);

    piece.pos_x = x;
    piece.pos_y = y;

    this.clicks++;

    if (this.is_shuffled && check_solution && this.is_solved()) {
      if (typeof this.onVictory == 'function') {
        this.onVictory(this.clicks);
      }

      this.clicks = 0;
      this.is_shuffled = false;
    }
  },

  is_solved: function() {
    return (this.current_configuration() == this.solution);
  },

  current_configuration: function() {
    return this.starting_state.inject('', function(sol, piece) {
      return sol + piece.pos_x + ',' + piece.pos_y + ' ';
    });
  },

  shuffle: function() {
    // This seems pretty good.
    for (var i = 0; i < this.dimension*10; i++) {
      this.move_randomly();
    }

    this.is_shuffled = true;
  },

  move_randomly: function() {
    var x = this.empty_piece[0]
    var y = this.empty_piece[1];
    var valid_moves = new Array();

    if (this.pieces[x+1] && this.pieces[x+1][y]) {
      valid_moves.push(this.pieces[x+1][y]);
    }

    if (this.pieces[x-1] && this.pieces[x-1][y]) {
      valid_moves.push(this.pieces[x-1][y]);
    }

    if (this.pieces[x] && this.pieces[x][y+1]) {
      valid_moves.push(this.pieces[x][y+1]);
    }

    if (this.pieces[x] && this.pieces[x][y-1]) {
      valid_moves.push(this.pieces[x][y-1]);
    }

    var move = valid_moves[Math.floor(Math.random()*valid_moves.length)];

    this.move_to_empty(move, x, y, 0.03, false);
    this.clicks = 0;
  }
  }
}
