

var BetSlip = function BetSlip() {

	this.logged_in = false;
	this.user_balance = Infinity;
	this.betItems = new Hash;
	this.stake = 5;
	this.slip_state = 'single';
	this.show_banks = false;
	this.system_types = new Hash();
	this.selected_system_type = null;
	this.perms_data= null;
	this.store;
	this.exchange_rate;
	this.user_slip_choice = false;
	this.users_bonus = 0;
	this.userHasActivePlaythrough = -1;// -1 means he doesn't have any playthrough, 0 = has inactive playthrough (but some bonuses), 1=has active plth (with bonuses) - this is set in footer.php

	if(BetSlip.isDomLoaded){
		this.initialize();
	}else{
		Event.observe(document, 'dom:loaded', this.initialize.bind(this), false);
	}

};

BetSlip.isDomLoaded = false;

BetSlip.prototype = {

	initialize: function () {

		var me = this;
		this.loadStore(); //start storage engine

		$$('#bet_type_tabs li a').each(function(a) {
			if(a) {
				Event.observe(a, 'click', function(e) {
					Event.stop(e);
					me.switchSlipState(e.target.id.split("_")[0], false);
				});
			}
		});

		if($('stepper')) {
			Event.observe($('stepper'), 'keydown', function(e) {
				if(me.changeStepperEvent(e)==3) {
					Event.stop(e);
					me.placeCombination();
				}
			});
			Event.observe($('stepper'), 'keyup', function(e) {
				if(me.changeStepperEvent(e)==3) {
				// Event.stop(e);
// me.placeCombination();
				}
			});
			Event.observe($('stepper'), 'blur', function(e) {
				me.changeStepperEvent(e);
			});
		}

		if($('stepper_button_plus')) {
			Event.observe($('stepper_button_plus'), 'click', function(e) {
				Event.stop(e);
				me.changeStepper('up');
			});
		}

		if($('stepper_button_minus')) {
			Event.observe($('stepper_button_minus'), 'click', function(e) {
				Event.stop(e);
				me.changeStepper('down');
			});
		}

		if($('toggle_show_banks')) {
			Event.observe($('toggle_show_banks'), 'click', function(e) {
				Event.stop(e);
				me.toggleShowBanks();
			});
		}

		if($('place_bet_button')) {
			Event.observe($('place_bet_button'), 'click', function(e) {
				Event.stop(e);
				me.placeCombination();
			});
		}


		//this.highlightButtons(s.outcomeId, s.marketId);
		//me.generatePermutations();
		me.highlightAllButtons();
		me.generateBetSlip();
		me.switchSlipState(me.slip_state);

	},

	highlightAllButtons: function () {
		var me = this;
		this.betItems.each( function(pair) {
			var s = pair.value;
			me.highlightButtons(s.outcomeId, s.marketId);
		});
	},

	loadStore: function () {
		var me = this;
		//start storage engine
		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
			Persist.remove('gears');
		this.store = new Persist.Store('BetSlip');

		if(me.getStore('betItems') != null) {
			var bet_string = me.getStore('betItems').toString();
			me.betItems = $H(bet_string.evalJSON());
			me.clearBetSLipOnLoad();
			me.stake = parseFloat(me.getStore('stake'));
			$('stepper').value = me.stake.toFixed(2);
			me.slip_state = me.getStore('slip_state').toString();
			me.show_banks = Boolean(me.getStore('show_banks') == 'true');
			me.selected_system_type = me.getStore('selected_system_type');
			me.user_slip_choice = Boolean(me.getStore('user_slip_choice') == 'true');
		}
	},



	getStore: function (key) {
		var value = null;
		this.store.get(key, function(ok, val) {
			if (ok)
				value = val;
		});
		return value;
	},

	clearBetSLipOnLoad: function () {
		var me = this;
		//store time
		if(me.getStore('time') == null) {
			me.store.set('time', '249');
		} else {
			if(me.getStore('time') != '249') {
				me.betItems.each(function(pair) {
					me.betItems.unset(pair.value.outcomeId);
				});
				console.log('clear betslip');
				me.store.set('time', '249');
			}
		}
	},

	toggleShowBanks: function () {
		var me = this;
		me.show_banks = (me.show_banks)?false:true;
		me.betItems.each(function(pair) {
			me.betItems.get(pair.value.outcomeId).bank = false;
		});
		this.generateBetSlip();		
	},

	totalBetItems: function () {
		var total = 0;
		this.betItems.each(function(pair) {
			total += (pair.value.checked)?1:0;
		});
		return total;
	},

	totalBetBanks: function () {
		var total = 0;
		this.betItems.each(function(pair) {
			total += (pair.value.checked && pair.value.bank)?1:0;
		});
		return total;
	},

	setLoggedIn: function (logged_in) {
		this.logged_in = logged_in;
	},

	setUserBalance: function (user_balance) {
		this.user_balance = user_balance;
		//alert(this.user_balance);
	},

	setExchangeRate: function (exchange_rate) {
		this.exchange_rate = exchange_rate;
	},


	parseBetItemsString: function (bet_item_string) {
		var betItems_Object = bet_item_string.evalJSON(true);
		this.betItems = Object.values(betItems_Object);
	},

	countBetItems: function () {
		return Object.values(this.betItems).size();
	},

	switchSlipState: function (slip_state, auto_selection) {
		console.log("switching from " + this.slip_state + "to " + slip_state);
		if(auto_selection == null)
			auto_selection = true;

		if(!auto_selection)
			this.user_slip_choice = true;

		if($(slip_state + '_bets').hasClassName('disabled'))
			return false;

		this.slip_state = slip_state;
		this.highlightSlipStates();

		$('total_odds_area').style.display  = (slip_state == 'combi')?'block':'none';
		$('show_banks_area').style.display  = (slip_state == 'system')?'block':'none';

		//this.generatePermutations();
		//this.getTotalStakeAndWinnings();

		this.generateBetSlip();
	},

	highlightSlipStates: function () {
		var me = this;

		$$('#bet_type_tabs li a').each(function(s) {
			if(me.slip_state == s.id.split("_")[0])
				s.className = 'current';
			else if( me.totalBetItems() < 2 && s.id.split("_")[0] == 'combi' )
				s.className = 'disabled';
			else if( me.totalBetItems() < 3 && s.id.split("_")[0] == 'system' )
				s.className = 'disabled';
			else
				s.className = '';
		});

	},

	toggleTick: function (outcomeId) {

		this.betItems.get(outcomeId).checked = (this.betItems.get(outcomeId).checked)?false:true;
		this.generateBetSlip();

	},

	toggleBank: function (outcomeId) {

		this.betItems.get(outcomeId).bank = (this.betItems.get(outcomeId).bank)?false:true;
		this.generateBetSlip();

	},


	removeFromSlip: function (outcomeId) {

		this.betItems.unset(outcomeId);
		this.storeBetSlip();
		this.removeHighlight(outcomeId);
		this.generateBetSlip();

	},


	addToSlip: function (outcomeId, eventName, betType, marketId, marketName, odds, eventId, sportId, regionId, leagueId) {

		if(eventName == null) {
			eventName = 'undefined';
		}
		if(betType == null) {
			betType= 'undefined';
		}	
		if(marketId == null) {
			marketId = 'undefined';
		}	
		if(marketName == null) {
			marketName = 'undefined';
		}	
		if(odds == null) {
			odds = 'undefined';
		}

		if(eventId == null) {
			eventId = 'undefined';
		}

		if(sportId == null) {
			sportId = 'undefined';
		}	
		if(regionId == null) {
			regionId = 'undefined';
		}	
		if(leagueId == null) {
			leagueId = 'undefined';
		}

		//if already in betting slip we remove it
		if(this.betItems.get(outcomeId)) {
			this.removeFromSlip(outcomeId);
			this.removeHighlight(outcomeId);
			return;
		}

		var item = new Object();
		item.outcomeId = outcomeId;
		item.eventName = eventName;
		item.eventId = eventId;
		item.betType = betType;
		item.marketId = marketId;
		item.marketName = marketName;
		item.odds = odds;
		item.sportId = sportId;
		item.regionId = regionId;
		item.leagueId = leagueId;
		item.checked = true;
		item.bank = false;		
		this.betItems.set(outcomeId, item);

		this.highlightButtons(outcomeId, marketId);

		//this.betItems[outcomeId] = item;	

		this.generateBetSlip();
	},

	highlightButtons: function (outcomeId, marketId) {
		var types = new Array('dl', 'mf', 'po', 'cl', 'odds');
		//highlight the bet buttons
		types.each(function(t) {
			if($(t+ "-" + outcomeId + "")) {
				//if we already have one in the events then we make it brighter
				var dl_count = 0;
				$$('.bet_type_winner .combibutton.selected a').each(function(s) {
					//foreach rel with the marketId and is selected we must highlight it
					if(s.rel == marketId) {
						s.up('div').addClassName('multiple_selected');
						dl_count++;
					}
				});
				$$('.quick_bet .combibutton.selected a').each(function(s) {
					//foreach rel with the marketId and is selected we must highlight it
					if(s.rel == marketId) {
						s.up('div').addClassName('multiple_selected');
						dl_count++;
					}
				});

				$$('.bet_type_winner .combibutton .multiple_selected a').each(function(s) {
					//console.log(s.rel);
					if(s.rel == marketId) {
						dl_count++;
					}
				});

				if(dl_count > 0) {
					$(t+ "-" + outcomeId + "").addClassName('multiple_selected');
				} else {
					$(t+ "-" + outcomeId + "").addClassName('selected');
				}
			}	
		});	
	},

	removeHighlight: function (outcomeId) {
		var types = new Array('dl', 'mf', 'po', 'cl', 'odds');
		types.each(function(t) {
			if($(t+ "-" + outcomeId + "")) {
				if(	$(t+ "-" + outcomeId + "").hasClassName('multiple_selected') ){
					$(t+ "-" + outcomeId + "").removeClassName('multiple_selected');
					$(t+ "-" + outcomeId + "").removeClassName('selected');
				} else if ($(t+ "-" + outcomeId + "").hasClassName('selected')) {
					$(t+ "-" + outcomeId + "").removeClassName('selected');
				}
			}
		});
	},

	generateBetSlip: function () {
		var me  = this;
		//if no items show the default thing
		if(me.betItems.size() == 0) {
			$('state_empty').style.display = 'block';
			$('state_combi').style.display = 'none';
			return;
		} else {
			$('state_empty').style.display = 'none';
			$('state_combi').style.display = 'block';
		}

		console.log(this.slip_state);
		if( this.totalBetItems() < 3 && this.slip_state == 'system' ) {
			this.switchSlipState('combi');
		} else if( this.totalBetItems() < 2 && this.slip_state == 'combi' ) {
			this.switchSlipState('single');
		}

		//if we have 2 single bets and user has not switched state we move to combi bet
		/*
&& this.user_slip_choice == false
		*/
console.log("total" + this.totalBetItems());
		if( this.totalBetItems() >= 2 && this.slip_state == 'single' && this.user_slip_choice == false) {
			this.switchSlipState('combi');
		}

		var top_element = bottom_element = li = null;
		$('bet_slip_items').update();
		this.betItems.each(function(pair) {
			s = pair.value;
			var checked = (s.checked)?'checked':'unchecked';
			top_element = Builder.node('div', {  }, [
			  Builder.node('a',{ className: 'bet_selector ' + checked, href: '#', onclick: 'bet_slip.toggleTick('+s.outcomeId+'); return false;' }),
			  Builder.node('span', { className: 'bet_tip_title' }, s.eventName + ' (' + s.betType + ')' ),
			  Builder.node('a', { className: 'bet_tip_remove',  onclick: 'bet_slip.removeFromSlip('+s.outcomeId+')' }, "")
			]);

			var bankClass = (s.bank)?'active':'inactive';

			bankClass = (me.show_banks && me.slip_state == 'system')?bankClass:'';
			bottom_element = Builder.node('div', {  }, [
			  Builder.node('a',{ className: 'bank '+bankClass+'', href: '#', onclick: 'bet_slip.toggleBank('+s.outcomeId+'); return false;'}),
			  Builder.node('span', { className: 'bet_tip_market' }, s.marketName + " (" + s.odds + ")" )
			]);

			li = Builder.node('li', { className: 'bet_tip' }, [
				top_element, bottom_element
			]);

			$('bet_slip_items').appendChild(li);
		});

		//check total odds
		var total_odds = this.getTotalOdds();


		this.generatePermutations();
		this.getTotalStakeAndWinnings();
		this.highlightSlipStates();
	},

	generatePermutations: function () {
		//show only if system bet
		if(this.slip_state != 'system') {
			$('bet_slip_permutations').update();
			$('bet_slip_permutations').hide();
			return false;
		} else {
			$('bet_slip_permutations').show();
		}

		//get how many bets we have
		$('bet_slip_permutations').update('');
		this.perms_data = this.getAllPermutations();
		var perms = Object.values(this.perms_data.get('perms'));
		if(this.totalBetItems() - this.totalBetBanks() == 1) {
			this.removeAllBanks();
			//console.log('switching to combi');
			this.switchSlipState('combi');
			//remove all banks
			return false;
		}

		if(this.selected_system_type != null && !this.validSystemType(this.selected_system_type))
			this.selected_system_type = null;

		for(i = 0; i < this.perms_data.get('total_perms'); i++) {
			if(perms[i].size() <= 1)
				continue;
			var perm_array = new Array( perms[i][0].size(), this.totalBetItems(), perms[i].size() );
			if(this.selected_system_type == null ) //if is null or not valid we use the next one
				this.selected_system_type = perm_array;

			var system_type_name = sprintf( "System %0d/%1d (%2d Bets)", perms[i][0].size(), this.totalBetItems(), perms[i].size() );
			var total_banks = this.totalBetBanks();
			if(total_banks > 0)
				system_type_name = sprintf( "System %0d/%1d - %2d Banks (%3d Bets)", perms[i][0].size(), this.totalBetItems(), this.totalBetBanks(), perms[i].size() );

			var li = Builder.node('li', {  }, [
				Builder.node('input',{ type: "radio", name: 'systemTypes', className: 'radioChoice', value: perms[i][0].size(), onclick: 'bet_slip.setSystemType( '+perms[i][0].size()+', '+this.totalBetItems()+', ' + perms[i].size() + ')', id: 'systemTypeCheck_' + perm_array.toString() }),
				Builder.node('span', { }, system_type_name )
			]);
			$('bet_slip_permutations').appendChild(li);
		}

		if($('systemTypeCheck_' + this.selected_system_type.toString()))
			$('systemTypeCheck_' + this.selected_system_type.toString()).checked = 'checked';

		//get total winnings foreach of the odds we need to display


	},

	validSystemType: function (selected_system_type) {
		var matches = 0;
		var perms = Object.values(this.perms_data.get('perms'));
		for(i = 0; i < this.perms_data.get('total_perms'); i++) {
			var perm_array = new Array( perms[i][0].size(), this.totalBetItems(), perms[i].size() );
			if( this.selected_system_type.toString() == perm_array.toString())
				matches++;
		}
		return (matches > 0);

	},

	setSystemType: function (tips_required, num_system_bets, num_bets) {
		this.selected_system_type = new Array(tips_required, num_system_bets, num_bets);
		this.getTotalStakeAndWinnings();
	},

	getTotalOdds: function () {
		var total_odds = 1;
		this.betItems.each(function(pair) {
			s = pair.value;
			total_odds *= parseFloat(s.odds);
		});
		$('total_odds').update(total_odds.toFixed(2));
		return total_odds;
	},

	getTotalStakeAndWinnings: function () {
		var me = this;
		var user_stake = parseFloat($('stepper').value);
		var max_profit = 0;
		var total_stake = 0;

		if( me.slip_state == 'combi' ) {

			var total_odds = 1;
			this.betItems.each(function(pair) {
				s = pair.value;
				if(s.checked)
					total_odds *= parseFloat(s.odds);
			});
			total_stake = user_stake;
			max_profit = user_stake * total_odds;
		} else if(me.slip_state == 'single') {

			total_stake = user_stake * me.totalBetItems();
			var total_odds = 0;
			this.betItems.each(function(pair) {
				s = pair.value;
				if(s.checked)
					max_profit += user_stake * parseFloat(s.odds);
			});

		} else if(me.slip_state == 'system') {
			$('toggle_show_banks').className = (this.show_banks)?'show_banks checked':'show_banks unchecked';


			//me.perms_data = me.getAllPermutations();

			var perms = Object.values(me.perms_data.get('perms'));

			//check selected perm
			var selected_index = 0;
			perms.each(function(perm, index) {
				var perm_array = new Array( perm[0].size(), me.totalBetItems(), perm.size() );
				if(me.selected_system_type.toString() == perm_array.toString()) {
					selected_index = index;
				}
			});

			var max_profit = 0;
			perms[selected_index].each(function(combi) {
				var combi_winnings = 1;
				combi.each(function(outcome) {
					combi_winnings *= me.betItems.get(outcome).odds;
				});
				max_profit += combi_winnings*user_stake;
			});

			//we update the stake here cheaper
			total_stake = user_stake * perms[selected_index].size();
		}

		if(me.canBet())
			$('bet_slip_place_bet').className = '';
		else
			$('bet_slip_place_bet').className = 'disabled';

		$('total_stake').update(total_stake.toFixed(2));
		$('max_profit').update(max_profit.toFixed(2));
		me.storeBetSlip();
	},

	changeStepperEvent: function (e) {

		var keyCode = e.charCode || e.keyCode;

		if(keyCode == 37 || keyCode==39 || keyCode==0 || keyCode==13);
		else if(keyCode == 38)
			this.changeStepper( 'up' );
		else if(keyCode == 40)
			this.changeStepper( 'down' );
		else {
		if( (keyCode>47 && keyCode<58) || (keyCode>95 && keyCode<106) || keyCode==110)
		{
		var sval = $('stepper').value;

			if(sval.length>0) {
			if(e.type == 'blur') {
				$('stepper').value = parseFloat($('stepper').value).toFixed(2);
			}
			if(isNaN(parseFloat($('stepper').value)))
				$('stepper').value = parseFloat(0).toFixed(2);

			this.store.set('stake', $('stepper').value);
			this.changeStepper( $('stepper').value );
			}

		} else { 
		if(keyCode>46) {
		//alert(keyCode);
		$('stepper').value = $('stepper').value.replace(/[^0-9.]/g, ""); 
		}
		}
		}


		if(keyCode==13) return 3;


	},


	changeStepper: function (value) {

		var stepper_value = parseFloat($('stepper').value); //get stepper value
		if (stepper_value) {

			//adjust value based on number range
			var diff = 1;
			if (stepper_value >= 10001) diff = 1000;
			else if (stepper_value >= 1001) diff = 100;
			else if (stepper_value >= 101) diff = 10;
			else if (stepper_value > 1.5) diff = 1;
			else if (stepper_value > 0.95) diff = 0.5;
			else if (stepper_value >= 0.25) diff = 0.05;
			if(value == 'down') {
				var newStake = stepper_value-diff;
			} else if (value == 'up') {
				var newStake = stepper_value+diff;
			} else {
				var newStake = parseFloat(stepper_value);
				//console.log(newStake);
			}

			if (newStake < 0.25) {
				return false; //dont change anything
			}

			/*Removed this condition: see bug 2008 from GIMO*/
			/*
			if (newStake > this.user_balance) {
				var newStake = this.user_balance;
				$('stepper').value = this.user_balance + "";
				//return false; //dont change anything
			}
			*/

			if(value == 'down' || value == 'up') {
				//console.log(this);
				$('stepper').value = newStake.toFixed(2);
				this.store.set('stake', $('stepper').value);
			}

		}		



		this.getTotalStakeAndWinnings();

	},

	/*
		this is only for system bets
		generates all possible system types for each bet
		SLOW use only once	
	*/
	getAllPermutations: function () {
		var me = this;
		var num_in = new Array();
		this.betItems.each(function(pair) {
			s = pair.value;
			if(s.checked)
				num_in.push(s.outcomeId);
		});

		var perms = this.getPermutations(num_in);
		//console.log(perms);
		//now we filter out the bankers
		var total_banks = this.totalBetBanks();
		if(total_banks > 0) {

			var bank_perms = new Object();		
			var perms_keys = Object.keys( perms);
			var bank_outcomes = new Array();//get all bank outcomeIds
			this.betItems.each(function(pair) {
				if(pair.value.checked && pair.value.bank)
					bank_outcomes.push(pair.value.outcomeId);
			});

			perms_keys.each(function(key) {
				//build new perms
				//if outcome id is in perm array then we keep the perm
				//bank_perms[key] = new Array();
				var temp_perms = me.filterPerms(perms[key], bank_outcomes);
				if(temp_perms.size() > 0)
					bank_perms[key] = temp_perms;				
			});
			//console.log(bank_perms);
			perms = bank_perms;

		}


		//count how many possible
		var result = new Hash();
		result.set('total_perms', Object.values(perms).size()); //count how many possible
		result.set('perms', perms); //return array of possibilities

		//return array of possibilities
		return result;
	},


	filterPerms: function (perms, bank_outcomes) {
		var bank_perms = new Array();

		perms.each(function(perm) {
			var count = 0;
			bank_outcomes.each(function(bank_outcomeId) {
				if(perm.inArray(bank_outcomeId)) { //if all are found
					count++;
				}
			});

			if(count == bank_outcomes.length)
				bank_perms.push(perm);
		});

		return (bank_perms);
	},

	getPermutations: function (num_in) {
		var count = num_in.size();
		var members = Math.pow(2, count);
		var output = new Array();
		for (var i = 0; i < members; i++) {

			var binary = sprintf("%0"+count+"b", i);
			var out = new Array();

			for (var j = 0; j < count; j++)
				if (binary.charAt(j) == '1') out.push(num_in[j]);

			if (out.size() >= 2)
				output.push(out);

		}

		var max_size = 0;
		output.each(function(o) {
			max_size = (o.size() > max_size)?o.size():max_size;
		});

		var perms = new Object();
		for(var i = 2; i < max_size; i++) {
			perms[i] = new Array();
			output.each(function(o) {
				if(o.size() == i) {
					perms[i].push(o);
				}
			});
		}

		return perms;
	},

	//now we must store the bet slip
	storeBetSlip: function () {
		this.store.set('betItems', this.betItems.toJSON());
		this.store.set('stake', this.stake);
		this.store.set('slip_state', this.slip_state);
		this.store.set('show_banks', this.show_banks);
		this.store.set('user_slip_choice', this.user_slip_choice);

		if( this.selected_system_type instanceof Object )
			this.store.set('selected_system_type', this.selected_system_type);

	},


	canBet: function () {

		if(this.totalBetItems() == 0)
			return false;

		if(isNaN(parseFloat($('stepper').value)))
			return false;

		if((parseFloat($('stepper').value)) < 0.25)
			return false;

		if((parseFloat($('stepper').value)) > this.user_balance)
			return false;

		return true;
	},

	//finally place combination


	placeCombination: function () {

		document.getElementById('place_bet_button').disabled = true; //disable the button so that the user can't click more than once
		var me = this;
		this.stake = parseFloat($('stepper').value);

		//only proceed if the thing is not disabled
		if($('bet_slip_place_bet').className == 'disabled')
			return;

		if(!this.logged_in) {
			showLoginBox();
			return;
		}

		if(this.user_balance < this.stake && this.users_bonus!=stake) {
			error("Insufficient Funds", "Sorry you do not have enough money to make this bet");
			return;
		}

		if(this.userHasActivePlaythrough==0 && this.checkOddsHigherThan(2.5)==false ){//if the user has active plth, but the odds are lower than 2.5, don't allow to place bet
			if(!confirm('YOU WILL LOSE YOUR BONUS IF YOU BET ON ODDS UNDER 2.5')) return;
		}

		if(this.userHasActivePlaythrough==1 && this.checkOddsHigherThan(2.5)==false ){//if the user does not have plth, but has some bonuses due to plth, if the bets are with odds<2.5, ask the user as he will loose the bonus
			error('Error','Sorry, odds under 2.5 are not accepted');
			return;
		}

		createProcessing("One moment please....")

		//we send all betItems as json, others normally
		var url = site_url('MyBet/ajax_placeCombination/');
		var system_bets = (this.slip_state == 'system') ? this.selected_system_type.toString().charAt(0) : 0;

		//if single bet send as system bet 1 / total
		if (this.slip_state == 'single' && me.totalBetItems() > 1) {
			system_bets = 1;
		} else if (this.slip_state == 'single' && me.totalBetItems() == 1) {
			system_bets = 0;
		}

		new Ajax.Request(url, {
			method: 'post', parameters: {
				betItems: this.betItems.toJSON(),
				stake: this.stake,
				system_bets: system_bets
			},
			onComplete:function(text){
				document.getElementById('place_bet_button').disabled = false;
				removeModal();
				var data = text.responseText.evalJSON();
				if(data['result'] == false) {
					if(data['error'] == 'not_logged') {
						showLoginBox();
						return;
					}else if(data['error'] == 'not_allowed') {
						error("Permission denied", "Sorry you this username has not been validated.");
					}else if(data['error'] == 'invalid_playthrough') {
						error("Error", "Sorry, odds under 2.5 are not accepted");
					}else if(data['error'] == 'insufficient_funds') {
						//error("Insufficient Funds", data['response']);
						error("Insufficient funds", "Sorry you have insufficient funds");	
					}else if(data['error'] == 'limit_exceeded') {
						error("Limit exceeded", "You have exceeded the limits that you have set upon yourself");
					} else if (data['error'] == 'combi_error') {
						
						error("ERROR", data['response']);
						
					} else {
						error("ERROR", data['response'].errors[0].message);
					}
				}
				if(data['result'] == true) {
					if(data['response'].errors != null) {
					    error("ERROR", data['response'].errors[0].message);
					} else {
						var open_bets = parseInt($('open_bets').innerHTML);
						$('open_bets').update(open_bets + 1);
						success("Bet placed", sprintf("Congratulations, Your bet has successfully been placed!<br />If you would like to see a popup of your betting receipt please <a href='#' onclick='printReceipt(%s); return false;' style='text-decoration: underline'>click here</a>", data['response']['combination']['systemId']), data['response']['combination']['systemId']);
console.log(data['response']['combination']['systemId']);
						var balance_array = $('balance').innerHTML.split(' ');
						if(me.IsNumeric(balance_array[0])) {
							var balance = parseFloat(balance_array[0]) - (data['response']['combination']['stake']/me.exchange_rate + data['bonus_lost']/me.exchange_rate);
							var currency = balance_array[1];
							$('balance').update(balance.toFixed(2) + ' ' + currency);
						} else if(me.IsNumeric(balance_array[1])) {
							var balance = parseFloat(balance_array[1]) - (data['response']['combination']['stake']*me.exchange_rate + data['bonus_lost']*me.exchange_rate);
							var currency = balance_array[0];
							$('balance').update(currency + ' ' + balance.toFixed(2));
						}
						/*var balance = parseFloat(balance_array[0]) - data['response']['combination']['stake'] - data['bonus_lost'];
						var currency = balance_array[1];
						$('balance').update(balance.toFixed(2) + ' ' + currency);*/
						me.removeSelectedBetItems();
						setTimeout("removeModal();", 30000);
					}
				}
			}
		});
		setTimeout('bet_slip.ReEnableBetPlaceButton()',1000);
	},

	ReEnableBetPlaceButton: function () {
		document.getElementById('place_bet_button').disabled = false;
	},

	checkOddsHigherThan: function (minOdds) {
		var me = this;
		var result = true;
		this.betItems.each(function(pair) {
			if (pair.value.odds < minOdds) result = false;
		});
		return result;
	},

	removeSelectedBetItems: function () {
		var me = this;
		this.betItems.each(function(pair) {
			if(pair.value.checked) {
				me.betItems.unset(pair.value.outcomeId);
				me.removeHighlight(pair.value.outcomeId);
			} else {
				me.betItems.get(pair.value.outcomeId).checked = true;
			}
		});
		me.storeBetSlip();
		me.generateBetSlip();
	},

	removeAllBanks: function () {
		var me = this;
		this.betItems.each(function(pair) {
			pair.value.bank = false;
		});
	},

	IsNumeric: function (sText) {
		var ValidChars = "0123456789.";
		var IsNumber=true;
		var Char;

		for (i = 0; i < sText.length && IsNumber == true; i++) {
			Char = sText.charAt(i);
			if (ValidChars.indexOf(Char) == -1)
				IsNumber = false;
      		}
		return IsNumber;
	}


};


Event.observe(document, 'dom:loaded', function(){ BetSlip.isDomLoaded = true; }, false);


Array.prototype.inArray = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}
