var DEFAULT_MARKET_INDEX = -1;    
/*
*	UI Controller, the root of all evil
*/
function controllers_UIController(){
	this.market = null;
	this.user = null;
	this.marketHasLoaded = null;
	this.myBetsHaveLoaded = null;
	this.marketUpdateTimeout = null;
	this.myBetsUpdateTimeout = null;
	this.myBetsRefreshHasStarted = false;
	this.currentTimeOut = controllers_MARKETVIEW_REFRESH_TIMEOUT;
	this.currentMyBetsTimeOut = controllers_MYBETS_REFRESH_TIMEOUT;
	this.oPAndLAnnotations = null;
	this.currentlySelectedCouponMarketId = null;
	this.groupCommissionText = null;
	this.userController = new controllers_User();
	this.marketViewController = new controllers_MarketViewController();
	this.betManagerController = new controllers_BetManagerController(this.marketViewController);
	this.profitAndLossController = new controllers_ProfitAndLossController();
	this.panelManagerController = new controllers_PanelManagerController();
	this.multiplesHelperController = new controller_MultiplesHelperController();	
	this.placeBetPreConditon = true;
	this.autoRefreshFlag = true;		
}

;controllers_UIController.prototype.marketDoesNotExist = function(){
    this.splashTempMarket(false);
}

;controllers_UIController.prototype.splashTempMarket = function(exchangeUnavailable, exchangeId) {
    this.betManagerController.resetMarket();
	this.currentlySelectedCouponMarketId = null;

	var tempMarket = new models_Market();
	tempMarket.marketId = null;
	tempMarket.name = '';
	
	var oMarketInformation = new models_Information();
	oMarketInformation.information = '';
	oMarketInformation.matchedSoFar = '';
	tempMarket.information = oMarketInformation;
	
	tempMarket.eventTypeId = null;
	tempMarket.betType = 'Odds';
	tempMarket.isSuspended = false;
	tempMarket.numberOfWinners = 0;
	tempMarket.eventId = null;
	
	tempMarket.isClosed = !exchangeUnavailable;
	tempMarket.exchangeUnavailable = exchangeUnavailable;
	tempMarket.runners = new models_Runners();
	tempMarket.bets = new models_Bets();
 
    if (exchangeId) {
        tempMarket.exchangeID = exchangeId;
    }
	var oCouponParentLinks = new models_CouponMarketLinks();
	this.marketViewController.setCouponParentLinks(oCouponParentLinks);
	this.setMarket(tempMarket);
	this.betManagerController.myBetsController.myBetsView.setState(controllers_MY_BETS_DEFAULT_VIEW);
	this.betManagerController.placeBetsController.placeBetsView.setState(controllers_PLACE_BETS_DEFAULT_VIEW);
}

;controllers_UIController.prototype.couponDoesNotExist = function(){
	var tempMarket = new models_Market();
	tempMarket.marketId = null;
	tempMarket.name = '';
	
	var oMarketInformation = new models_Information();
	oMarketInformation.information = '';
	oMarketInformation.matchedSoFar = '';
	tempMarket.information = oMarketInformation;
	
	tempMarket.eventTypeId = null;
	tempMarket.betType = 'Odds';
	tempMarket.isSuspended = false;
	tempMarket.numberOfWinners = 0;
	tempMarket.eventId = null;
	tempMarket.isClosed = true;
	tempMarket.runners = new models_Runners();
	var oCouponParentLinks = new models_CouponMarketLinks();
	this.marketViewController.setCouponParentLinks(oCouponParentLinks);
	this.setMarket(tempMarket);
	this.betManagerController.myBetsController.myBetsView.setState(controllers_MY_BETS_DEFAULT_VIEW);
	this.betManagerController.placeBetsController.placeBetsView.setState(controllers_PLACE_BETS_DEFAULT_VIEW);
	document.getElementById("MVFooter").innerHTML = "";
}

;controllers_UIController.prototype.setMarket = function(market){
	if(market instanceof models_Coupon){
		if(this.market instanceof models_Coupon){
			if ((this.market.id != market.id) || (this.market.id == market.id && !this.compareCouponMarkets(this.market,market))){
				betexJITController.updateHelpStructure(market, this.user);
				this.currentlySelectedCouponMarketId = null;
				this.panelManagerController.restorePanels();
				this.interruptRequests();
				this.currentMyBetsTimeOut = controllers_MYBETS_REFRESH_TIMEOUT;
			}
		}else{
			betexJITController.updateHelpStructure(market, this.user);
			this.currentlySelectedCouponMarketId = null;
			this.panelManagerController.restorePanels();			
			if(parent.frames['menu'].frames['multiplesTreeContainer']){
				if(parent.frames['menu'].frames['multiplesTreeContainer'].goMenu){
					parent.frames['menu'].frames['multiplesTreeContainer'].goMenu('',market.id,market.groupId);
				}
			}			
		}		
	}else{
		this.currentlySelectedCouponMarketId = null;
		if (this.market instanceof models_Coupon) {
			if (this.market.id != market.id) {
				betexJITController.updateHelpStructure(market, this.user);
				this.panelManagerController.restorePanels();				
				if(parent.frames['menu'].frames['multiplesTreeContainer']){
					if(parent.frames['menu'].frames['multiplesTreeContainer'].goMenu){
						parent.frames['menu'].frames['multiplesTreeContainer'].goMenu(market.eventId,market.marketId,market.groupId);
					}
				}				
				this.interruptRequests();
				this.currentMyBetsTimeOut = controllers_MYBETS_REFRESH_TIMEOUT;
			}
		}else if(this.market != null && this.market.marketId != market.marketId){
			betexJITController.updateHelpStructure(market, this.user);
			this.panelManagerController.restorePanels();
			if(parent.frames['menu'].frames['multiplesTreeContainer']){
				if(parent.frames['menu'].frames['multiplesTreeContainer'].goMenu){
					parent.frames['menu'].frames['multiplesTreeContainer'].goMenu(market.eventId,market.marketId,market.groupId);
				}
			}
			this.interruptRequests();
			this.currentMyBetsTimeOut = controllers_MYBETS_REFRESH_TIMEOUT;
		}else if(this.market == null){			
			betexJITController.updateHelpStructure(market, this.user);
			this.currentMyBetsTimeOut = controllers_MYBETS_REFRESH_TIMEOUT;
			if(parent.frames['menu'].frames['multiplesTreeContainer']){
				if(parent.frames['menu'].frames['multiplesTreeContainer'].goMenu){
					parent.frames['menu'].frames['multiplesTreeContainer'].goMenu(market.eventId,market.marketId,market.groupId);
				}
			}
		}
	}
	
	this.market = market;	
	if(this.currentlySelectedCouponMarketId != null){
		if(!this.market.getCouponMarketByMarketId(this.currentlySelectedCouponMarketId)) {
			this.setActiveCouponMarket(market.markets.get(0).marketId);
		}
	}		
	this.panelManagerController.setMarket(this.market);	
	this.marketViewController.setMarket(this.market);	
	this.betManagerController.setMarket(this.market);
	this.userController.setMarket(this.market);
	this.profitAndLossController.setMarket(this.market);	
	if(market instanceof models_Coupon){
		if(this.currentlySelectedCouponMarketId == null){
			this.setActiveCouponMarket(market.markets.get(0).marketId);
		}
	}else{
		this.currentlySelectedCouponMarketId = null;
		if (market.betType == "Range" || market.betType == "Line") {
			interface_updatePreferences(document.getElementById('exchangeUIView'), null, true);
		} 
	}

	/* This is only here because of the Range and Line markets. If you view a Range or
   	   Line market and then view another market, nothing has been changed so the view
	   remains Exchange. This check only sees if it needs to update things if the 
	   cookie value is COMPACT and if it is showing the EXCHANGE view where it should be 
	   showing the COMPACT view based on the user settings */
	if (GetCookie(constants_MULTIPLES_UI_VIEW_COOKIE) == constants_UI_VIEW_COMPACT) {
		if (document.getElementById("MVHeaderUIViewCompactLink").style.display != "none") {
			interface_updatePreferences(document.getElementById('compactUIView'));
		}
	}
	this.marketHasLoaded = true;
	
	if (this.market != null) {
		for (var runnersCtr=0; runnersCtr < this.betManagerController.placeBetsController.bets.length(); runnersCtr++){
	    	currentRunner = this.betManagerController.placeBetsController.bets.items[runnersCtr];

	    	// Checking in the above collection if the current bet item market id and currently viewed market ids are the same
	    	if (currentRunner.marketId == this.market.marketId) {
	    	 	if (currentRunner.bidType == models_BidType.BACK){
					for (var backCtr=0; backCtr < this.market.runners.length(); backCtr++){
						document.getElementById("OddsMVLayButton_" + this.market.runners.items[backCtr].runnerId).style.visibility = 'hidden';
						document.getElementById("MVLayButton_" + this.market.runners.items[backCtr].runnerId).disabled = true;
					}
				} else {
					for (var layCtr=0; layCtr < this.market.runners.length(); layCtr++){
						document.getElementById("OddsMVBackButton_" + this.market.runners.items[layCtr].runnerId).style.visibility = 'hidden';
						document.getElementById("MVBackButton_" + this.market.runners.items[layCtr].runnerId).disabled = true;
					}
				}
				break;
			}
	    }
	}
}
;controllers_UIController.prototype.createLegs = function(runner,bidType){
	if (bidType == models_BidType.BACK) {
		parent.frames['main'].interface_placeBet(this.market, runner, 2, models_BidType.BACK, "MVBackButton_"+runner);	
	} else {
		parent.frames['main'].interface_placeBet(this.market, runner, 3, models_BidType.LAY, "MVLayButton_"+runner);	
	}
}

;controllers_UIController.prototype.refreshCurry = function() {
	if (this.market) {
		if (this.market instanceof models_Coupon) {
			parent.frames['main'].location = "/multiples/betting/MarketView.do?ci=" + this.market.id;
		} else {
			parent.frames['main'].location = "/multiples/betting/MarketView.do?mi=" + this.market.marketId + "&groupId="+ this.market.groupId;
		}
	}
}

