var odds_types = ['moneylines', 'spreads', 'totals'];
var games_data = {};
var bets = {};

/*
 * GAMES MANAGEMENT
 */
function addGame(event_id) {
	closeNavMenu();
	//$('.match-event-new').append('<div class="loading-event"></div>');
	$.get('/ajax/getmatch/id/'+event_id+'/calculator/'+calculator_type, function(game) {
	
		games_data[event_id] = game;
		$('.match-event-new').append('<div class="loading-event"></div>');
		if(replace_event_id == null) {
		
			$('.match-event-new').before(game.html);
		}else{
		
			$('#match-event-'+replace_event_id).replaceWith(game.html);
			$('#link-add-event-'+replace_event_id).css('display', '');
			if(calculator_type == 'wager') {
				$('.one-bet').css('display', 'none');
				$('.one-bet .match-event-medium').css('display', 'none');
				$('.no-bet').css('display', 'block');
				//$('.calculator-result .bloc-result-wager').css('display', 'none');
				
//				for(type in bets[replace_event_id]) {
//					outcome = bets[replace_event_id][type];
//					$('#' + event_id + '-' + type + '-' + outcome).attr('checked', 'checked');
//					updateBet(event_id, type, outcome, $('#' + event_id + '-' + type + '-' + outcome));
//				}
			}
			delete bets[replace_event_id];
		}
		$('#link-add-event-'+event_id).css('display', 'none');
		if(calculator_type == 'wager') {
			$('.wager-content .match-event-new').css('display', 'none');
			$('.bloc-betting-on .match-event').replaceWith(game.html);
			$('.bloc-betting-on .match-event-medium').removeClass('match-event-medium').addClass('match-event');
			$('.bloc-betting-on .match-event .bloc-event-info-action-wager').replaceWith('<div class="bloc-event-bet"><a target="_blank" rel="nofollow" class="btn-bet-now" href="' + books_url[29] + '"></a></div>');
			$('.calculator-result').css('display', 'block');
			$('.legends-bloc-medium').css('display', 'block');
		}else if(calculator_type == 'parlay') {
			$('.match-event-new').css('display', 'none');
			$('.bloc-add-event').css('display', 'block');
			$('.legends-bloc-large').css('display', 'block');
		}
		
	}, 'json');
	$('.match-event-new').remove('<div class="loading-event"></div>');
}
function delGame(event_id) {
	
	$('#match-event-'+event_id).remove();
	delete bets[event_id];
	$('#link-add-event-'+event_id).css('display', '');
	if(calculator_type == 'parlay') {
		if($('.match-event').length > 1) {
			$('.match-event-new').css('display', 'block');
			$('.bloc-add-event').css('display', 'none');
			
		}
	}
	
}
function updateBet(event_id, type, team, chk_box) {

//	alert($(chk_box).is(':checked'));
	
	if($(chk_box).is(':checked')) {
		// Add the bet
		
		$(chk_box).parent().addClass('selected-checkbox');
		if(bets[event_id] == undefined) {
			bets[event_id] = {};
		}

		// Uncheck other checkbox ...
		var chk_box_id = $(chk_box).attr('id');
		$('.' + $(chk_box).attr('class')).each(function() {
			if($(this).attr('id') != chk_box_id && $(this).is(':checked') == true) {
				$(this).attr('checked', '');
				$(this).parent().removeClass('selected-checkbox');
//				if(bets[event_id] != undefined) {
//					delete bets[event_id][type];
//					if(bets[event_id]['moneylines'] == undefined && bets[event_id]['spreads'] == undefined && bets[event_id]['totals'] == undefined) {
//						delete bets[event_id];
//					}
//				}
			}
		});
		
		bets[event_id][type] = team;

//		alert(type + ' ' + team);

		if(calculator_type == 'wager') {
			$('.no-bet').css('display', 'none');
			$('.one-bet').css('display', 'block');
			$('.bet-on-' + type).css('display', 'block');
//			$('.bloc-bet-compare').css('display', 'none');
			
			wager_amounts[type]['active'] = 1;

			if(type == 'moneylines') {
				$('.bet-on-' + type + ' .team-bet').html(games_data[event_id][team+'_team']);
				$('.bet-on-' + type + ' .odds-bet').html(games_data[event_id]['odds']['moneylines']['odds_'+team]);
			}else if(type == 'spreads') {
				$('.bet-on-' + type + ' .team-bet').html(games_data[event_id][team+'_team'] + ' ' + games_data[event_id]['odds']['spreads']['spreads_'+team]);
				$('.bet-on-' + type + ' .odds-bet').html(games_data[event_id]['odds']['spreads']['odds_'+team]);
			}else if(type == 'totals') {
				$('.bet-on-' + type + ' .team-bet').html(team + ' ' + games_data[event_id]['odds']['totals']['totals']);
				$('.bet-on-' + type + ' .odds-bet').html(games_data[event_id]['odds']['totals']['odds_'+team]);
			}

			// We check the other math block below
			$('.' + $(chk_box).attr('class')).each(function () {
				if($(this).attr('id') == $(chk_box).attr('id')) {
					$(this).attr('checked', 'checked');
					$(this).parent().addClass('selected-checkbox');
				}
			});

//			computeOddsWager();
		}
	}else{
		// Delete the bet
		
		$(chk_box).parent().removeClass('selected-checkbox');
		if(bets[event_id] != undefined) {
			delete bets[event_id][type];
			if(bets[event_id]['moneylines'] == undefined && bets[event_id]['spreads'] == undefined && bets[event_id]['totals'] == undefined) {
				delete bets[event_id];
			}
		}

		if(calculator_type == 'wager') {
			c = 0;
			for(event_id in bets) {
				c++;
			}
			$('.bet-on-' + type).css('display', 'none');
			wager_amounts[type]['active'] = 0;
			if(c == 0) {
				$('.no-bet').css('display', 'block');
				$('bloc-betting-on').css('display', 'none');
//				$('.calculator-result').css('display', 'none');
			}

			// We uncheck the other math block below
			$('.' + $(chk_box).attr('class')).each(function () {
				if($(this).attr('id') == $(chk_box).attr('id')) {
					$(this).attr('checked', '');
					$(this).parent().removeClass('selected-checkbox');
				}
			});
			
			// Hide result box
			$('.bloc-result-wager-' + type).css('display', 'none');

			
		}
	}
}
function computeOddsParlay() {
	var c = 0;
	for(event_id in bets) {
		c++;
	}
	
	if(c == 0) return;
	
	var amount = parseInt($('.amount').val());

	var book_order = [];

	for(book_id in money) {
		var total_odds = 1;
		money[book_id]['valid'] = 1;
		money[book_id]['odds'] = 1;
		money[book_id]['money'] = 0;

		if(book_selected[book_id] != undefined) {
			for(event_id in bets) {
				for(type in bets[event_id]) {
					outcome = bets[event_id][type];
					next_odds = games_data[event_id]['odds'][type]['books'][book_id]['odds_'+outcome+'_dec'];
					if(next_odds > 0) {
						money[book_id]['odds'] = money[book_id]['odds'] * next_odds;
					}else{
						money[book_id]['valid'] = 0;
					}
				}
			}
	
			if(money[book_id]['valid'] == 1) {
				money[book_id]['money'] = amount * money[book_id]['odds'];
				book_order[book_order.length] = {id:book_id, money:money[book_id]['money']};
			}else{
				book_order[book_order.length] = {id:book_id, money:0};
			}
		}
		
	}
	book_order.sort(sortBooks);
	$('.tbl-result-sportsbook tr').remove();
	for(k in book_order) {
		book_id = book_order[k]['id'];
		book_money= book_order[k]['money'];
		k = parseInt(k);
		next_rank = k + 1;
		
		tr = '<tr class="' + (k == 0 ? 'first-result-sportsbook' : '') + '" id="book_' + book_id + '">';
		tr += '<td class="rank-sportsbook">' + next_rank + '.</td>';
		tr += '<td class="logo-sportsbook"><a href="' + books_url[book_id] + '" rel="nofollow" target="_blank"><img src="/medias/css/images/calculator/small-sportsbooks/' + books[book_id]['name_url'] + '.png" /></a></td>';
		tr += '<td class="name-sportsbook"><a href="' + books_url[book_id] + '" rel="nofollow" target="_blank">' + books[book_id]['name'] + '</a></td>';

		if(book_money > 0) {
			infos = '<a href="' + books_url[book_id] + '" rel="nofollow" target="_blank"><span>$ ' + Math.round(book_money) + '</span></a>';
		}else{
			infos = 'Odds may not be available';
		}
		tr += '<td class="winning-sportsbook">' + infos + '</td>';
		tr += '<td class="bet-sportsbook">' + (book_money > 0 ? '<a target="_blank" rel="nofollow" href="' + books_url[book_id] + '" class="' + (k == 0 ? 'btn-bet-now' : '') + '">Bet now</a>' : '') + '</td></tr>';

		$('.tbl-result-sportsbook tbody').append(tr);
	}

	$('.calculator-result').css('display', 'block');
}
function sortBooks(book1, book2){
	if(book1.money > 0 && book2.money > 0) {
		diff = book1.money - book2.money;
	}else if(book1.money > 0) {
		diff = 1;
	}else if(book2.money > 0) {
		diff = -1;
	}else{
		diff = 0;
	}
	diff = diff * -1;
	return diff;
}

