var largeImageBase = "/images/cards/Large/";
var bigCardBack = "/images/odds-calculator/card-back.png";

var Table = {};
Table.positions = ['seat1', 'seat2', 'board', 'seat3', 'seat4', 'seat5', 'seat6', 'seat7', 'seat8', 'seat9', 'seat10'];
Table.position = 'seat1';

function find_next_position(last) {
	if (!last) last = 'seat1';
	
	// makes an independant copy of the array
	var myPositions = Table.positions.slice();
	var idx = Table.positions.indexOf(last);
	var front = myPositions.splice(idx);
	myPositions = front.concat(myPositions);
	var originalPosition = myPositions[0];
	
	var nextPos = 'seat1';
	var cardIdx = 0;
	for (var i=0; i < myPositions.length; i++) {

		var pos = myPositions[i];

		if ((originalPosition == 'board') && (i > 0)) {
			// If we start at the board, when we are done we need to start
			// back at seat1 cause seat 1 and seat 2 should always fill before
			// moving on.
			return find_next_position('seat1');
		}
		
		cardIdx = openCard(pos);
		if ( cardIdx != null) {
			nextPos = pos;
			break;
		}
	}
	return [nextPos, cardIdx];
}

function openCard(pos) {
	var cards = $('#' + pos + ' img.card');
	var idx = null;
	for (var i=0; i < cards.length; i++) {
		var rel = $(cards[i]).attr('rel');
		if ( rel == '' || rel == undefined ) {
			idx = i;
			break;
		}
	}
	return idx;
}

function resetPosition(pos) {
	$.each($('#' + pos + ' img.card'), function() {returnCard(this)});
	$('div.hand-odds').find('span.win, span.tie').text('');
	$('div.seat div.hand-odds').css('visibility', 'hidden');
}

function setPosition(pos) {
	Table.position = pos;
	highlightPosition(Table.position);
}

function returnCard(card) {
	var rel = $(card).attr('rel');

	if (rel) {
		$('#deck img[rel=' + rel + ']').css('visibility', 'visible');
		$(card).attr('rel', '');
		$(card).attr('src', bigCardBack);
		return true;
	}
	else {
		return false;
	}
}

function highlightPosition(pos, idx) {
	// Remove the highlight from the last card
	$('img.selected-position').removeClass('selected-position')
	
	if (!idx) idx = openCard(pos);
	$($('#' + pos + ' img.card')[idx]).addClass('selected-position');
}

function calcOdds() {
	var hands = jsonCards();
	
	if (hands) {
		$.getJSON("/poker-tools/odds-calculator/texas-holdem", hands, function(data) {
			$.each(data, function(seat, hand) {
				$('#' + seat + ' div.hand-odds span.win').text(hand.win_pct);
				$('#' + seat + ' div.hand-odds span.tie').text(hand.tie_pct);
				$('#' + seat + ' div.hand-odds').css('visibility', 'visible');
			});
		});
	}
}

function handVals(seat) {
	var hand = $.map( $('#' + seat + ' img.card'), function(v) {return $(v).attr('rel')} );
	var ret = [];
	if (seat == 'board') {
		if ( (hand[0] != '' && hand[0] != undefined) && (hand[1] != '' && hand[1] != undefined) && (hand[2] != '' && hand[2] != undefined) ) {
			ret.push(hand[0]); ret.push(hand[1]); ret.push(hand[2]);
			if ( (hand[3] != '' && hand[3] != undefined) ) {
				ret.push(hand[3]);
				if ( (hand[4] != '' && hand[4] != undefined) ) {
  				ret.push(hand[4]);
  			}
			}
		}
	}
	else {
		$.each(hand, function(i,val) {
			if (val != '')
				ret.push(val);
		})
	}
	return ret;
}

function jsonCards() {
	var hands = {};
	var handCount = 0;
	$.each(Table.positions, function(i,seat) {
		cards = handVals(seat);
		if (cards.length == 2) {
			if (seat != 'board') {
				++handCount;
			}
			hands[seat] = cards.join(",");
		}
	})
	hands['board'] = handVals('board').join(",");
	
	if (handCount > 1) {
		return hands;
	}
	else {
		return false;
	}
}

$(function() {
  if (Cookie.get('odds-calculator-help-first-time') == 'false') {
	  $('#cal-help-window').hide();
  }
  Cookie.set('odds-calculator-help-first-time', 'false');

	$('a.cal-help, a#red-x').click(function() {
		$('#cal-help-window').toggle();
		return false;
	});

	highlightPosition(Table.position);
	$('div.seat div.hand-odds').css('visibility', 'hidden');

	$('#table div.seat img.card, div#board img.card').click(function() {
		var seat = $(this).parent().attr('id');
		if (seat) {
			var ret = returnCard(this);
			setPosition(seat);
			if (ret) {
				var hand = handVals(seat);
				if ( (seat == 'board' && hand.length != 5) || hand.length == 1 ) {
					// kill the odds and recalc
					$('div.hand-odds').find('span.win, span.tie').text('');
					$('div.seat div.hand-odds').css('visibility', 'hidden');
					calcOdds();
				}
			}
		}
	})

	$('#deck img.deck-card').click(function() {
		var seat = Table.position;
		var cardIdx = openCard(Table.position);
		if (cardIdx == null) {
			// This should mean that all of the cards are already dealt
			return false;
		}
		
		var card = $(this).attr('rel');
		$(this).css('visibility', 'hidden');
		
		var card = $($('#' + Table.position + ' img.card')[cardIdx]);
		card.attr('rel', $(this).attr('rel'));
		card.attr('src', largeImageBase + $(this).attr('card'));

		try {
			Table.position = find_next_position(Table.position)[0];
		}
		catch(e) {
			Table.position = 'seat1';
		}
		
		highlightPosition(Table.position);

		if (seat == 'board') {
			var board = handVals('board');
			if (board.length > 2) {
				calcOdds();
			}
		}
		else {
			calcOdds();
		}
	});
	
	$('#reset').click(function(event) {
		$.each(Table.positions, function(i,pos) {
			resetPosition(pos);
		});
		setPosition('seat1');
	});
})

// For IE compatibility as IE doesn't support indexOf.  Bad browser!
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