;controllers_UIController.prototype.compareCouponMarkets = function(market,newMarket) {
	if (market.markets && newMarket.markets) {
		if (market.markets.length() == newMarket.markets.length()) {
			for (var iCount=0;iCount<market.markets.length();iCount++){
				if (!this.compareCouponObjects(market.markets.get(iCount), newMarket.markets.get(iCount))) {
					return false;
				}
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
	return true;
}

;controllers_UIController.prototype.compareCouponObjects = function(newObject, oldObject) {
	var newObjectClone = new cloneObject(newObject, true);
	newObjectClone.isActivelyTagged = "doNotCompare";
	newObjectClone.isSuspended = "doNotCompare";
	newObjectClone.hasBets = "doNotCompare";
	newObjectClone.homeScore = "doNotCompare";
	newObjectClone.awayScore = "doNotCompare";
	newObjectClone.enhanced = "doNotCompare";
	for (var iCount=0;iCount<newObjectClone.runners.length();iCount++){
		newObjectClone.runners.get(iCount).isActivelyTagged = "doNotCompare";
	}
	for (var iCount in newObjectClone) {
		if (typeof newObjectClone[iCount] != 'object') {
			if (newObjectClone[iCount] != oldObject[iCount] && newObjectClone[iCount] != "doNotCompare") {
				return false;
			}
		}
	}
	return true;
}

;controllers_UIController.prototype.interruptRequests = function(){
	try{
		window.frames['myBetsManager'].location.replace("/multiples/blank.jsp");
		window.frames['placeBetsManager'].location.replace("/multiples/blank.jsp");
	}catch(x){
		try{
			window.frames['myBetsManager'].location.href = "/multiples/blank.jsp";
			window.frames['placeBetsManager'].location.href = "/multiples/blank.jsp";
		}catch(x){
			
		}
	}
	this.myBetsRefreshHasStarted = false;
}

;controllers_UIController.prototype.setUserPreferences = function(user){	
	this.user = user;	
	this.userController.setUser(user);	
	this.marketViewController.setUserPreferences(user);	
	this.betManagerController.setUserPreferences(user);	
	if(this.marketHasLoaded) {
		this.refreshMarket(true);		
		if(this.market instanceof models_Coupon){
			this.interruptRequests();
		}		
	}
}

;controllers_UIController.prototype.setUserPreferencesWithTermsAndCondtions = function(user){		
	this.user = user;
	var url = MultiplesDomain + 'account/termsandconditions/MultiplesTermsAndConditionsLoader.do';
	frames['termsAndConditionsManager'].location = url;	
}

;controllers_UIController.prototype.getUserPreferences = function(){		
	 return new cloneObject(this.user);
}

;controllers_UIController.prototype.updateUserPreferencesFromCookieValues = function(user){	
	var pFrame = parent.frames['header'];
	var sShowHelpCookieValue = GetCookie(constants_SHOW_HELP_COOKIE);
	var sUIViewCookieValue = GetCookie(constants_MULTIPLES_UI_VIEW_COOKIE);
	
	if(sShowHelpCookieValue != null && sShowHelpCookieValue != ""){		
		if (pFrame && pFrame.bHeaderLoaded && pFrame.oUser) {			
			if (sShowHelpCookieValue == "true") {
				pFrame.oUser.preferences.showHelp = true;
			} else {
				pFrame.oUser.preferences.showHelp = false;
			}		
		} 				
		if (sShowHelpCookieValue == "true") {
			user.preferences.showHelp =true;
		} else {
			user.preferences.showHelp =false;
		}
	}
	
	if(sUIViewCookieValue != null && sUIViewCookieValue != ""){	
		if (pFrame && pFrame.bHeaderLoaded && pFrame.oUser) {	
			if (pFrame.oUser.preferences.multiplesUIView != sUIViewCookieValue) {
				pFrame.oUser.preferences.multiplesUIView = sUIViewCookieValue;
			} 		
		} 				
		if (user.preferences.multiplesUIView != sUIViewCookieValue) {
			user.preferences.multiplesUIView = sUIViewCookieValue;
		}
	}
	return user;
}

;controllers_UIController.prototype.getMarketData = function(marketId, origin, groupId, accountId,deepString){
	if(deepString == null){
		deepString = '';
	}
	var target = (marketId.indexOf('ci=') >= 0)? '/multiples/betting/LoadCouponDataAction.do?' : '/multiples/betting/LoadMarketDataAction.do?';	
	var linkOrigin = '&origin='+origin;
	var linkGroupId = '&groupId='+groupId;
	var linkAccountId = '&accountId='+accountId;
	var linkDeepString = '&deep='+deepString;
	window.frames['predictionManager'].location = target+marketId+linkOrigin+linkGroupId+linkAccountId+linkDeepString;

	this.marketHasLoaded = false; 
	this.myBetsHaveLoaded = false;
	this.showLoading();

	clearTimeout(this.marketUpdateTimeout);
	clearTimeout(this.myBetsUpdateTimeout);

	this.currentTimeOut = controllers_MARKETVIEW_REFRESH_TIMEOUT;
	clearTimeout(this.marketUpdateTimeout);
	this.marketUpdateTimeout = setTimeout("interface_startMarketRefresh()", controllers_MARKETVIEW_REFRESH_TIMEOUT);
	
	var oController = this.betManagerController.placeBetsController;

	if(this.betManagerController.activeTab == controllers_PLACE_MYBETS_TAB)
	{
		this.betManagerController.placeBetsController.placeBetsView.setState(controllers_PLACE_BETS_PLACEBETS_VIEW);
		this.betManagerController.setActiveTab(controllers_PLACE_BETS_TAB);
	}
}

;controllers_UIController.prototype.showLoading = function(){
	document.getElementById("MVContentSuspendInfo").style.display = "none";
	document.getElementById("MVContentLoadingInfo").style.display = "block";
}

function HideAllOtherBetType(market, oddsPrefix ,buttonsPrefix) {
	for (var iCtr=0; iCtr < market.runners.length(); iCtr++)
	{
		document.getElementById(oddsPrefix + market.runners[iCtr].runnerId).style.visibility = 'hidden';
		document.getElementById(buttonsPrefix + market.runners[iCtr].runnerId).disabled = true;
	}
}

;controllers_UIController.prototype.refreshMarket = function(userAction, forceMarketInterimRefresh){		
	if (!this.market) return;	
	var target = MultiplesDomain + ((this.market instanceof models_Coupon)? 'betting/LoadCouponDataAction.do?ci='+this.market.id+'&groupId='+this.market.groupId : 'betting/LoadMarketDataAction.do?mi='+this.market.marketId+'&groupId='+this.market.groupId);
	try{
		if(this.market instanceof models_Coupon){			
			window.frames['predictionManager'].document.location.replace(target);
		}else{			
			if(!this.market.isClosed){						
				window.frames['predictionManager'].document.location.replace(target);				
			}
		}
	}catch(x){
		if(window.frames['predictionManager'] && window.frames['predictionManager'].document){				
			window.frames['predictionManager'].document.location.replace(target);
		}
	}
		
	this.setAutoRefreshFlag(false);	
	/*
	Market View refresh hack for instant gratification in bet placement.
	*/
	clearTimeout(this.marketUpdateTimeout);
	if(forceMarketInterimRefresh && this.currentTimeOut == controllers_MARKETVIEW_REFRESH_TIMEOUT){
		this.currentTimeOut = controllers_MARKETVIEW_REFRESH_TIMEOUT;
	}else if(this.currentTimeOut != controllers_MARKETVIEW_REFRESH_TIMEOUT){
		this.currentTimeOut = controllers_MARKETVIEW_REFRESH_TIMEOUT;
	}else if(userAction){
		this.currentTimeOut = controllers_MARKETVIEW_REFRESH_TIMEOUT;
	}
	this.marketUpdateTimeout = setTimeout("interface_startMarketRefresh()", this.currentTimeOut);
}


;controllers_UIController.prototype.startMarketRefresh = function(){
	if(this.marketHasLoaded){
		if(this.user.preferences.autoRefresh){
			this.refreshMarket();
		}
	}
	clearTimeout(this.marketUpdateTimeout);
	this.currentTimeOut = controllers_MARKETVIEW_REFRESH_TIMEOUT;
	this.marketUpdateTimeout = setTimeout("interface_startMarketRefresh()", this.currentTimeOut);
}

;controllers_UIController.prototype.setActiveBetManagerTab = function(iTabId){
      var oController = this.betManagerController.placeBetsController;  
      if(iTabId == controllers_PLACE_MYBETS_TAB && this.marketHasLoaded)
      {                  
                        if (iTabId == controllers_PLACE_MYBETS_TAB && !this.user.loggedIn) {
                              return alert(loginMsg);
                        } 
      }
      // added by Ash to reset the placebet screen when the place bet tab is clicked.
    else if (iTabId == controllers_PLACE_BETS_DEFAULT_VIEW && oController.placeBetsView.currentState == controllers_PLACE_BETS_PROCESSING_VIEW )
    {
         this.betManagerController.placeBetsController.placeBetsView.cancelAllPlaceBets();
         betexUIGlobalSettings.multipleBetType = models_BidType.BACK;

         if (document.getElementById("optMultiple") != null){
	         document.getElementById("optMultiple").checked = true;	         
	     }	    
         this.betManagerController.placeBetsController.placeBetsView.setState(controllers_PLACE_BETS_PLACEBETS_VIEW); 
    }
    this.betManagerController.setActiveTab(iTabId);
    PlacebetsPanelHeight(this.betManagerController.myBetsController.bets);
}

;controllers_UIController.prototype.setPlaceBetPreCondition = function(value){
	this.placeBetPreConditon = value;
}

;controllers_UIController.prototype.setAutoRefreshFlag = function(value){
	this.autoRefreshFlag = value;
}
;controllers_UIController.prototype.getAutoRefreshFlag = function(){
	return this.autoRefreshFlag;
}

;controllers_UIController.prototype.placeBet = function(marketId, runnerId, betIndex, bidType, DOMObject, viewType, marketInfoDOMReference){
	if(!this.placeBetPreConditon){
		return;
	}	
	var oController = this.betManagerController.placeBetsController;	
	
	if(this.betManagerController.activeTab == controllers_PLACE_MYBETS_TAB){		
		this.betManagerController.placeBetsController.placeBetsView.setState(controllers_PLACE_BETS_PLACEBETS_VIEW);
		this.betManagerController.setActiveTab(controllers_PLACE_BETS_TAB);
	}	
	if(this.market instanceof models_Coupon){
		if(marketId  != this.currentlySelectedCouponMarketId){					
			this.setActiveCouponMarket(marketId);
		}
	} else {
		if(this.market.isSuspended) {
			return alert(sKey_AlertSuspended);
		}
	}
	this.betManagerController.placeBet(runnerId, betIndex, bidType, DOMObject, this.marketViewController.currentlySelectedCouponStakeValue,viewType, marketInfoDOMReference);
}

;controllers_UIController.prototype.placeMultipleBets = function(bidType){
	if(this.betManagerController.placeBetsController.placeBetsView.currentState == controllers_PLACE_BETS_PROCESSING_VIEW || !this.market) {
		return;
	}
	this.betManagerController.placeMultipleBets(bidType, this.marketViewController.currentlySelectedCouponStakeValue);
}


;controllers_UIController.prototype.setActiveCouponMarket = function(marketId, actionedFromArrows){
	if(this.betManagerController.placeBetsController.placeBetsView.currentState == controllers_PLACE_BETS_PROCESSING_VIEW) {
		return;
	}
	if(this.currentlySelectedCouponMarketId == marketId) {
		return;
	}
	this.currentlySelectedCouponMarketId = marketId;	
	if(this.marketHasLoaded) {	
		this.marketViewController.setActiveCouponMarket(marketId, actionedFromArrows);	
		this.betManagerController.setActiveCouponMarket(marketId);
	}
	if(this.betManagerController.activeTab == controllers_PLACE_MYBETS_TAB && this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId).hasBets){
		this.startMyBetsRefresh(true, marketId);
	}
	this.currentMyBetsTimeOut = controllers_MYBETS_REFRESH_TIMEOUT;
	if(this.marketHasLoaded){	
		if(actionedFromArrows && this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId).hasBets){				
			this.setActiveBetManagerTab(controllers_PLACE_MYBETS_TAB);
		} else {				
			if (this.user.preferences.showHelp) {				
				this.setActiveBetManagerTab(controllers_HELP_TAB);
			} else {			
				this.setActiveBetManagerTab(controllers_PLACE_BETS_TAB);
			} 
		}
	}else{		
		this.betManagerController.setActiveCouponMarket(marketId);
	}
}

;controllers_UIController.prototype.sessionTimeout = function(user){
	this.setUserPreferences(user);
	this.betManagerController.sessionTimeout();
}

/*
*	The following controller functions are to enable the obfuscator to obfuscate the JS and not effect the event handling that was handled by the relevant nodes.
*/
;controllers_UIController.prototype.deleteBet = function(betId, bidType, origin){
	if(origin == models_BetActionOrigin.MYBETS){
		var bet = this.betManagerController.myBetsController.bets.getBetByBetId(betId, bidType);
		this.betManagerController.myBetsController.deleteBet(bet);
	}else{
		var bet = this.betManagerController.placeBetsController.bets.getBetByRunnerIdAndBidType(betId, bidType);
		this.betManagerController.placeBetsController.deleteBet(bet);
	}
}

;controllers_UIController.prototype.deletePlaceBet = function(marketId){
	this.betManagerController.placeBetsController.deletePlaceBet(marketId);
}

;controllers_UIController.prototype.deleteMultipleBet = function(betId, bidType, origin){
		var bet = this.betManagerController.placeBetsController.bets.getBetByRunnerIdAndBidType(betId, bidType);
		this.betManagerController.placeBetsController.deleteMultipleBet(bet);
}

;controllers_UIController.prototype.deleteMultipleFoldBet = function(betFoldId, trId){
		this.betManagerController.placeBetsController.deleteMultipleFoldBet(betFoldId, trId);
}

;controllers_UIController.prototype.registerUser = function(){
	if(this.user.loggedIn) {
		alert(sAlreadyLoggedIn);
	}
	else {
		spawn("joinNow");
	}
}

/*
* User Manager
*/

function controllers_User() {
	this.market = null;
	this.user = null;
	this.preferences = null;
	this.userPrefsView = new views_User();
	this.ajax = new AjaxObject(this);
	this.oldPreferences = null;
}

;controllers_User.prototype.setMarket = function(market) {
	this.market = market;
	this.userPrefsView.setMarket(market);
}

;controllers_User.prototype.setUser = function(user) {
	this.user = user;
	this.userPrefsView.setUser(user);
	this.preferences = new cloneObject(user.preferences);
}

;controllers_User.prototype.updatePreferences = function(oFormElement, event, bForcedView) {
	var params = "";
	switch(oFormElement.id) {
		case "showHelp":
			this.user.preferences.showHelp = oFormElement.checked;
			SetCookie("", constants_SHOW_HELP_COOKIE, this.user.preferences.showHelp);
			this.preferences = new cloneObject(this.user.preferences);
			params = "showHelp=" + this.user.preferences.showHelp;
		break;
		case "compactUIView":
			params = "multiplesUIView=COMPACT";
			if (this.market) {
				if (this.market.betType != constants_MARKET_TYPE_RANGE && this.market.betType != constants_MARKET_TYPE_LINE) { 
					this.user.preferences.multiplesUIView = constants_UI_VIEW_COMPACT;
					SetCookie("", constants_MULTIPLES_UI_VIEW_COOKIE, constants_UI_VIEW_COMPACT);
				}
			}
			this.preferences = new cloneObject(this.user.preferences);
			changeUIview(false);
			PlacebetsPanelHeight(null);
		break;
		case "exchangeUIView":
			params = "multiplesUIView=EXCHANGE";
			this.user.preferences.multiplesUIView = constants_UI_VIEW_EXCHANGE;
			if (!bForcedView) { // update cookie only if user has changed it, not the market determining what view is displayed
				SetCookie("", constants_MULTIPLES_UI_VIEW_COOKIE, constants_UI_VIEW_EXCHANGE);
			}
			this.preferences = new cloneObject(this.user.preferences);
			changeUIview(true);
			PlacebetsPanelHeight(null);			
		break;		
	} 
	this.userPrefsView.updatePreferences(oFormElement, event);
	
	if (params != "" && this.user.loggedIn) {
		var action = "/multiples/betting/SetIndividualPreferenceAction.do";
		this.ajax.post(action, params);
	}
}

function changeUIview(IsenhancedView)
{
	// Added by Ash to remove/show the appearance of Back / Lay multiples radio buttons depending upon Express view or Enhanced view
	
	if(isMozilla()){
	
		if(!IsenhancedView){
			document.getElementById("BMPlaceBetsRadioRow").style.visibility = "hidden";
		} else {
			document.getElementById("BMPlaceBetsRadioRow").style.visibility = "visible";		
		}
	
		//Adjusting height for mozilla
		footerH = document.getElementById('BMPlaceBetsBetViewFooter').offsetHeight;
		radioRowH = document.getElementById('BMPlaceBetsRadioRow').offsetHeight;
				
		if( footerH > radioRowH & !IsenhancedView){
			document.getElementById('BMPlaceBetsBetViewFooter').style.height = footerH - radioRowH;
		} else if (footerH < radioRowH){
			document.getElementById('BMPlaceBetsBetViewFooter').style.height = footerH + radioRowH;
		}		
	
	} else {
		
		if(!IsenhancedView){
			document.getElementById("BMPlaceBetsRadioRow").style.display = "none";
		} 
		else {
			document.getElementById("BMPlaceBetsRadioRow").style.display = "block";		
		}	
	}
	
	// Variable to hold all the div in the page
	var alldiv = document.all ?
    document.all.tags('div') :
    document.getElementsByTagName ? 
    document.getElementsByTagName('div') : new Array();
    
    var arrTDId = new Array();

    // Searches all the div within which prices are displayed. Those tables are hidden.
    for (var divCtr=0;divCtr<alldiv.length;divCtr++)
    {
    	// Hides/Shows all the Lay buttons when Back is selected - .bets.items[0].bidType above deleted
    	if( (alldiv[divCtr].id.indexOf("OddsMVBackButton_") >= 0) || (alldiv[divCtr].id.indexOf("OddsMVLayButton_") >= 0) || (alldiv[divCtr].id.indexOf("divThirdRunnerMVCouponLayButton_") >= 0)  || (alldiv[divCtr].id.indexOf("divThirdRunnerMVCouponBackButton_") >= 0)  || (alldiv[divCtr].id.indexOf("divSecondRunnerMVCouponLayButton_") >= 0)  || (alldiv[divCtr].id.indexOf("divSecondRunnerMVCouponBackButton_") >= 0)  || (alldiv[divCtr].id.indexOf("divFirstRunnerMVCouponLayButton_") >= 0)  || (alldiv[divCtr].id.indexOf("divFirstRunnerMVCouponBackButton_") >= 0) ) 
    	{
    		if(alldiv[divCtr].innerHTML == "0" || parseInt(alldiv[divCtr].innerHTML) == 0 || alldiv[divCtr].innerHTML == htmlMVAskButton || alldiv[divCtr].innerHTML == "" )
    		{
    			alldiv[divCtr].style.visibility = 'hidden';
    		}
    	}
	}
	
}

/**
 * This function is a hack to avoid Bet Manager tab switching from Place Bet Tab to Help Tab; if showHelp == true
 */ 
;controllers_User.prototype.updateShowHelpPreference = function(oUser) {	
	if(oUser.preferences.showHelp){	
		//Saving old prefereces before modifying; to get hold of them later		
		this.oldPreferences = new cloneObject(oUser.preferences);		
		//setting showHelp to false temporarily
		oUser.preferences.showHelp = false;		
	}
	return oUser;
}
;controllers_User.prototype.handleAjaxResponse = function(response) {

}

;controllers_User.prototype.showTermsAndConditions = function(obj) {
	spawn(obj);
}

/*
* Panel Manager - Controller
*/

function controllers_PanelManagerController() {
	this.panelManagerView = new views_PanelManager();
	this.market = null;
}

;controllers_PanelManagerController.prototype.setMarket = function(market) {
	this.market = market;
	this.panelManagerView.setMarket(market);
}

;controllers_PanelManagerController.prototype.restorePanels = function() {
	this.panelManagerView.restorePanels();
}

;controllers_PanelManagerController.prototype.displayPanel = function(event, panelName) {
	var id = "";
	if (panelName == "MVHelpBackMultiplesInfo" || panelName == "MVHelpLayMultiplesInfo") { 
		if (event.srcElement) {
			id = event.srcElement.parentNode.id;
		} else if (event.target) {
			id = event.target.parentNode.id;
		}
	}
	
	if ((panelName.substring(0,6) != "MVHelp" && panelName.substring(0,12) != "MVEnhancedUI") 
		|| (panelName.substring(0,12) == "MVEnhancedUI" && betexUIController.userController.user.preferences.enhancedView && this.market.enhanced) 
		|| (panelName == "MVHelpShowHelp") 
		|| (panelName.substring(0,6) == "MVHelp" && betexUIController.userController.user.preferences.showHelp) 
		|| ((panelName == "MVHelpBackMultiplesInfo" || panelName == "MVHelpLayMultiplesInfo") && id == "moreInfoTD")) {
		this.panelManagerView.displayPanel(event, panelName);
	}
}

;controllers_PanelManagerController.prototype.populatePanel = function(panelName, runnerId) {
	this.panelManagerView.populatePanel(panelName, runnerId);
}

;controllers_PanelManagerController.prototype.hidePanel = function(panelName) {
	this.panelManagerView.hidePanel(panelName);
}

;controllers_PanelManagerController.prototype.togglePanel = function(event, panelName) {
	if (eval("document.getElementById('" + panelName + "')").style.display == "none") {
		if (panelName == "MVHelpOddsConvertor") {
			betexJITController.loadOddsConverter("PU");
		}
		this.panelManagerView.displayPanel(event, panelName);
	} else {
		this.panelManagerView.hidePanel(panelName);
	}
}

;controllers_PanelManagerController.prototype.cancelEventBubble = function(event) {
	this.panelManagerView.cancelEventBubble(event);
}

;controllers_PanelManagerController.prototype.toggleMVOptionsPanel = function() {
	this.panelManagerView.toggleMVOptionsPanel();
}

/**
* Bet Manager Controller
*/
function controllers_BetManagerController(marketViewHandle){
	this.market = null;
	this.user = null;
	this.activeTab = null;
	this.betManagerView = new views_BetManagerView(this.market);
	this.placeBetsController = new controllers_PlaceBetsController();
	this.myBetsController = new controllers_MyBetsController(marketViewHandle);
	this.marketInformationController = new controllers_MarketInformationController();
	this.oPAndLAnnotations = null;
	this.betManagerLoaded = false;
}

;controllers_BetManagerController.prototype.setMarket = function(market){
	if(market instanceof models_Coupon){
		if(this.market instanceof models_Coupon){
			if ((this.market.id != market.id) || (this.market.id == market.id && !betexUIController.compareCouponMarkets(this.market,market))){
				this.currentlySelectedCouponMarketId = null;				
			}
		}else{
			this.currentlySelectedCouponMarketId = null;			
		}
	}else{
		this.currentlySelectedCouponMarketId = null;
		if(this.market instanceof models_Coupon){
			if (this.market.id != market.id){}
		} else if(this.market != null && this.market.marketId != market.marketId){}
	}
	this.market = market;
	this.betManagerView.setMarket(market);	
	this.placeBetsController.setMarket(market);
	this.myBetsController.setMarket(market);
	this.marketInformationController.setMarket(market);
}


;controllers_BetManagerController.prototype.resetMarket = function(){
	this.setActiveTab((this.user.preferences.showHelp) ? controllers_HELP_TAB : controllers_MARKET_INFORMATION_TAB);
}

;controllers_BetManagerController.prototype.placeBet = function(runnerId, betIndex, bidType, DOMObject, currentlySelectedCouponStakeValue, viewType, marketInfoDOMReference){
	this.setActiveTab(controllers_PLACE_BETS_TAB);
	this.placeBetsController.placeBet(runnerId, betIndex, bidType, DOMObject, currentlySelectedCouponStakeValue, viewType, marketInfoDOMReference);
}

;controllers_BetManagerController.prototype.placeMultipleBets = function(bidType, currentlySelectedCouponStakeValue){
	this.setActiveTab(controllers_PLACE_BETS_TAB);
	this.placeBetsController.placeMultipleBets(bidType, currentlySelectedCouponStakeValue);
}

;controllers_BetManagerController.prototype.setActiveTab = function(tabId){	
	if(this.activeTab == tabId) {
		return;
	}
	if(tabId == controllers_PLACE_MYBETS_TAB && !this.user.loggedIn) {
		return alert(loginMsg);
	}
	if(this.placeBetsController.placeBetsView.currentState == controllers_PLACE_BETS_CONFIRMATION_VIEW) {
		this.placeBetsController.confirmBetsContinue();
	}
	if(this.myBetsController.myBetsView.currentState == controllers_My_BETS_CONFIRMATION_VIEW) {
		this.myBetsController.confirmedMyBetsContinue();
	}
	
	if(tabId == controllers_PLACE_BETS_TAB)
	{
		document.getElementById("BMMyBetsNoBetsViewWrapper").style.display = "none";
	}
	this.activeTab = tabId;
	this.betManagerView.setActiveTab(tabId);
	this.betManagerView.updateView();

	if (tabId == controllers_PLACE_MYBETS_TAB)
	{
		document.getElementById("BMMyBetsNoBetsViewWrapper").style.display = "block";	
	}
}

;controllers_BetManagerController.prototype.setBetPlacementResult = function(stakeList, foldsList, bidTy, currBetRefId){
	this.placeBetsController.setBetPlacementResult(stakeList, foldsList, bidTy, currBetRefId);
}

;controllers_BetManagerController.prototype.setActiveMyBetTabMultiple = function(){		
	var tabId = controllers_PLACE_MYBETS_TAB;
	this.activeTab = controllers_PLACE_MYBETS_TAB;
	var marketBets;
	
	this.betManagerView.setActiveTab(tabId);
	this.placeBetsController.placeBetsView.drawMyBetSelection();
	this.placeBetsController.placeBetsView.drawMyBetResult();
	this.placeBetsController.placeBetsView.drawMyBetFooter();
	this.betManagerView.updateView();
	
	myBetsHeadersAndFooters(this.placeBetsController.bets);

	document.getElementById("BMMyBetsContentWrapper").style.display = "block";	
			
	var totalHeight = document.body.clientHeight;


	//document.getElementById("BMMyBetsBetsViewWrapper").style.height = totalHeight * (80/100);

	this.betHTMLContextIsSet = true;
	
	// This is for turning ON the visiblity of the runners after a bet is placed
	var iSize = this.placeBetsController.bets.getMarketLegsLength();	
	if(this.market instanceof models_Coupon){
		for (var x = 0; x <  iSize; x++){						
				marketLegsObj =  this.placeBetsController.bets.marketLegsCollection[x];
				marketId = marketLegsObj.marketId;
				bidType = marketLegsObj.betType;				
				try{
					this.placeBetsController.HideShowAlternateBetType(marketId, bidType, 'visible', false, this.placeBetsController.market.markets.getMarketByMarketId(marketId).runners);
				} catch(z){					
					if(z){
						continue
					}
				}
				var marketBets = this.placeBetsController.bets.getBetsByMarketId(marketId);
				if(marketBets){
					for (var y = 0; y < marketBets.length; y++){																
						betexUIController.marketViewController.marketView.setMarketViewButtonToggleClass(marketBets[y].attachedParentDOMReference);
					}
				}		
			
			}
	} else {		
		marketObj = this.market;
		this.placeBetsController.SingleMarketHideShowAlternateBetType(marketObj.marketId, "", 'visible', false, marketObj.runners);	
		marketBets = this.placeBetsController.bets.getBetsByMarketId(this.market.marketId);
		if(marketBets){
			for (var x = 0; x < marketBets.length; x++){				
				betexUIController.marketViewController.marketView.setMarketViewButtonToggleClass(marketBets[x].attachedMarketInfoDOMReference);
			}
		}
	}
	
	
	this.placeBetsController.setToggleMVButtonStatus(false);	
    this.placeBetsController.placeBetsView.cancelAllPlaceBets();
    this.placeBetsController.placeBetsView.buildBetItems();
	//document.getElementById("BMMyBetsContentWrapper").style.height = totalHeight * (94/100);    
    this.bets=null;
}

function myBetsHeadersAndFooters(bets) {
		// Added by Ash to control the display of the header and footer in My bets
		if (bets.getMarketLegsLength() >= betexUIGlobalSettings.minLegSize) {
			document.getElementById("TableMyBetsHeading").style.display = "block";
			document.getElementById("TableMyBetsFooter").style.display = "block";
						
			document.getElementById("BMMyBetsNoBetsViewWrapper").style.display = "none";
		}
}

;controllers_BetManagerController.prototype.setUserPreferences = function(user){
	this.user = user;
	this.placeBetsController.setUserPreferences(user);
	this.myBetsController.setUserPreferences(user);
	this.marketInformationController.setUserPreferences(user);
	this.betManagerView.setUserPreferences(user);

	if (this.user.preferences.showHelp) {
		this.setActiveTab(controllers_HELP_TAB);
	} else {
		this.setActiveTab(controllers_PLACE_BETS_TAB);
	} 
}

;controllers_BetManagerController.prototype.setActiveCouponMarket = function(marketId){
	if(this.currentlySelectedCouponMarketId == marketId) {
		return;
	}
	this.currentlySelectedCouponMarketId = marketId;	
	this.placeBetsController.setActiveCouponMarket(marketId);
	this.myBetsController.setActiveCouponMarket(marketId);
	this.marketInformationController.setActiveCouponMarket(marketId);	
}

;controllers_BetManagerController.prototype.sessionTimeout = function(user){
	this.placeBetsController.placeBetsView.throwBetPlacementException();
	this.myBetsController.myBetsView.throwBetEditException();
}

;controllers_BetManagerController.prototype.controlRealEstate = function(sFunctionalArea) {	
	if (sFunctionalArea == "initialise") {
		if (!this.betManagerLoaded) {
			this.betManagerLoaded = true;
			this.controlRealEstate("resize");
		}
	} else {
		if (this.betManagerLoaded) {
			var totalHeight = document.body.clientHeight;
			var BMHeaderHeight = document.getElementById('BMHeaderWrapper').offsetHeight;
			switch(sFunctionalArea) {
				case "placeBets":					
					var BMPlaceBetsHeaderHeight = document.getElementById('BMPlaceBetsHeaderWrapper').offsetHeight;
					var BMPlaceBetsFooterHeight = document.getElementById('BMPlaceBetsFooterWrapper').offsetHeight;
					var iHeight = totalHeight - BMHeaderHeight - BMPlaceBetsHeaderHeight - BMPlaceBetsFooterHeight - 3; // extra 3 pixels come from padding
					document.getElementById('BMPlaceBetsContentWrapper').style.height = iHeight;
					document.getElementById('BMPlaceBetsVerifyViewWrapper').style.height = iHeight;
				break;
				case "myBets":
					var BMMyBetsHeaderHeight = document.getElementById('BMMyBetsHeaderWrapper').offsetHeight;
					var iHeight = totalHeight - BMHeaderHeight - BMMyBetsHeaderHeight - 3;
					document.getElementById("BMMyBetsContentWrapper").style.height = ((iHeight > 0) ? iHeight : 0);
				break;
				case "help":							
					if(this.betManagerView.activeTab != controllers_PLACE_BETS_TAB){
						document.getElementById("BMPlaceBetsHeaderWrapper").style.display = "none";
					}
					var iHeight = totalHeight - BMHeaderHeight - 3; // extra 3 pixels come from padding
					document.getElementById("BMHelpWrapper").style.height = ((iHeight > 0) ? iHeight : 0);
					iHeight = iHeight - document.getElementById("BMHelpHeader").offsetHeight - document.getElementById("BMHelpFooter").offsetHeight;
					document.getElementById("BMHelpContent").style.height = ((iHeight > 0) ? iHeight : 0);
				break;
				case "resize":
					var iHeight = totalHeight - BMHeaderHeight - 2; // extra 2 pixels come from padding
					document.getElementById("BMContentWrapper").style.height = ((iHeight > 0) ? iHeight : 0);					
					this.controlRealEstate("placeBets");				
					this.controlRealEstate("myBets");			
					this.controlRealEstate("help");					
					iHeight = totalHeight - BMHeaderHeight - 3; // extra 3 pixels come from padding
					document.getElementById("BMMarketInformationWrapper").style.height = ((iHeight > 0) ? iHeight : 0);
				break;
			}
		}
	}
}

;controllers_BetManagerController.prototype.showViewBetsButtonsAndHideMessage = function(){
	var viewBetsButtonDiv = document.getElementById("BMViewBetsButtonDiv");
	var viewBetsMessageDiv = document.getElementById("BMViewBetsMessageDiv");
		
	//Show View Bets Buttons ('Clear All' &  'View Odds') 	
	if(viewBetsButtonDiv){
		viewBetsButtonDiv.style.display = "block";	
	}
						
	//Hide View Bets Calculating Odds Message	
	if(viewBetsMessageDiv){	
		viewBetsMessageDiv.style.display = "none";	
	}	
}

;controllers_BetManagerController.prototype.hideViewBetsButtonsAndShowMessage = function(){
	var viewBetsButtonDiv = document.getElementById("BMViewBetsButtonDiv");
	var viewBetsMessageDiv = document.getElementById("BMViewBetsMessageDiv");
	
	//Hide View Bets Buttons ('Clear All' &  'View Odds') 	
	if(viewBetsButtonDiv){
		viewBetsButtonDiv.style.display = "none";	
	}
						
	//Show View Bets Calculating Odds Message	
	if(viewBetsMessageDiv){	
		viewBetsMessageDiv.style.display = "block";	
	}	
}
;controllers_BetManagerController.prototype.showPlaceBetsButtonsAndHideMessage = function(){
	var placeBetsButtonDiv = document.getElementById("BMPlaceBetsButtonDiv");
	var	placeBetsMessageDiv = document.getElementById("BMPlaceBetsMessageDiv");	
	
	//Show Place Bets Buttons ('Clear All' &  'View Odds') 	
	if(placeBetsButtonDiv){
		placeBetsButtonDiv.style.display = "block";	
	}
						
	//Hide Place Bets Processing Message	
	if(placeBetsMessageDiv){	
		placeBetsMessageDiv.style.display = "none";	
	}	

}
;controllers_BetManagerController.prototype.hidePlaceBetsButtonsAndShowMessage = function(){
	var placeBetsButtonDiv = document.getElementById("BMPlaceBetsButtonDiv");
	var placeBetsMessageDiv = document.getElementById("BMPlaceBetsMessageDiv");	
	
	//Hide Place Bets Buttons ('Clear All' &  'View Odds') 	
	if(placeBetsButtonDiv){
		placeBetsButtonDiv.style.display = "none";	
	}
						
	//Show Place Bets Processing Message	
	if(placeBetsMessageDiv){	
		placeBetsMessageDiv.style.display = "block";	
	}	
}

/**
* PlaceBets Controller
*/
function controllers_PlaceBetsController(){
	this.market = null;
	this.bets = new models_Bets();
	this.myBets = new models_Bets();
	this.confirmedBets = new models_Bets();
	this.confirmedBetResults = new models_BetPlacementResults();
	this.placeBetsHelper = new controllers_BetsHelperController(this.bets);
	this.placeBetsView = new views_PlaceBetsView(this.bets);
	this.currentlySelectedCouponMarketId = null;
	this.liabilityItems = new models_BetsLiabilityItems();
	this.oPAndLAnnotations = null;
	this.betsSubmitted = false;
//	this.loadMarketChoices();
	this.multiplesHelperController = new controller_MultiplesHelperController();
	this.currentBet = null;
	this.toggleMVButton = false;
}

;controllers_PlaceBetsController.prototype.loadMarketChoices = function(){
	this.bets.choiceCollection = new Array();

	for (var mlCount = betexUIGlobalSettings.maxLegSize - 1; mlCount >= 0; mlCount--) {
		var choiceContainer = new models_MarketChoiceContainer();
		choiceContainer.containerId = mlCount + 1;
	
		var bCount = mlCount;
		var choice = new models_MarketChoice();
		choice.choiceValue = marketChoiceValues[mlCount, bCount];
		choice.choiceName = marketChoiceNames[mlCount, bCount];
		choice.choiceFold = bCount + 1;
		choiceContainer.addChoices(choice);				
	
		this.bets.addChoiceCollection(choiceContainer);
	}
}

;controllers_PlaceBetsController.prototype.setMarket = function(market){	
	var marketChanged = false;
	if(market instanceof models_Coupon){		
		if(this.market instanceof models_Coupon){
			if ((this.market.id != market.id) || (this.market.id == market.id && !betexUIController.compareCouponMarkets(this.market,market))){
				marketChanged = false;
			}
		}else{
			marketChanged = false;
		}
	}else{	
		if(this.market instanceof models_Coupon){
			marketChanged = true;
		}else if(this.market != null && this.market.marketId != market.marketId) {
			marketChanged = false;
		}else if(this.market == null){
			marketChanged = true;
		}
	}
	this.market = market;		
	this.placeBetsView.setMarket(market);
	if(this.placeBetsView.currentState != controllers_PLACE_BETS_PLACEBETS_VIEW){
		this.placeBetsView.updateView(true);
	}
	if(marketChanged){
		if(!(market instanceof models_Coupon)){
			this.setBetLiabilityItems();
		}
	}else{
		this.setBetLiabilityItems(true);
	}
	// Added by Ash to control the visiblity of Multiples back/lay radio buttons.
	if (this.user.preferences.multiplesUIView == constants_UI_VIEW_EXCHANGE)
		changeUIview(true);
	else
		changeUIview(false);
}

;controllers_PlaceBetsController.prototype.setMyBets = function(oMyBets){
	this.myBets = oMyBets;
}

;controllers_PlaceBetsController.prototype.setBetPlacementResult = function(stakeList, foldsList, bidTy, betRefId){
	this.bets.setUpdatedStakeCollection(stakeList);
	this.bets.setFoldsCollection(foldsList);	
	this.bets.bidSelectedType = bidTy;
	this.bets.betReferenceId = betRefId;
}

;controllers_PlaceBetsController.prototype.setBetLiabilityItems = function(updateLiabilityModel){
	var market;
	if(this.market instanceof models_Coupon) {
		market = this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId);
	}
	else {
		market = this.market;
	}
	
	if(!this.market instanceof models_Coupon) 
	{
		for (var i=0;i<market.runners.length();i++)
		{
			if(updateLiabilityModel)
			{
				var runnerExists = this.liabilityItems.getLiabilityItemByRunnerId(market.runners.get(i).runnerId);
				if(!runnerExists)
				{
					var newLiabilityItem = new models_BetsLiabilityItem();
					newLiabilityItem.runner = market.runners.get(i);
					this.liabilityItems.add(newLiabilityItem);
				}
			}
			else
			{
				var newLiabilityItem = new models_BetsLiabilityItem();
				newLiabilityItem.runner = market.runners.get(i);
				this.liabilityItems.add(newLiabilityItem);
			}
		}
	}
}