function selectBooks(book_id, from) {
	book_id = parseInt(book_id);
	if(book_id == 0) {
		if(is_all_books) {
			$('#book-mask').removeClass('overlay-list-book');
			is_all_books = false;
		}else{
			$('#book-mask').addClass('overlay-list-book');
			is_all_books = true;
		}

		mybooks = [];
		for(next_book_id in books) {
			next_book_id = parseInt(next_book_id);
			book_selected[next_book_id] = 1;
			$('#chk_' + next_book_id).attr('checked', 'checked');
		}
		
		mybooks = [];
		cookie = mybooks.join(',');
		writeCookie('mybooks', cookie, 365);
	}else{
		if($(from).is(':checked')) {
			book_selected[book_id] = 1;
			var i = mybooks.indexOf(book_id);
			if(i == -1) {
				mybooks.push(book_id);
				cookie = mybooks.join(',');
				writeCookie('mybooks', cookie, 365);
			}
//			alert(dump(mybooks));
		}else{
			var i = mybooks.indexOf(book_id);
			if(i != -1) {
				mybooks.splice(i,1);
				cookie = mybooks.join(',');
				writeCookie('mybooks', cookie, 365);			
			}
//			alert(dump(mybooks));
			delete book_selected[book_id];
		}
	}
}

function changeAmountParlay(input) {
	writeCookie('amount_parlay', parseInt($(input).val()), 365);
//	computeOddsParlay();
}