;controllers_PlaceBetsController.prototype.resetMarket = function(){
	this.currentlySelectedCouponMarketId = null;
	this.bets.empty();
	this.liabilityItems.empty();
}

;controllers_PlaceBetsController.prototype.setActiveCouponMarket = function(marketId){
	if(this.currentlySelectedCouponMarketId == marketId) {
		return;
	}
	this.currentlySelectedCouponMarketId = marketId;
	this.placeBetsHelper.setActiveCouponMarket(marketId);
	this.placeBetsView.setActiveCouponMarket(marketId);
	this.setBetLiabilityItems();
}

;controllers_PlaceBetsController.prototype.placeBet = function(runnerId, betIndex, bidType, DOMObject, currentlySelectedCouponStakeValue, viewType, marketInfoDOMReference){	

	if (this.placeBetsView.currentState == controllers_PLACE_BETS_PROCESSING_VIEW) {
		return;
	}
	if (this.placeBetsView.currentState == controllers_PLACE_BETS_CONFIRMATION_VIEW) {
		return;
	}
	
	var objDom = document.getElementById(DOMObject);
	if (objDom == null || objDom.disabled) {
		return;
 	}
 	
	var duplicatedBet = this.bets.getBetByRunnerIdAndBidType(runnerId, bidType);
	var ctrBets=0;
	var betDetailsArray;
	var betDetails;
	var marketObj;	
	var selectedRunnersItems=1;
	var arrSelectedRunners = new Array();
	
	// Validation for closed markets
	if (this.market) {
		if (this.market.isClosed) {
			alert(closedMessage);
			return;
		}
	}
	
	// Validation for suspended markets
	if (this.market.isSuspended) {
		return;
	}	
	if (this.market instanceof models_Coupon) {		
		marketObj = this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId);		
	} else {
		marketObj = this.market;			
	}
	
	// This condition will be met when Coupon view is currently ON.	
	if (this.market instanceof models_Coupon) {
		// The first market is picked from the coupon to get the number of runners. Note: The number of runners will be the same for all the markets in a coupon
		if (!this.validateSingleOrMultipleWinnerMarkets(this.bets.length(), this.market.markets.items[0].runners.items.length, duplicatedBet, 2, this.bets, marketObj, true )) {
			return;
		}
	} else {
		// This condition will be met when Market view is currently ON.	
		if (!this.validateSingleOrMultipleWinnerMarkets(this.bets.length(), marketObj.runners.length(), duplicatedBet, this.market.numberOfWinners, this.bets, marketObj, false )) {
			return;
		}
	}	
	
	// Condition to check if the current market selection is within the same group as per the previous selected market
	if (this.bets.length() > 0) {
		var betDetailsForGroup = this.bets.get(0).toString();
		var betDetailsForGroupArray = betDetailsForGroup.split("\t");
		
		if (marketObj.groupId != betDetailsForGroupArray[10]) {
			alert(marketInOtherGroup);
			return;
		}
	}	
	if (this.ValidateConflicts(marketObj)==false) {
		alert(conflictingMarketsSelection);
		return;		
	} 
	if (duplicatedBet) {		
		if (this.market instanceof models_Coupon) {
			return this.deleteBet(duplicatedBet, marketObj.marketId, true, marketObj, viewType);
		} else {
			if (marketObj.runners.getRunnerByRunnerId(runnerId).bets.get(betIndex).getPrice() != duplicatedBet.getPrice()) {
				this.deleteBet(duplicatedBet, marketObj.marketId, false, marketObj, viewType);
			} else {
				return this.deleteBet(duplicatedBet, marketObj.marketId, false, marketObj, viewType);
			}
		}
	}	
	var runner;
	runner = marketObj.runners.getRunnerByRunnerId(runnerId);

	var thisBet = new models_Bet();
	thisBet.betId = runnerId + '_' + bidType + '_bet';
	thisBet.runner = runner;
	thisBet.MultMarketName=marketObj.name;
	thisBet.bidType = bidType;
	thisBet.betStatus = models_BetStatusEnum.POTENTIAL;
	thisBet.marketId = marketObj.marketId;
	thisBet.groupId = marketObj.groupId;
	thisBet.runnerId = runnerId;
	thisBet.multId = marketObj.multId;
	thisBet.viewType = viewType;

	if (this.market instanceof models_Coupon) {
		if (runner.bets.get(betIndex) != null) {
			thisBet.setPrice((this.user.preferences.couponOddsDisplay == models_CouponOddsView.AVERAGE)? (runner.bets.get(betIndex).couponAveragePrice)? runner.bets.get(betIndex).couponAveragePrice : runner.bets.get(betIndex).getPrice() : runner.bets.get(betIndex).getPrice());
		}
		thisBet.setSize(currentlySelectedCouponStakeValue);
	} else {
		if (runner.bets.get(betIndex) != null) {
			thisBet.setPrice(runner.bets.get(betIndex).getPrice());
		}
	}
	
	var tmpMarketId = new Array();
	
	for (var iCnt=0;iCnt<this.bets.getMarketLegsLength();iCnt++) {
		var oMarketLegs = this.bets.getMarketLegs(iCnt);
		tmpMarketId[iCnt] = oMarketLegs.marketId;
	}
	
	// Maximum legs
	if ((this.bets.getMarketLegsLength()) >= betexUIGlobalSettings.maxLegSize) {
		if (this.checkAvailability(tmpMarketId, marketObj.marketId) == DEFAULT_MARKET_INDEX) {
			alert(maximumLegs.replace(/{MaximumLegs}/, betexUIGlobalSettings.maxLegSize));
			return;
		}
	}
	
	if (this.market instanceof models_Coupon) {
		thisBet.attachParentBetDOMReference(DOMObject);
		thisBet.attachMarketInfoDOMReference(marketInfoDOMReference);
	} else {
		thisBet.attachParentBetDOMReference(marketInfoDOMReference);
		thisBet.attachMarketInfoDOMReference(DOMObject);	
	}
		
	this.bets.add(thisBet);		
	
	// This section is for hiding the other bid types when a bid type is selected
	if (this.market instanceof models_Coupon) {		
		this.HideShowAlternateBetType(marketObj.marketId, bidType, 'hidden', true, marketObj.runners);		
	} else {
		this.SingleMarketHideShowAlternateBetType(marketObj.marketId, bidType, 'hidden', true, marketObj.runners);
	}
	
	// Section for zero market winner

	var ZeroMarketFlag = false;		// This is included in the deletebet section too.
	if (ZeroMarketFlag) {
		this.ZeroMarketWinnerHideShowBetType(marketObj, bidType, 'hidden', true, runnerId);
    }  	
	iSize = 0;	
	var marketId = "";
	var marketAvailabilityIndex = DEFAULT_MARKET_INDEX;
	for (var iCnt=0;iCnt<this.bets.length();iCnt++) {
		var oBet = this.bets.get(iCnt);
		var marketToBeAdded = false;		
		marketId = oBet.runner.marketId;
		if (tmpMarketId.length > 0) {		
			marketAvailabilityIndex = this.checkAvailability(tmpMarketId, marketId);			
			if (marketAvailabilityIndex != DEFAULT_MARKET_INDEX) {				
				var marketLegs = this.bets.getMarketLegs(marketAvailabilityIndex);
				var addRunner = false;
				for (var iTemp=0;iTemp<marketLegs.getLegLength();iTemp++) {
					var oLeg = marketLegs.getLeg(iTemp);
					if (oLeg.runnerId == oBet.runner.runnerId) {
						addRunner = false;
						break;
					} else {
						addRunner = true;
					}
				}

				if (addRunner == true) {	
					var legRunner = new models_LegRunner();
					legRunner.runnerId = oBet.runner.runnerId;
					legRunner.runnerName = oBet.runner.selection.name;
					legRunner.betId = oBet.betId;
					legRunner.price = oBet.price;
					marketLegs.addLegs(legRunner);		
					this.bets.setMarketLegs(marketAvailabilityIndex, marketLegs);
				}
			} else {
				var marketLegs = new models_MarketLegs();
				
				marketLegs.marketId = oBet.runner.marketId;
				marketLegs.marketName = oBet.MultMarketName;
				marketLegs.legId = iSize;
				marketLegs.legName = null;
				marketLegs.activeStatus = 'A';
				marketLegs.betType = oBet.bidType;

				var leg = new models_LegRunner();
				leg.runnerId = oBet.runner.runnerId;
				leg.runnerName = oBet.runner.selection.name;
				leg.betId = oBet.betId;
				leg.price = oBet.price;
				marketLegs.addLegs(leg);

				this.bets.addMarketLeg(marketLegs);
				iSize++;
				tmpMarketId[tmpMarketId.length] = marketLegs.marketId;
			}
		} else {
			var marketLegs = new models_MarketLegs();

			marketLegs.marketId = oBet.runner.marketId;
			marketLegs.marketName = oBet.MultMarketName;
			marketLegs.legId = iSize;
			marketLegs.legName = null;
			marketLegs.activeStatus = 'A';
			marketLegs.betType = oBet.bidType;

			var leg = new models_LegRunner();
			leg.runnerId = oBet.runner.runnerId;
			leg.runnerName = oBet.runner.selection.name;
			leg.betId = oBet.betId;			
			leg.price = oBet.price;			
			marketLegs.addLegs(leg);

			this.bets.addMarketLeg(marketLegs);
			iSize++;
			tmpMarketId[tmpMarketId.length] = marketLegs.marketId;
		}
	}
	
	/* Belinda 29/08/2008 - does nothing
	for (var iCnt = 0; iCnt < this.bets.getMarketLegsLength(); iCnt++) {
		var oMarketLegs = this.bets.getMarketLegs(iCnt);
		
		for (var iTmp = 0; iTmp < oMarketLegs.getLegLength(); iTmp++) {
			var legObj = oMarketLegs.getLeg(iTmp);
		}	
	}
	*/		
	
	this.setCurrentBet(thisBet);
	this.setToggleMVButtonStatus(true);
	this.placeBetsView.updateView(true);	
	// Added by Ash - to adjust the height of the placebet panel depending upon the number of legs choosen.	
	PlacebetsPanelHeight(this.bets);
	
}