function changeAmount(type, input) {
	wager_amounts[type]['amount'] = parseInt($(input).val());
	
	writeCookie('amount_'+type, wager_amounts[type]['amount'], 365);
//	computeOddsWager();
}

function computeOddsWager() {
	
	var c = 0;
	for(event_id in bets) {
		c++;
	}
	
	if(c == 0) return;
	
	
	$('.bloc-betting-on').css('display', 'block');
	$('.bloc-bet-compare').css('display', 'none');
	
	for(event_id in bets) {
		for(type in bets[event_id]) {
			$('.bloc-' + type + ' .wager-bet-amount strong').html('$' + wager_amounts[type]['amount']);
			book_order = [];
			team = bets[event_id][type];
			
			if(type == 'moneylines') {
				$('.bloc-' + type + ' .wager-team').html('<strong>' + games_data[event_id][team+'_team'] + '</strong> ' + games_data[event_id]['odds']['moneylines']['odds_'+team]);
			}else if(type == 'spreads') {
				$('.bloc-' + type + ' .wager-team').html('<strong>' + games_data[event_id][team+'_team'] + '</strong> ' + games_data[event_id]['odds']['spreads']['spreads_'+team] + ' ' + games_data[event_id]['odds']['spreads']['odds_'+team]);
			}else if(type == 'totals') {
				$('.bloc-' + type + ' .wager-team').html('<strong>' + team + '</strong> ' + games_data[event_id]['odds']['totals']['totals'] + ' ' + games_data[event_id]['odds']['totals']['odds_'+team]);
			}
			
			for(book_id in books) {
				book_id = parseInt(book_id);
				odds = games_data[event_id]['odds'][type]['books'][book_id]['odds_'+team];
				odds_dec = games_data[event_id]['odds'][type]['books'][book_id]['odds_'+team+'_dec'];
				param = '';
				if(type == 'spreads') {
					param = games_data[event_id]['odds'][type]['books'][book_id]['spreads_'+team];
					if(param > 0) {
						param = '+' + param;
					}
				}else if(type == 'totals') {
					param = games_data[event_id]['odds'][type]['books'][book_id]['totals'];
					if(team == 'over') {
						param = 'o' + param;
					}else if(team == 'under') {
						param = 'u' + param;
					}
				}
				if(odds_dec > 0) {
					money[type][book_id]['book_id'] = book_id;
					money[type][book_id]['param'] = param;
					money[type][book_id]['valid'] = 1;
					money[type][book_id]['odds'] = odds;
					money[type][book_id]['odds_dec'] = odds_dec;
					money[type][book_id]['money'] = (odds_dec * wager_amounts[type]['amount']) - wager_amounts[type]['amount'];
				}else{
					money[type][book_id]['valid'] = 0;
					money[type][book_id]['book_id'] = book_id;
				}
				book_order[book_order.length] = money[type][book_id];
			}
			book_order.sort(sortBooks);

			$('ul.bloc-' + type + '-winnings').html('');
			for(k in book_order) {
				winning = book_order[k];
				book = books[winning['book_id']];
				li_class = k == 0 ? 'first' : '';
				li = '<li class="' + li_class + '">';
				li += '<a rel="nofollow" target="_blank" href="' + books_url[winning['book_id']] + '">';
				li += '<img src="/medias/css/images/calculator/small-sportsbooks/' + book['name_url'] + '.png">';
				if(winning.valid == 1) {
					li += '<span class="wager-odds">' + winning['param'] + ' ' + winning['odds'] + '</span>';
					li += '<span class="wager-win">$' + parseInt(winning['money']) + '</span>';
				}else{
					li += '<span class="wager-not-available">Not available</span>';
				}
				li += '</a>';
				li += '</li>';
				$('ul.bloc-' + type + '-winnings').append(li);
			}
			$('.bloc-result-wager-' + type).css('display', 'block');
		}
	}
	
//	$('.bloc-bet-compare').css('display', 'block');
}