function PlacebetsPanelHeight(bets){}

;controllers_PlaceBetsController.prototype.setCurrentBet = function(betObj) {	
	this.currentBet = betObj;
}

;controllers_PlaceBetsController.prototype.getCurrentBet = function() {
	return this.currentBet;
}

;controllers_PlaceBetsController.prototype.setToggleMVButtonStatus = function(toggleMVButton) {		
	this.toggleMVButton = toggleMVButton;	
}

;controllers_PlaceBetsController.prototype.getToggleMVButtonStatus = function() {
	return this.toggleMVButton;
}

;controllers_PlaceBetsController.prototype.ValidateConflicts = function(marketObj) {
	var arrDummyMarketContingencyComplete = new Array();
	arrDummyMarketContingencyComplete = betexUIGlobalSettings.conflictMarkets.split("^");
	var arrDummyMarketContingency = new Array(arrDummyMarketContingencyComplete.length); 

	for (var arrContigencyCtr=0; arrContigencyCtr < arrDummyMarketContingency.length ;arrContigencyCtr++)
	{
		var arrBuffer = new Array();
		arrBuffer = arrDummyMarketContingencyComplete[arrContigencyCtr].split("|");
		arrDummyMarketContingency[arrContigencyCtr] = new Array(arrBuffer[0], arrBuffer[1], arrBuffer[2]);
	}

	for (var i =0;i<arrDummyMarketContingency.length;i++)
	{
		// Browse through the array only if the group is same as the current group being viewed
		if(marketObj.groupId == arrDummyMarketContingency[i][0])
		{
			if ( (marketObj.multId == arrDummyMarketContingency[i][1]) || (marketObj.multId == arrDummyMarketContingency[i][2]) )	// The current market entry is present in the contingency list
			{
				// Check the adjacent market id  for which an entry is made in the contingency list to prevent such "place bets"
				// Check if the adjacent market id is already a part of the multiple bet selection
	
				// Browse through the Placed bets collection
				for (var ctrBets=0; ctrBets < this.bets.length(); ctrBets++)
				{
					if (this.bets.length() > 0)
					{
						nbet = this.bets.get(ctrBets);	
					
	
						// Checking if the conflicting market entry in the DB is already selected.
						// checking if Market A = Market B as per the database entry.
						if (marketObj.multId == arrDummyMarketContingency[i][1])
						{
						
							if (arrDummyMarketContingency[i][2] == nbet.multId)
							{
								return false;
							}
						}
	
						// checking if Market B = Market A as per the database entry(reverse of above).
						if (marketObj.multId == arrDummyMarketContingency[i][2])
						{
							if (arrDummyMarketContingency[i][1] == nbet.multId )
							{
								return false;
							}
						}
					}
				}
			}
		}
	}
	return true;

}