/*
 * DISPLAY MANAGEMENT
 */
function closeNavMenu() {
	$('.navigation').css('display','none');
//	$('.parlay_amount').val($('.parlay_amount').val() + 'C ')
//	alert('closing');
}
function see_events_list(element, position) {
	var select_match_box = $('.navigation');
	var main_selector = $('.calculator-content');
	var main_selector_offsets = main_selector.offset();
	var offsets = $(element).offset();
	
	switch(position) {
		case 'left':
			var new_pos_x = offsets.left - main_selector_offsets.left - main_selector_offsets.left;
		break;
		case 'right':
			var new_pos_x = offsets.left - (select_match_box.width() - $(element).width()) - main_selector_offsets.left;
		break;
	}
	var new_pos_y = offsets.top - main_selector_offsets.top + $(element).outerHeight() - 2;
	select_match_box.css('left', new_pos_x+'px').css('top', new_pos_y+'px').css('display', 'block');
}


/*
 * COOKIES
 */
function writeCookie(name,value,expiration) {
	var day = new Date();
	if(expiration == undefined) expiration = 1;
	if(expiration == 'tomorrow') {
		day.setDate(day.getDate()+1);
		day.setHours(0);
		day.setMinutes(0);
		day.setSeconds(0);
	}else{
		day.setTime(day.getTime() + (expiration * 24 * 3600 * 1000));
	}
	
	newcookie = name + "=" + escape(value) + ";expires=" + day.toGMTString() + ";path=/";
	document.cookie = newcookie;
}
function getCookie(name) {
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen){
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return argumentsCookie(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null; 
}
function argumentsCookie(offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr)); 
}