;controllers_PlaceBetsController.prototype.ZeroMarketWinnerHideShowBetType = function(market, bidType, oddsVisiblity, oddsAvailablity, runnerId) {
	for (var runnersCtr=0; runnersCtr < market.runners.length(); runnersCtr++) {
		if(market.runners.items[runnersCtr].runnerId != runnerId) {
    		document.getElementById("OddsMVLayButton_" + market.runners.items[runnersCtr].runnerId).style.visibility = oddsVisiblity;
			document.getElementById("MVLayButton_" + market.runners.items[runnersCtr].runnerId).disabled = oddsAvailablity;
    		document.getElementById("OddsMVBackButton_" + market.runners.items[runnersCtr].runnerId).style.visibility = oddsVisiblity;
			document.getElementById("MVBackButton_" + market.runners.items[runnersCtr].runnerId).disabled = oddsAvailablity;
		}
	}
}

;controllers_PlaceBetsController.prototype.HideShowAlternateBetType = function(marketId, pageData, oddsVisiblity, oddsAvailablity, runnersObj) {

	for (var x = 0; x< runnersObj.length(); x++){
		runnerId = runnersObj.get(x).runnerId;
		
		if(pageData == models_BidType.BACK){			
			document.getElementById("MVCouponLayButton_" + marketId + "_"+ runnerId).childNodes.item(0).style.visibility = oddsVisiblity;
			document.getElementById("MVCouponLayButton_" + marketId + "_"+ runnerId).disabled = oddsAvailablity;		
		}
		
		if(pageData == models_BidType.LAY){
			document.getElementById("MVCouponBackButton_" + marketId + "_"+ runnerId).childNodes.item(0).style.visibility = oddsVisiblity;
			document.getElementById("MVCouponBackButton_" + marketId + "_"+ runnerId).disabled = oddsAvailablity;
		
		}
	
		if(!pageData || pageData == ""){
			document.getElementById("MVCouponLayButton_" + marketId + "_"+ runnerId).childNodes.item(0).style.visibility = oddsVisiblity;
			document.getElementById("MVCouponLayButton_" + marketId + "_"+ runnerId).disabled = oddsAvailablity;
			
			document.getElementById("MVCouponBackButton_" + marketId + "_"+ runnerId).childNodes.item(0).style.visibility = oddsVisiblity;
			document.getElementById("MVCouponBackButton_" + marketId + "_"+ runnerId).disabled = oddsAvailablity;		
		}
	
	}
}

;controllers_PlaceBetsController.prototype.SingleMarketHideShowAlternateBetType = function(marketId, pageData, oddsVisiblity, oddsAvailablity, runnersObj) {
	for (var x = 0; x< runnersObj.length(); x++){
		runnerId = runnersObj.get(x).runnerId;
		
		if(pageData == models_BidType.BACK){			
			document.getElementById("OddsMVLayButton_" + runnerId).style.visibility = oddsVisiblity;
			document.getElementById("MVLayButton_" + runnerId).disabled = oddsAvailablity;		
		}
		
		if(pageData == models_BidType.LAY){
			document.getElementById("OddsMVBackButton_" + runnerId).style.visibility = oddsVisiblity;
			document.getElementById("MVBackButton_" + runnerId).disabled = oddsAvailablity;
		
		}
	
		if(!pageData || pageData == ""){
			document.getElementById("OddsMVLayButton_" + runnerId).style.visibility = oddsVisiblity;
			document.getElementById("MVLayButton_" + runnerId).disabled = oddsAvailablity;	
			
			document.getElementById("OddsMVBackButton_" + runnerId).style.visibility = oddsVisiblity;
			document.getElementById("MVBackButton_" + runnerId).disabled = oddsAvailablity;		
		}
	
	}
}
;controllers_PlaceBetsController.prototype.validateSingleOrMultipleWinnerMarkets = function(betsLength, runnersLength, duplicatedBet, numberOfWinners, bets, marketObj, couponView){
		// Condition to check - All runners cannot be selected for a market.
		var selectedRunnerPerMarketCount=0;
		
		if( ((betsLength >= runnersLength -1 ) && !(duplicatedBet)) || ((numberOfWinners > 1) && !(duplicatedBet) ) )
		{
			// Check in the selected legs if they belong to the same market
			if (betsLength > 0)
			{
				for (var selectedRunnerPerMarketCountCtr=0; selectedRunnerPerMarketCountCtr < betsLength ;selectedRunnerPerMarketCountCtr++)
				{
					betDetails = bets.get(selectedRunnerPerMarketCountCtr).toString();
					betDetailsArray = betDetails.split("\t");
					if (betDetailsArray[9] == marketObj.marketId)
					{
						// If a runner was selected for the current market, increment the count by 1
						selectedRunnerPerMarketCount = selectedRunnerPerMarketCount + 1;
						if(couponView){
							numberOfWinners = marketObj.numberOfWinners;
						}
					}
				}
			}

			if(numberOfWinners > 1)
			{
				// Condition to check if the current market is a multiple winner market. If yes, then allow only one selection in the market
				if (selectedRunnerPerMarketCount > 0 )
				{
					alert(multipleSelectionsForZeroOrMultMarket);
					return false;
				}					
			}
			else
			{
				// Checking if all runners are not selected in a single winner market. If yes, prevent it.
				if (selectedRunnerPerMarketCount >= marketObj.runners.length() -1 )
				{
					alert(oddsNoAllSelectionAlert);
					return false;
				}
			}
		}
		return true;
}
// Modded this to return the index if found - rather than a boolean
;controllers_PlaceBetsController.prototype.checkAvailability = function(marketArray, marketid){
	var marketIndex = DEFAULT_MARKET_INDEX;	
	for (var iTmpCnt=0;iTmpCnt<marketArray.length;iTmpCnt++){
		if (marketid == marketArray[iTmpCnt]){
			marketIndex = iTmpCnt;
			break;
		}
	}	
	return marketIndex;
}

;controllers_PlaceBetsController.prototype.placeMultipleBets = function(bidType, currentlySelectedCouponStakeValue){
	if(this.placeBetsView.currentState == controllers_PLACE_BETS_PROCESSING_VIEW) {
		return;
	}
	if(this.market.isSuspended) {
		return alert(sKey_AlertSuspended);
	}
	var market = (this.market instanceof models_Coupon)? this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId) : this.market;
	for (var i=0;i<market.runners.length();i++){
		var thisRunner = market.runners.get(i);
		if(thisRunner.vacant == false || thisRunner.vacant == null){
			if(this.bets.getBetByRunnerIdAndBidType(thisRunner.runnerId, bidType) == false){
				var thisBet = new models_Bet();
				thisBet.betStatus = models_BetStatusEnum.POTENTIAL;
				var betIndex = (bidType == models_BidType.BACK)?2 : 3;
				thisBet.runner = thisRunner;
				thisBet.bidType = bidType;
				if(this.market instanceof models_Coupon){
					if(thisRunner.bets.get(betIndex) != null){
						thisBet.setPrice((this.user.preferences.couponOddsDisplay == models_CouponOddsView.AVERAGE)? (thisRunner.bets.get(betIndex).couponAveragePrice)? thisRunner.bets.get(betIndex).couponAveragePrice : thisRunner.bets.get(betIndex).getPrice(): thisRunner.bets.get(betIndex).getPrice());
					}
					thisBet.setSize(currentlySelectedCouponStakeValue);
				}else{
					if(thisRunner.bets.get(betIndex) != null) {
						thisBet.setPrice(thisRunner.bets.get(betIndex).getPrice());
					}
				}
				var node;
				if (this.market instanceof models_Coupon) {
					node = (bidType == models_BidType.BACK)? "MVCouponBackButton_" + market.marketId + "_" + thisRunner.runnerId : "MVCouponLayButton_" + market.marketId + "_" + thisRunner.runnerId;
				} else {
					node = (bidType == models_BidType.BACK)? "MVBackButton_" + thisRunner.runnerId : "MVLayButton_" + thisRunner.runnerId;
				}
				thisBet.multId = this.market.multId;
				thisBet.attachParentBetDOMReference(node);
				this.bets.add(thisBet);
			}
		}
	}
	this.placeBetsView.updateView(true);
}

;controllers_PlaceBetsController.prototype.applyPayoutLiability = function(){
	var payouLiability = document.getElementById("BMPayoutLiabilityAmount").value;
	if(isNaN(payouLiability)){
		alert(sKey_NANReturnAlert);
		document.getElementById("BMPayoutLiabilityAmount").value = "";
	}else{
		var market = (this.market instanceof models_Coupon)? this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId) : this.market;
		var bAnyErrors = false;
		for (var i=0;i<this.bets.length();i++){
			var oBet = this.bets.get(i);
			if(oBet.bidType != models_BidType.BACK){
				if (oBet.applyPayoutLiability(this.user.preferences.liabilityView, payouLiability, market.getMinimumOddsIncrement(), (i==this.bets.length()-1 && bAnyErrors) ? true : false )) {
					bAnyErrors = true;
				}
				this.placeBetsView.updateBetProfit(oBet);
			}
		}
	}
	this.calculateLiability();
}

;controllers_PlaceBetsController.prototype.calculateLiability = function(forceProfitAndLossRepaint){
	var market = (this.market instanceof models_Coupon)? this.market.markets.getMarketByMarketId(this.currentlySelectedCouponMarketId) : this.market;
	if(market.betType != "Odds") {	
		return;
	}
	
	// Loop through Place array and put values into place
	for (var i=0;i<this.bets.length();i++){
		var oBet = this.bets.get(i);
		var liabilityItem = this.liabilityItems.getLiabilityItemByRunnerId(oBet.runner.runnerId);
		if(oBet.bidType == models_BidType.BACK){
			liabilityItem.backStakeLiability = (0- oBet.getSize());
		}else{
			liabilityItem.layPrice = oBet.getPrice();
			liabilityItem.laySize = oBet.getSize();
		}
	}
	// This array prepares the Advanced Profit and Loss calculator with the correct bets.
	var advancedProfitAndLossBets = new models_Bets();
	if(!(this.market instanceof models_Coupon)){
		for (var j=0;j<this.bets.length();j++){
			var oBet = this.bets.get(j);
			if (oBet.getSize() != null && oBet.getPrice() != null) {
				advancedProfitAndLossBets.add(oBet)
			}
		}
	}
	// Loop through and create individual liability
	for (var i=0;i<this.liabilityItems.length();i++){
		var oItem = this.liabilityItems.get(i);
		if((oItem.layPrice != 0) && (oItem.laySize != 0)){
			oItem.layLiability = (0-((oItem.layPrice - 1) * oItem.laySize));
		}
		if(oItem.backStakeLiability != 0){
			oItem.individualProfitAndLoss = oItem.layLiability - oItem.backStakeLiability;	// Lay - Back Liab
		}else{
			oItem.individualProfitAndLoss = oItem.layLiability;	// Lay only Liab
		}
		oItem.flag = 0;

	
		if(this.oPAndLAnnotations != null && !(this.market instanceof models_Coupon)){

/********************** Advanced Profit and Loss Calculator *************************************************/

			var iSelID, iBetSelID, dBackWin, dLayLose, dOdds, dStake, backLay, bValidMatched, sHtmlPL, dPL, dCurrentPL;
			var returnArray = new Array();
		
			iSelID = oItem.runner.selectionId;
			dBackWin = 0;
			dLayLose = 0;
			bValidMatched = false;			
			for (var j=0;j<advancedProfitAndLossBets.length();j++){
				iBetSelID = advancedProfitAndLossBets.get(j).runner.selectionId;
				backLay = (advancedProfitAndLossBets.get(j).bidType == models_BidType.BACK);
				dOdds = Number(advancedProfitAndLossBets.get(j).getPrice());
				dStake = Number(advancedProfitAndLossBets.get(j).getSize());
				
				if(isNaN(dOdds) || isNaN(dStake)) {
					return;
				}
				
				if ((dStake != null) && (dOdds != null)) {
					dOdds-=1;
					if (oItem.runner.market.numberOfWinners == 1) {
						bValidMatched = true;
						if (backLay) {
							dBackWin+=(iBetSelID==iSelID?(dOdds*dStake):(dStake*-1));
						} else {
							dLayLose+=(iBetSelID==iSelID?(-1*dOdds*dStake):dStake);
						}
					} else {
						if (iBetSelID == iSelID) {
							bValidMatched = true;
							if (backLay) {
								dBackWin+=dOdds*dStake;
								dLayLose-=dStake;
							} else {
								dBackWin-=dOdds*dStake;
								dLayLose+=dStake;
							}
						}
					}
				}
			}		
			if(advancedProfitAndLossBets.length() > 0){
				if (oItem.runner.market.numberOfWinners == 1) {				
					var oPAndLAnnotation = this.oPAndLAnnotations.getProfitAndLossBySelectionId(oItem.runner.selectionId)
					if(oPAndLAnnotation != null && oPAndLAnnotation.profitLoss != null){
						if (oPAndLAnnotation.profitLoss >= 0){
							dCurrentPL = (oPAndLAnnotation.profitLoss)? oPAndLAnnotation.profitLoss : 0;
						}else{
							dCurrentPL = (oPAndLAnnotation.profitLoss)? oPAndLAnnotation.profitLoss : 0;
						}
					}else{
						dCurrentPL = 0;
					}
					dPL = dBackWin + dLayLose;
					dPL = Number(dPL) + dCurrentPL;
					this.placeBetsView.updateRunnerFuturePAndL(oItem.runner, dPL, null, null, forceProfitAndLossRepaint);					
				} else {				
					var oPAndLAnnotation = this.oPAndLAnnotations.getProfitAndLossBySelectionId(oItem.runner.selectionId)
					dCurrentPL = (oPAndLAnnotation.profitLoss)? oPAndLAnnotation.profitLoss : 0;
					dProfit = (oPAndLAnnotation.profit)? oPAndLAnnotation.profit : 0;
					dLoss = (oPAndLAnnotation.loss)? oPAndLAnnotation.loss : 0;
					dBackWin = (dProfit == null)? dBackWin : dBackWin + dProfit;
					dLayLose = (dLoss == null)? dLayLose : dLayLose + dLoss;
					if ((dBackWin==0) && (dLayLose==0)){
						this.placeBetsView.updateRunnerFuturePAndL(oItem.runner, null, null, null);
					}else {
						this.placeBetsView.updateRunnerFuturePAndL(oItem.runner, null, dBackWin, dLayLose, forceProfitAndLossRepaint);
					}
				}
			}else{				
				this.placeBetsView.updateRunnerFuturePAndL(oItem.runner, null, null, null, forceProfitAndLossRepaint);
			}
		}
/*************************************************************************/
	}
	var iExposure = 0;
	var iPos, iWorse;
	var numberOfItemsToSum = (market.numberOfWinners == 0)? this.liabilityItems.length()-1 : market.numberOfWinners;
	
	for (var i=0;i<numberOfItemsToSum;i++){
		iPos = -1;
		iWorse = 0;
	
		for (var k=0;k<this.liabilityItems.length();k++){
			var oItem = this.liabilityItems.get(k);
			if((oItem.individualProfitAndLoss < iWorse) && (oItem.flag == 0)){
				iWorse = oItem.individualProfitAndLoss;
				iPos=k;
			}
		}
		if (iPos>-1) {
			this.liabilityItems.get(iPos).flag = 1;
		}
	}
	
	for (var i=0;i<this.liabilityItems.length();i++){
		var oItem = this.liabilityItems.get(i);
		oItem.exposure = (oItem.layLiability * oItem.flag) + ((1 - oItem.flag) * oItem.backStakeLiability);
		iExposure = iExposure +oItem.exposure;
	}
	this.placeBetsView.updateLiabilityTotals(iExposure);
}

;controllers_PlaceBetsController.prototype.cancelAllPlaceBets = function(){
	var iSize = this.bets.getMarketLegsLength();
	for (var iCnt=0;iCnt<iSize;iCnt++)
	{
		this.deletePlaceBet(this.bets.marketLegsCollection[0].marketId);
	}
	
	// Added by Ash to set the border of placebets sections to 0 when there is no more bets in the collection.
	this.bets.empty();
	document.getElementById("clearAll").disabled=true;
	document.getElementById("placeBetsTable").setAttribute("border", "0");	
    betexUIGlobalSettings.multipleBetType = models_BidType.BACK;
    if (document.getElementById("optMultiple_B") != null){
	    document.getElementById("optMultiple_B").checked = true;
	}
	
	// State is set as the current bets view can be reset/cancelled from verify bets screen.
	this.placeBetsView.setState(controllers_PLACE_BETS_DEFAULT_VIEW);
	this.placeBetsView.buildBetItems();
	
	// Added by Ash - to adjust the height of the placebet panel depending upon the number of legs choosen.
	PlacebetsPanelHeight(this.bets);
	betexUIController.setPlaceBetPreCondition(true);
}

;controllers_PlaceBetsController.prototype.deletePlaceBet = function(marketId){
	var marketIndex = '';
	var noOfMarket = 1;
	var noOfStake = 1;
	var marketObj;
	
		for (var iCnt=0;iCnt<this.bets.getMarketLegsLength();iCnt++){
			var oMarketLegs = this.bets.getMarketLegs(iCnt);
			if (marketId == oMarketLegs.marketId){
				marketIndex = iCnt;
				break;
			}
		}	
		// This section is for hiding the other bid types when a bid type is selected
		// Loop the count the number of selected runners for the current market. 
		var selectedRunnerPerMarketCount=0;
		var selectedRunnersInSelectedMarket=0;
		var betDetailsArray = new Array();
		var betDetails;
		var marketBets = this.bets.getBetsByMarketId(marketId);
		
		if(marketBets){
			for (var x = 0; x < marketBets.length; x++){				
				try {								
					betexUIController.marketViewController.marketView.setMarketViewButtonToggleClass(marketBets[x].attachedParentDOMReference);
				} catch(y){								
					try{					
						betexUIController.marketViewController.marketView.setMarketViewButtonToggleClass(marketBets[x].attachedMarketInfoDOMReference);
					} catch(z){						
						continue;
					}
				}
			}
		}
		this.setToggleMVButtonStatus(false);
		// Be defensive here - and if any errors occur wipe out everything to prevent the chance of inconsistent data see Jira MLT-101
		try {
			this.updateMarket(marketIndex, noOfMarket);		
			var marketLength = this.bets.getMarketLegsLength();
			this.updateBetinBets(oMarketLegs);
		}catch(ex){
			this.cancelAllPlaceBets();
			alert(sKey_MyBetsErrorDeletingBetsText);
		}  					
		this.placeBetsView.updatePlaceBetCount(marketLength);		
		this.placeBetsView.removePlaceBet(marketIndex);
		
		for (var selectedRunnerPerMarketCountCtr=0; selectedRunnerPerMarketCountCtr < this.bets.length() ;selectedRunnerPerMarketCountCtr++)
		{
			betDetails = this.bets.get(selectedRunnerPerMarketCountCtr).toString();
			betDetailsArray = betDetails.split("\t");
			if (betDetailsArray[9] == marketId)
			{
				// If a runner was selected for the current market, increment the count by 1
				selectedRunnersInSelectedMarket = selectedRunnersInSelectedMarket + 1;
			}
		}	
		// Enable other bet buttons if there are NO selected runners in the selected market.
		if (selectedRunnersInSelectedMarket == 0)
		{			
			if(this.market instanceof models_Coupon)
			{	
				marketObj = this.market.markets.getMarketByMarketId(marketId);			
				try{						
					this.HideShowAlternateBetType(marketId, "", 'visible', false, marketObj.runners);
				} catch(x){
				
				}
			}
			else
			{	
				marketObj = this.market;				
				if(marketObj.marketId == marketId)	{
					this.SingleMarketHideShowAlternateBetType(marketId, "", 'visible', false, marketObj.runners);
				}
			}
		}		
		// Section to handle zero-winners market section.
		var ZeroMarketFlag = false;
		if (ZeroMarketFlag)
		{
			this.ZeroMarketWinnerHideShowBetType(this.market, '', 'visible', false, bet.runner.runnerId);
		}
		
		this.bets.deleteStakeCollection((marketLength-1), noOfMarket);
		this.placeBetsView.calculateMarketChoiceStakes();

	// Added by Ash - to adjust the height of the placebet panel depending upon the number of legs choosen.
	PlacebetsPanelHeight(this.bets);

}

;controllers_PlaceBetsController.prototype.updateMarket = function(marketIndex, noOfMarket){
	this.bets.deleteMarketLegs(marketIndex, noOfMarket);
}