/*
 * HELPERS
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
	
			if(typeof(value) == 'object') { //If it is an array,
					dumped_text += level_padding + "'" + item + "' ...\n";
					dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function showCalculator(type) {

    
	$('#sb-overlay').live('click', function(event) { 
		closeCalculator(type);
	});
	$('#site').after('<div class="sb-container-loading" id="sb-container"><div id="sb-overlay"></div><div style="z-index:100;position:relative;background:url(\'/medias/images/bg-loader.png\') center center no-repeat; width:100%; height:100%;"><div style="z-index:100;position:relative;background:url(\'/medias/css/images/loading/ajax-loader.gif\') center center no-repeat; width:100%; height:100%;">&nbsp;</div></div></div>');

		window.location.replace("#sb-container");	
	
		$.get('/ajax/calculator/'+type, function(data) {
			$('.sb-container-loading').remove();
			$('#site').after(data);
		});

//	}
}

function closeCalculator(type) {

$('div').remove('.sb-container-'+type);
	
}

var is_hover_calculator_btn = false;
var is_hover_calculator_menu = false;

$(window).load(function() {
	
	$('.choose-event-left').live('click', function(event) {
		if($(this).hasClass('btn-change')) {
			replace_event_id = $(this).attr('alt');
		}else{
			replace_event_id = null;
		}
		see_events_list(this, 'left');
		event.stopPropagation();
	});
	$('.choose-event-right').live('click', function(event) { 
	
		if($(this).hasClass('add-event')) {
			$(this).addClass('add-event-active');
		}
		if($(this).hasClass('btn-change')) {
			$(this).addClass('btn-change-active');
		}
		if($(this).hasClass('choose-event')) {
			$(this).addClass('choose-event-active');
		}
		
		if($(this).hasClass('btn-change')) {
			replace_event_id = $(this).attr('alt');
		}else{
			replace_event_id = null;
		}
		see_events_list(this, 'right');
		event.stopPropagation();
	});
	$('.choose-event-left, .choose-event-right').live('mouseenter', function(e) {
		is_hover_calculator_btn = true;
		
	});
	$('.choose-event-left, .choose-event-right').live('mouseleave', function(e) {		
		is_hover_calculator_btn = false;
		
		setTimeout(function() {
			if(!is_hover_calculator_menu) {
				closeNavMenu();
		$('.add-event').removeClass('add-event-active'); 
		$('.btn-change').removeClass('btn-change-active'); 
		$('.choose-event').removeClass('choose-event-active'); 
			}
		},500);
	});
	$('.navigation').live('mouseenter', function(){
		is_hover_calculator_menu = true;
	});
	$('.navigation').live('mouseleave', function(){		
		is_hover_calculator_menu = false;
		closeNavMenu();
		
		$('.add-event').removeClass('add-event-active'); 
		$('.btn-change').removeClass('btn-change-active'); 
		$('.choose-event').removeClass('choose-event-active'); 
		

	
	});
	$('body').live('click', function() {
//		closeNavMenu();
	});
	$('.btn-get-best-payout').live('click', function() {
		computeOddsParlay();
	});
	$('.btn-get-best-payout3').live('click', function() {
		computeOddsWager();
	});

});