;controllers_PlaceBetsController.prototype.updateBetinBets = function(marketLeg){
	for (var iCnt=0;iCnt<marketLeg.getLegLength();iCnt++){
		var legRunner = marketLeg.getLeg(iCnt);
		var legId = legRunner.runnerId;
			for (var i=0;i<this.bets.length();i++){
				var oBet = this.bets.get(i);
				if (oBet.runner.runnerId == legId){
					this.bets.deleteBet(i);
					break;
				}
			}
	}
}

;controllers_PlaceBetsController.prototype.deleteBet = function(bet, marketId, view, marketObj, viewType){	
	var betIndex;
	var noOfMarket = 1;
	var marketObj;

	for (var i=0;i<this.bets.length();i++){
		if(this.bets.get(i).runner.runnerId == bet.runner.runnerId && bet.bidType == this.bets.get(i).bidType){
			betIndex = i;
			this.bets.get(i).viewType = viewType;
			break;
		}
	}
	
	this.updatePlaceBetsModel(betIndex);
	this.setToggleMVButtonStatus(false);
	this.placeBetsView.removeBet(betIndex);
	this.bets.deleteBet(betIndex);
	var marketLength = this.bets.getMarketLegsLength();
	this.bets.deleteStakeCollection((marketLength-1), noOfMarket);
	this.placeBetsView.calculateMarketChoiceStakes();	
	
	// This section is for hiding the other bid types when a bid type is selected
	// Loop the count the number of selected runners for the current market. 
	var selectedRunnerPerMarketCount=0;
	var selectedRunnersInSelectedMarket=0;
	var betDetailsArray = new Array();
	var betDetails;
	
	for (var selectedRunnerPerMarketCountCtr=0; selectedRunnerPerMarketCountCtr < this.bets.length() ;selectedRunnerPerMarketCountCtr++)
	{
		betDetails = this.bets.get(selectedRunnerPerMarketCountCtr).toString();
		betDetailsArray = betDetails.split("\t");
		if (betDetailsArray[9] == marketId)
		{
			// If a runner was selected for the current market, increment the count by 1
			selectedRunnersInSelectedMarket = selectedRunnersInSelectedMarket + 1;
		}
	}

	// Enable other bet buttons if there are NO selected runners in the selected market.
	if (selectedRunnersInSelectedMarket == 0)
	{		
		if(view)
		{	
			marketObj = this.market.markets.getMarketByMarketId(marketId);		
			this.HideShowAlternateBetType(marketId, "", 'visible', false, marketObj.runners);
		}
		else
		{
			marketObj = this.market;
			if(marketObj.marketId == marketId){
				this.SingleMarketHideShowAlternateBetType(marketId, "", 'visible', false, marketObj.runners);
			}
		}
	}
	
	// Section to handle zero-winners market section.
	var ZeroMarketFlag = false;
	if (ZeroMarketFlag)
	{
		this.ZeroMarketWinnerHideShowBetType(this.market, '', 'visible', false, bet.runner.runnerId);
	}
	
	// Added by Ash - to adjust the height of the placebet panel depending upon the number of legs choosen.
	PlacebetsPanelHeight(this.bets);
	
}

;controllers_PlaceBetsController.prototype.updatePlaceBetsModel = function(betIndex){
	var bet = this.bets.get(betIndex);	
	var legId = bet.runner.runnerId;
	var legName = bet.runner.selection.name;
	var marketId = bet.runner.marketId;
	var marketName = bet.MultMarketName;
	var legSize = 0;
	var marketIndex = 0;
	var marketSize = 0;
	
	for (var iCnt=0; iCnt < this.bets.getMarketLegsLength(); iCnt++){
		var oMarketLegs = this.bets.getMarketLegs(iCnt);
		var oMarketId = oMarketLegs.marketId;
				
		if (oMarketId == marketId){

			for (var iTemp=0;iTemp<oMarketLegs.getLegLength();iTemp++){
				var oLeg = oMarketLegs.getLeg(iTemp);
				var oLegId = oLeg.runnerId;
				
				if (oLegId == legId){
					var otemp = oMarketLegs.deleteLeg(iTemp , 1);
					legSize = oMarketLegs.getLegLength();					
					marketIndex = iCnt;
					break;
				}
			}
			
			break;
		}
	}
	
	if (legSize == 0){
		this.updateMarket(marketIndex, 1);
	}
}

;controllers_PlaceBetsController.prototype.deleteMultipleBet = function(bet){
	var betIndex;

	for (var i=0;i<this.bets.length();i++){
		if(this.bets.get(i).runner.runnerId == bet.runner.runnerId && bet.bidType == this.bets.get(i).bidType){
			betIndex = i;
			break;
		}
	}
	
	var liabilityItem = this.liabilityItems.getLiabilityItemByRunnerId(this.bets.get(i).runner.runnerId);
	
	if(bet.bidType == models_BidType.BACK){
		liabilityItem.backStakeLiability = 0;
	}else{
		liabilityItem.layPrice = 0;
		liabilityItem.laySize = 0;
		liabilityItem.layLiability = 0;
	}
	
	liabilityItem.individualProfitAndLoss = 0;
	liabilityItem.flag = 0;
	liabilityItem.exposure = 0;
	
	this.placeBetsView.removeMultipleBet(bet, betIndex);
	this.placeBetsView.updateView();
	this.updatePercentBookView();
}

;controllers_PlaceBetsController.prototype.deleteMultipleFoldBet = function(betFoldId, trId){
	var betFold;

	for (var i=0;i<this.bets.betFoldLength();i++)
	{
			betFold = this.bets.betFoldGet(i);
			// Added by Ash to manuplate bet collection for stakes > 0
			if (betFold.selectionId == betFoldId)
			{
				break;
			}
	}
	
	this.placeBetsView.removeMultipleBet(betFold, trId);

}

;controllers_PlaceBetsController.prototype.attachMarketViewDOMReference = function(bet, DOMObject){
	bet.parentDOMItem = DOMObject;
}

;controllers_PlaceBetsController.prototype.submitBets = function(frm){
	bStakeExceedsAvailableAlertShown = false;
	var alertExceptionsHaveBeenThrown = false;	
	
	var multiple = '';
	var legIds = '';
	var marketIds = '';
	var originalmarketIds = '';
	var legBidTypes = '';
	var spBetTypes = '';
	var runnerIds = '';
	var originalRunnerIds = '';
	var runnerOdds = '';
	var stakes = '';
	
	frm.action = "/multiples/betting/LoadIndicativeBetPricesAction.do";
	
	//Hiding Buttons & displaying View Bets Message		
	betexUIController.betManagerController.hideViewBetsButtonsAndShowMessage();
	
	//Populate the form variables for Market from the javascript values
	for (var iCnt=0;iCnt<this.bets.getMarketLegsLength();iCnt++){
		
		var currMarket = this.bets.getMarketLegs(iCnt);
		var currMarketId = currMarket.marketId;
		var marketName = currMarket.marketName;
		var legId = currMarket.legId;
		var legName = currMarket.legName;	
		var bidType = currMarket.betType;
		var SPType = 'N';
		
		if (iCnt == this.bets.getMarketLegsLength()-1) {
			legIds += legId;
			marketIds += currMarketId;
			originalmarketIds += currMarketId;
			legBidTypes += bidType;
		} else {
			legIds += legId + '|';
			marketIds += currMarketId + '|';
			originalmarketIds += currMarketId + '|';
			legBidTypes += bidType + '|';
		}

		//To load the Piping Symbol for every iteration		
		if (iCnt != 0) {
			runnerIds += '|';
			originalRunnerIds += '|';
			runnerOdds += '|';
		}
		
		for (var iTmp = 0; iTmp < currMarket.getLegLength(); iTmp++) {
			var legObj = currMarket.getLeg(iTmp);
				
			if (iTmp == currMarket.getLegLength() - 1) {
				runnerIds += legObj.runnerId;
				originalRunnerIds += legObj.runnerId;
				runnerOdds += legObj.price;
			} else {
				runnerIds += legObj.runnerId + '&';
				originalRunnerIds += legObj.runnerId + '&';
				runnerOdds += legObj.price + '&';					
			}				
		}
	}

	//Populate the form variables for Multiple options from the javascript values
	for (var iCnt = 0; iCnt < frm.optMultiple.length; iCnt++) {
	   if (frm.optMultiple[iCnt].checked == true){
	     multiple = frm.optMultiple[iCnt].value;
	   }
	}

	//Added the following code to loop thru the stakes for folds and if any is blank then 0 it.
	//Populate the form variables: stake from the stakes collection
	for (var iCnt=this.bets.getStakeCollectionLength()-1;iCnt>=0;iCnt--){
		var tmpFormatStakes = this.bets.getStake(iCnt);
		if  ( ( tmpFormatStakes == "" ) || isNaN(tmpFormatStakes) ){
			tmpFormatStakes = 0;
			this.bets.setStake(iCnt, tmpFormatStakes);
		}
		
		if (iCnt == 0){
			stakes = stakes + tmpFormatStakes;
			spBetTypes = spBetTypes + SPType;
		} else {
			stakes = stakes + tmpFormatStakes + '|';
			spBetTypes = spBetTypes + SPType + '|';
		}
	}
  
	frm.multipleCombinationBidType.value = multiple;	
	frm.multipleCombinationGroupID.value = this.bets.get(0).groupId;
	frm.originalMarketIDs.value = marketIds;
	frm.multipleLegBidTypes.value = legBidTypes;
	frm.spBetTypes.value = spBetTypes;
	frm.originalRunnerIDs.value = runnerIds;
	frm.runnersOdds.value = runnerOdds;
	frm.attemptedStakes.value = stakes;
	frm.betQuoteId.value = getBetQuoteId();
	window.frames['placeBetsManager'].location = "/multiples/betting/MarketView.do?id=pb";	    
    
    if(frm.optMultiple[0].checked) {
        betexUIGlobalSettings.multipleBetType = models_BidType.BACK;
    } else {
         betexUIGlobalSettings.multipleBetType = models_BidType.LAY;
    }
    
	betexUIController.setPlaceBetPreCondition(false);
		
	frm.submit();		
}


;controllers_PlaceBetsController.prototype.submitVerifiedBets = function(user){	
	bStakeExceedsAvailableAlertShown = false;
	this.placeBetsView.submitVerifiedBets();

}

;controllers_PlaceBetsController.prototype.cancelVerifiedBets = function(user){
	this.placeBetsView.cancelVerifiedBets();
	// Added by Ash to remove/show the appearance of Back / Lay multiples radio buttons depending upon Express view or Enhanced view
	
	if (this.user.preferences.multiplesUIView == constants_UI_VIEW_COMPACT) {
		document.getElementById("BMPlaceBetsRadioRow").style.display = "none";
	} else {
		document.getElementById("BMPlaceBetsRadioRow").style.display = "block";
	}

	if (isMozilla()) {
		this.placeBetsView.buildBetMarketChoice();
		this.placeBetsView.calculateMarketChoiceStakes();
	}
	PlacebetsPanelHeight(this.bets);
}

;controllers_PlaceBetsController.prototype.setBetPlacementResults = function(bets, betResults){
	this.confirmedBets = bets;
	this.confirmedBetResults = betResults;
	if(betResults.get(0).errorCode == controllers_STAKE_EXCEEDED_EXPOSURE || betResults.get(0).errorCode == controllers_STAKE_EXCEEDED_LOSS_LIMIT){
		if (!bStakeExceedsAvailableAlertShown){
			alert(stakeExceedsAvailable);
			bStakeExceedsAvailableAlertShown = true;
		}
		this.placeBetsView.setBetPlacementToOriginal()
	}else{
		this.placeBetsView.setBetPlacementResults(bets, betResults);
		for (var i=0;i<this.bets.length();i++){
			var liabilityItem = this.liabilityItems.getLiabilityItemByRunnerId(this.bets.get(i).runner.runnerId);
			if(this.bets.get(i).bidType == models_BidType.BACK){
				liabilityItem.backStakeLiability = 0;
			}else{
				liabilityItem.layPrice = 0;
				liabilityItem.laySize = 0;
				liabilityItem.layLiability = 0;
			}
			liabilityItem.individualProfitAndLoss = 0;
			liabilityItem.flag = 0;
			liabilityItem.exposure = 0;
			this.placeBetsView.removeBet(i);
			this.bets.deleteBet(i);
			i--;
		}
	}
	this.placeBetsView.updateLiabilityTotals(0);
	this.calculateLiability();
}

;controllers_PlaceBetsController.prototype.throwBetPlacementException = function(alertStr){
	alert(alertStr);
	this.placeBetsView.throwBetPlacementException();
}

;controllers_PlaceBetsController.prototype.throwBetCancelationException = function(alertStr){
	alert(alertStr);
	this.placeBetsView.throwBetCancelationException();
}

;controllers_PlaceBetsController.prototype.cancelConfirmedBet = function(betId){
	var bet = this.confirmedBets.getBetByBetId(betId);
	var betResult = this.confirmedBetResults.getBetByBetId(betId);
	this.placeBetsView.cancelConfirmedBet(bet, betResult);
}

;controllers_PlaceBetsController.prototype.setBetCancelationResults = function(bets, betResults){
	this.placeBetsView.setBetCancelationResults(bets, betResults);
}

;controllers_PlaceBetsController.prototype.setLayBetsLiabilityView = function(){
	this.placeBetsView.setLayBetsLiabilityView();
}

;controllers_PlaceBetsController.prototype.setBetEditingResults = function(bets, betResults){

}

;controllers_PlaceBetsController.prototype.confirmBetsContinue = function(){
	this.confirmedBets = null;
	this.confirmedBetResults = null;
	this.placeBetsView.confirmBetsContinue();
	this.placeBetsView.updateView();
}

;controllers_PlaceBetsController.prototype.setUserPreferences = function(user){
	this.user = user;
	this.placeBetsView.setUserPreferences(user);
}

;controllers_PlaceBetsController.prototype.loadMultipleBets = function(stakeList, foldsList, bidTy){
	this.bets.setUpdatedStakeCollection(stakeList);
	this.bets.setFoldsCollection(foldsList);
	this.bets.bidSelectedType = bidTy;
	this.placeBetsView.drawBetSelection();
	this.placeBetsView.submitMultipleBets();
}

;controllers_PlaceBetsController.prototype.updateStake = function(obj){
	var regexp = /[^\d\.]+/g;
	if(!regexp.test(obj.value)){
		regexp = /[0-9]*\.[0-9]{3}/;
		if(regexp.test(obj.value)){
			obj.value = obj.value.substring(0, obj.value.length -1);
		}

		this.bets.setStake(obj.name, ""+DoRnd(parseFloat(""+obj.value),2));
		this.placeBetsView.calculateMarketChoiceStakes();
	} else {
		obj.value = obj.value.replace(regexp,'');
	}
}

;controllers_PlaceBetsController.prototype.betSelectionRadio = function(betValue){
	this.placeBetsView.updateBetSelection(betValue);
	//PlacebetsPanelHeight(this.bets);
}

/**
* My Bets Controller
*/

function controllers_MyBetsController(marketViewHandle){
	this.market = null;
	this.user = null;
	
	this.confirmedBets = null;
	this.confirmedBetResults = null;
	
	this.currentlySelectedCouponMarketId = null;
	
	this.bets = new models_Bets();
	this.myBetsView = new views_MyBetsView(marketViewHandle);
	this.myBetsHelper = new controllers_BetsHelperController(this.bets);
}

;controllers_MyBetsController.prototype.setMarket = function(market){
	this.market = market;
	this.myBetsView.setMarket(market);
	this.myBetsHelper.setMarket(market);
}

;controllers_MyBetsController.prototype.setLoadingState = function(market){
	this.myBetsView.setLoadingState()
}

;controllers_MyBetsController.prototype.setActiveCouponMarket = function(marketId){
	if(this.currentlySelectedCouponMarketId == marketId) {
		return;
	}
	this.currentlySelectedCouponMarketId = marketId;
	this.myBetsHelper.setActiveCouponMarket(marketId);
	this.myBetsView.setActiveCouponMarket(marketId);
}

;controllers_MyBetsController.prototype.resetMarket = function(){
	this.currentlySelectedCouponMarketId = null;
	this.myBetsView.resetMarket();
	this.bets.empty();
}

;controllers_MyBetsController.prototype.setUserPreferences = function(user){
	this.user = user;
	this.myBetsView.setUserPreferences(user);
}

;controllers_MyBetsController.prototype.deleteBet = function(bet){
	this.myBetsView.deleteBet(bet);
}

;controllers_MyBetsController.prototype.submitMyBets = function(){
	var alertExceptionsHaveBeenThrown = false;
	var bBypassCountDown = true;
	for (var i=0;i<this.bets.length();i++){
		var oBet = this.bets.get(i);
		if(oBet.betStatus == models_BetStatusEnum.UNMATCHED){
			var checkPrice = this.myBetsHelper.checkPrice(oBet, oBet.getDOMReferencesForMyBet().childNodes.item(2).childNodes.item(0), true);
			var checkSize = this.myBetsHelper.checkSize(oBet, oBet.getDOMReferencesForMyBet().childNodes.item(4).childNodes.item(0), true, true);
			if(oBet.newSize == null || oBet.newPrice == null || oBet.newSize == '' || oBet.newPrice == '' || oBet.getPrice() == null || oBet.getSize() == null || oBet.getPrice() == '' || oBet.getSize() == '' || checkPrice == false || checkSize == false){
				alertExceptionsHaveBeenThrown = true;
				break;
			}
		}
	}
	if(alertExceptionsHaveBeenThrown == false) {
		this.myBetsView.submitMyBets(bBypassCountDown);
	}
}

;controllers_MyBetsController.prototype.resetMyBets = function(){
	this.myBetsView.resetMyBets();
}

;controllers_MyBetsController.prototype.cancelAllMyBets = function(){
	this.myBetsView.cancelAllMyBets();
}

/*
*	Shared methods
*/
function controllers_BetsHelperController(bets){
	this.market = null;
	this.bets = bets;
	this.currentlySelectedCouponMarketId = null;
}

;controllers_BetsHelperController.prototype.setMarket = function(market){
	this.market = market;
}

;controllers_BetsHelperController.prototype.setActiveCouponMarket = function(marketId){
	this.currentlySelectedCouponMarketId = marketId;
}

/*
* Profit and Loss Annotation Object.
*/
function controllers_ProfitAndLossController(){
	this.market = null;
	this.user = null;
	this.profitAndLoss = null;
	this.profitAndLossView = new views_ProfitAndLossView();
}

;controllers_ProfitAndLossController.prototype.setMarket = function(market){
	this.market = market;
	this.profitAndLossView.setMarket(market);
}

;controllers_ProfitAndLossController.prototype.setProfitAndLossAnnotations = function(profitAndLossAnnotations){
	this.profitAndLoss = profitAndLossAnnotations;
}

/**
* Market Information Controller
*/

function controllers_MarketInformationController(){
	this.market = null;
	this.user = null;
	this.marketInformationView = new views_MarketInformationView(this.bets);
	this.multiplesHelperController = new controller_MultiplesHelperController();
}

;controllers_MarketInformationController.prototype.setMarket = function(market){	
	this.market = market;
	this.marketInformationView.setMarket(market);

	this.marketInformationView.updateView();
	// Added by Ash to Add commision text for groups in rules

	var arrGroupCommissionComplete = new Array();
	
	if (betexUIGlobalSettings.groupCommission) {
		arrGroupCommissionComplete = betexUIGlobalSettings.groupCommission.split("^");
	}
	var arrGroupCommission = new Array(arrGroupCommissionComplete.length); 

	for (var arrGroupCommissionCtr=0; arrGroupCommissionCtr < arrGroupCommissionComplete.length ;arrGroupCommissionCtr++)
	{
		var arrBuffer = new Array();
		arrBuffer = arrGroupCommissionComplete[arrGroupCommissionCtr].split("|");
		if (arrBuffer[0] == market.groupId)
		{
			betexUIGlobalSettings.groupCommission = arrBuffer[1];
			break;
		}
	}
		
	var arrComm = document.getElementById("BMMarketInformationCommissionText").innerHTML.split(" %");
	
	if (arrComm[1] == null && arrComm[0] != betexUIGlobalSettings.groupCommission)
	{
		var commissionTextHTML = document.getElementById("BMMarketInformationCommissionText").innerHTML;
		this.setGroupCommissionText(commissionTextHTML);
		document.getElementById("BMMarketInformationCommissionText").innerHTML = betexUIGlobalSettings.groupCommission + ' ' + commissionTextHTML;	 
	} 
	else if(arrComm[0] != betexUIGlobalSettings.groupCommission){
		document.getElementById("BMMarketInformationCommissionText").innerHTML = betexUIGlobalSettings.groupCommission + ' ' + this.commissionText;	 
	}		
}
;controllers_MarketInformationController.prototype.setGroupCommissionText = function(commissionText){
	this.commissionText = commissionText;
}
;controllers_MarketInformationController.prototype.setActiveCouponMarket = function(marketId){
	if(this.currentlySelectedCouponMarketId == marketId) {
		return;
	}
	this.currentlySelectedCouponMarketId = marketId;
	this.marketInformationView.setActiveCouponMarket(marketId);
}

;controllers_MarketInformationController.prototype.setUserPreferences = function(user){
	this.user = user;
	this.marketInformationView.setUserPreferences(user);
}

/**
* Helper controller for storing Market Conflicts and Commission Information - Added by Lash
*/
function controller_MultiplesHelperController(){
	this.conflictArray = null;
	this.commissionArray = null;	
}

;controller_MultiplesHelperController.prototype.addConflicts = function (conflicts){
	this.conflictArray = conflicts;
	betexUIGlobalSettings.conflictMarkets = conflicts;
}
;controller_MultiplesHelperController.prototype.addCommissions = function (commissions, maxLegSize, minLegSize, maximumLiabilityReturn, minimumPossibleReturn){	
	this.commissionArray = commissions;
	betexUIGlobalSettings.groupCommission = commissions;
	betexUIGlobalSettings.maxLegSize = parseInt(maxLegSize);
	betexUIGlobalSettings.minLegSize = parseInt(minLegSize);
	betexUIGlobalSettings.maximumLiabilityReturn = maximumLiabilityReturn;
	betexUIGlobalSettings.minimumPossibleReturn = minimumPossibleReturn;
}
;controller_MultiplesHelperController.prototype.getConflicts = function (){
	return this.conflictArray;
}
;controller_MultiplesHelperController.prototype.getCommissions = function (){
	return this.commissionArray;
}


/**
* Market View - Controller
*/

function controllers_MarketViewController(){
	this.market = null;
	this.user = null;
	this.marketView = new views_MarketView();
	this.currentlySelectedCouponStakeValue = null;
	this.currentlySelectedCouponMarketId = null;
	this.marketViewBetsHelper = new controllers_BetsHelperController(null);
	this.currentlySelectedCouponStakeField = "couponStakeValue1";
	this.oPAndLAnnotations = null;
	this.marketViewLoaded = false;
}

;controllers_MarketViewController.prototype.setMarket = function(market){	
	this.market = market;
	this.marketView.setMarket(market);
	this.marketViewBetsHelper.setMarket(market);
	this.marketView.updateView();
}

;controllers_MarketViewController.prototype.addRunners = function(runners){
	this.market.runners = runners;
}

;controllers_MarketViewController.prototype.setUserPreferences = function(user){
	this.user = user;	
	this.currentlySelectedCouponStakeValue = this.user.preferences.couponStake1;
	this.marketView.setUserPreferences(user);
	this.setCouponStakes();
}

;controllers_MarketViewController.prototype.setCouponParentLinks = function(couponParentLinks){
	this.marketView.setCouponParentLinks(couponParentLinks);
}

;controllers_MarketViewController.prototype.setActiveCouponMarket = function(marketId){
	if(this.currentlySelectedCouponMarketId == marketId) {
		return;
	}
	this.currentlySelectedCouponMarketId = marketId;
	this.marketViewBetsHelper.setActiveCouponMarket(marketId);
	this.marketView.setActiveCouponMarket(marketId);
}

;controllers_MarketViewController.prototype.setCouponStakes = function(){}

;controllers_MarketViewController.prototype.controlRealEstate = function(sFunctionalArea) {	

	if (this.market.isClosed) return;	// Added by laks to prevent the state being lost when a closed market is selected.
	
	if (sFunctionalArea == "initialise") {	
		if (!this.marketViewLoaded) {
			this.marketViewLoaded = true;
			this.controlRealEstate("resize");
			this.controlRealEstate("backLayHeaders");
		}
	} else {
		if (this.marketViewLoaded) {
			switch(sFunctionalArea) {
				case "resize":
					var MVHeaderHeight = document.getElementById('MVHeaderWrapper').offsetHeight;
					var ContentWrapperHeight = document.body.clientHeight - MVHeaderHeight - document.getElementById('MVFooterWrapper').offsetHeight - 2; // extra 2 pixels come from padding
					if (ContentWrapperHeight < 0) {
						ContentWrapperHeight = 0;
					}
					document.getElementById("MVContentWrapper").style.height = ((ContentWrapperHeight > 0) ? ContentWrapperHeight : 0);
					
					// calculate MV Content centre point (which is bigger MVContentWrapper or the actual MVContent?)
					var iMVContentCentrePoint = 0;
					if (document.getElementById('MVContent').offsetHeight < parseInt(document.getElementById("MVContentWrapper").style.height)) {
						var iHeight = (document.getElementById('MVContent').offsetHeight / 2);
						iMVContentCentrePoint = ((iHeight > 0) ? iHeight : 0);
					} else {
						var iHeight = parseInt(document.getElementById("MVContentWrapper").style.height) / 2;
						iMVContentCentrePoint = ((iHeight > 0) ? iHeight : 0);
					}

					// position suspendedInfo panel
					if ((iMVContentCentrePoint - (document.getElementById("MVContentSuspendInfo").offsetHeight / 2)) > MVHeaderHeight) {
						var iHeight = iMVContentCentrePoint - (document.getElementById("MVContentSuspendInfo").offsetHeight / 2);
						document.getElementById("MVContentSuspendInfo").style.top = ((iHeight > 0) ? iHeight : 0);
					} else {
						document.getElementById("MVContentSuspendInfo").style.top = 50;
					}					
					this.controlRealEstate("backLayHeaders");
				break;
				case "backLayHeaders":
					var MVHeaderBackWidth = 0;
					var MVHeaderLayWidth = 0;					
					if (document.getElementById("MVContentBack1stContent")) {						
						MVHeaderBackWidth += document.getElementById("MVContentBack1stContent").offsetWidth;
					}					
					if (document.getElementById("MVContentLay1stContent")) {						
						MVHeaderLayWidth += document.getElementById("MVContentLay1stContent").offsetWidth;
					}						
					// sublime cowboy work to add width of scrollbar (which differs in IE and Mozilla)					
					if (document.getElementById('MVContent').offsetHeight >= parseInt(document.getElementById("MVContentWrapper").style.height)) {
						MVHeaderLayWidth += (navigator.appVersion.indexOf("MSIE") != -1) ? 17 : 19;
					}					
					if (MVHeaderBackWidth > 0) {						
						document.getElementById("MVHeaderBackCell").width = MVHeaderBackWidth;
					}				
					if (MVHeaderLayWidth > 0) {					
						document.getElementById("MVHeaderLayCell").width = MVHeaderLayWidth;						
					}					
				break;
			}
		} 
	}	
}

try{
	interface_registerJSResource("bettingController")
}catch(x){
}
