if (! ("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}


var initialBgSize;

var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}

function loadExtraBets(eventId, type) {
	
	if (type == null){
		type = 'extra';
	}
	var div = type+'bet';
	
	

	var url = site_url('Events/ajaxGetMarketsByEventId_block/');
	if(div != 'specialbet') {
		if($(div + '_' + eventId).previous('.bet_row').hasClassName('highlighted')) {
			$(div + '_' + eventId).previous('.bet_row').removeClassName('highlighted');
		} else {
			$(div + '_' + eventId).previous('.bet_row').addClassName('highlighted');
		}
	}
	
	if($(div + '_' + eventId) && $(div + '_' + eventId).innerHTML.replace(/^\s*|\s*$/g,'').length != 0) {
		$('content_section_main').setStyle({
		  height: '100%'
		});
		if($(div + '_' + eventId).hasClassName('collapsed') && $('eventToggler-'+eventId).hasClassName('collapsed') ) {
			$(div + '_' + eventId).removeClassName('collapsed');
			$(div + '_' + eventId).addClassName('opened');
			$('eventToggler-'+eventId).removeClassName('collapsed');
			$('eventToggler-'+eventId).addClassName('opened');
			$('eventToggler-'+eventId).update('-');
			initBgResize();
			//return;
		}else if($(div + '_' + eventId).hasClassName('opened') || $('eventToggler-'+eventId).hasClassName('opened') ) {
			$(div + '_' + eventId).removeClassName('opened');
			$(div + '_' + eventId).addClassName('collapsed');
			$('eventToggler-'+eventId).removeClassName('opened');
			$('eventToggler-'+eventId).addClassName('collapsed');
			//$('eventToggler-'+eventId).update('+');
			$('eventToggler-'+eventId).update($('eventToggler-'+eventId).title);
			initBgResize();
			return;
		}
	}

	if(!$(div + '_' + eventId))
		return false;
	

	//load all extra bets for this id
	if($(div + '_' + eventId).innerHTML.replace(/^\s*|\s*$/g,'').length == 0) {
		$$('body').first().addClassName('busy');
		$('eventToggler-'+eventId).removeClassName('opened');
		$('eventToggler-'+eventId).removeClassName('collapsed');
		$('eventToggler-'+eventId).addClassName('loading');
		$('eventToggler-'+eventId).update('-');
		new Ajax.Updater(div + '_' + eventId, url, {method: 'post', parameters: {
					eventId: eventId,
					type: type
				},
				onComplete:function(text){
					$('content_section_main').setStyle({
					  height: '100%'
					});
					$$('body.busy').first().removeClassName('busy');
					$('divCursor').hide();		
					$('eventToggler-'+eventId).removeClassName('loading');
					$('eventToggler-'+eventId).addClassName('opened');
					$('eventToggler-'+eventId).update('-');
					$(div + '_' + eventId).previous('.bet_row').addClassName('highlighted');
					if(div != 'specialbet') {
						$(div + '_' + eventId).removeClassName('collapsed');
						$(div + '_' + eventId).addClassName('opened');
					}
					applyBetslipFunctionToDiv();
					applyTooltip();
					resizeMainBg();
				}
			}
		);
	}
	
}

function updateLeagues(leagueId, sportId) {

	//add outcome id to slip
	//if not on correct page we redirect
	if($('events_block') == null) {
		return;
	}

	var url = site_url('Events/ajaxGetEvents_block/');
	$$('body').first().addClassName('busy');
	$('li_league_' + leagueId).addClassName('loading');
	
	new Ajax.Updater('events_block', url, {
	  parameters: { leagueId: leagueId },
	  onComplete:function(text){
			$$('body.busy').first().removeClassName('busy');
			$$('.current').each(function(s, index) {
				s.removeClassName('current');
			});
			$('li_league_' + leagueId).removeClassName('loading');
			$('li_league_' + leagueId).addClassName('current');
			Effect.ScrollTo('events_block');
			bet_slip.highlightAllButtons();
		}
	});
	
	try  {
		document.title = $('li_league_'+leagueId).parentNode.parentNode.up('li').down('a').innerHTML + ' - ' + trim($('li_league_'+leagueId).parentNode.parentNode.parentNode.parentNode.up('li').down('a').innerHTML, " ") + ' - ' + $('li_league_'+leagueId).innerHTML;
	} catch(err) {}

	window.location.hash = '#' + leagueId;
	
}
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function openSportNode(element, sportId) {
	if(element.title)
		try{
			googleTrackPageview('sport', element.title);
		}catch(e){
			console.log(e);
		}
	//check if this already contains a ul if so then return
	if($('sport_' + sportId).next() !== null ) {
		toggleSport(element);
		return false;
	}
	var onclickcontent = element.onclick;
	element.onclick = "";
	var ul;
	var li;
	var a;
	//create element
	element.addClassName('loading');
	$$('body').first().addClassName('busy');
	var url = site_url('MyBet/ajaxGetRegionsBySportId/');
	new Ajax.Request(url, {
		method: 'post', parameters: {
			sportId: sportId
		},
		onComplete:function(text){
			$$('body.busy').first().removeClassName('busy');
			element.addClassName('open_sport_node');
			var data = text.responseText.evalJSON();
			data['regions']['regions'].each(function(s, index) {
				//console.log(size(data['regions']['regions']));
				if(index == 0) {
					ul = new Element('ul', { 'id': 'sportcontainer_' + sportId});
					ul.setAttribute('class', 'tree_sports');
					ul.setAttribute('className', 'tree_sports');
				}
				a = new Element('a', {'href': '#'}).update(s['name']);
				a.onclick = function(){
					//console.log('region_' + s['regionId'] + '_sport_' + sportId);
					//alert(s['regionId']);
					openRegionNode(sportId, s['regionId']);
					return false;
				};
				li = new Element('li', {'id':'region_' + s['regionId'] + '_sport_' + sportId, 'class': 'rs'}).update(a);
				ul.insert(li);
			});
			element.onclick = onclickcontent;
			/*li = new Element('li', {'id':'more_bets', 'class': 'more_bets'});
			li.update('More bets');
			ul.insert(li);*/
			$('sport_' + sportId).up('li').addClassName('open_sport_node');
			$('sport_' + sportId).empty();
			$('sport_' + sportId).insert({ after: ul });
			element.removeClassName('loading');
			
			if($$('#sportcontainer_'+sportId+' li').size() == 1) {
				var temp_region_id = $$('#sportcontainer_'+sportId+' li')[0].id.split("_")[1];
				openRegionNode(sportId, temp_region_id);
			}
			//resize the white bg
			resizeMainBg();
		}
	});
	
}
		
function toggleSport(li) {
	//must use $(li.id) because just li breaks with ie7;
	var next  = $(li.id).next('ul', 0);
	$$('ul.tree li ul.tree_sports').each(function(s, index) {
		var sub_id = s.id.split("_")[1];
		if(li.id == 'sport_' + sub_id) {
			if(next.style.display == 'none') {
				//next.toggleClassName('opened');
				li.up('li').addClassName('opened');
				Effect.toggle(next.id, "slide", {duration: duration}); 
			} else {
				//next.toggleClassName('collapsed');
				li.up('li').removeClassName('opened');
				li.up('li').removeClassName('open_sport_node');
				Effect.toggle(next.id, "slide", {duration: duration}); 
			}
		
		} 
	});
	
	//resize the white bg
	setTimeout("resizeMainBg()",500);
}

//open in new window if fails then open as link
function openWindow(page, width, height) {
	var toolwin = window.open(page,"toolwin","left=0,screenX=0,top=0,screenY=0,titlebar=no,toolbar=no,directory=no,scrolling=yes,scrollbars=1,scroll=yes,width=" + screen.width + ",height=" + (screen.height-50));
	/*if(!toolwin) {
		window.location.href = page;
	}*/
	return false;
}

var newWin = null;
function popUp(strURL, strType, strWidth, strHeight) {
 if (newWin != null && !newWin.closed)
   newWin.close();
 var strOptions="";
 if (strType=="console")
   strOptions="resizable,height="+
     strHeight+",width="+strWidth;
 if (strType=="fixed")
   strOptions="status,height="+
     strHeight+",width="+strWidth;
 if (strType=="elastic")
   strOptions="status,height="+
     strHeight+",width="+strWidth;
 newWin = window.open(strURL, 'newWin', strOptions);
 newWin.focus();
}
function nextEventCountDown() {
	$('remaining_time_countdown').update(getFullRemainingTime());
}

function $f(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
	 return window[movieName];
	} else {
	 return document[movieName];
	}
}

Element.observe(document, 'dom:loaded', function(){

	$$('.quick_bet div').each(function(s, index) {
		if(s.down('a')) {
			s.observe('click', s.down('a').onclick);

			Event.observe(
				s.down('a'),
				'click',
				function(e) {
					Event.stop(e);
					return false;
				}
			);

		}
	});
	
	$$('.bet_type_winner div').each(function(s, index) {
		if(s.down('a')) {
			s.observe('click', s.down('a').onclick);

			Event.observe(
				s.down('a'),
				'click',
				function(e) {
					Event.stop(e);
					return false;
				}
			);

		}
	});
	$$('.verticalBets div').each(function(s, index) {
		if(s.down('a')) {
			s.observe('click', s.down('a').onclick);

			Event.observe(
				s.down('a'),
				'click',
				function(e) {
					Event.stop(e);
					return false;
				}
			);

		}
	});
	$$('#carousel .odds div').each(function(s, index) {
		if(s.down('a')) {
			s.observe('click', s.down('a').onclick);

			Event.observe(
				s.down('a'),
				'click',
				function(e) {
					Event.stop(e);
					return false;
				}
			);

		}
	});
	
	if($('connection_tabs')) { 
		// Find all elements that use that given CSS class  
		var elements = $$('#connection_tabs li');  
		elements.each(  
			function(e) {
				// Assign the onclick method to the element  
				Event.observe(e, "mouseover", tabsMouseoverListener );  
				Event.observe(e, "mouseout", tabsMouseoutListener );  
			} 
		);
	}
	
	if($('toolbar_message'))
		$('toolbar_message').update($$('#toolbar li.current span')[0].innerHTML);
		
	// Find all elements that use that given CSS class  
	var elements = $$('#toolbar li');  
	elements.each(  
		function(e) {
			// Assign the onclick method to the element  
			Event.observe(e, "mouseover", toolbarMouseoverListener );  
			Event.observe(e, "mouseout", toolbarMouseoutListener );  
		} 
	);
	
	/*if($('bookmark_me')) {
		Event.observe(
			'bookmark_me',
			'click',
			function() {
				CreateBookmarkLink('Bet770.com', 'http://bet770.com');
				return false;
			}
		);
	}*/
		
	if($('refresh')) {
		Event.observe(
			'refresh',
			'click',
			function(e) {
				Event.stop(e);
				changeStepper(0);
				return false;
			}
		);
	}

	if($('refresh')) {
		Event.observe(
			'refresh',
			'blur',
			function(e) {
				changeStepper(0);
				return false;
			}
		);
	}

	if($('my_messages')) {
		new Effect.Pulsate('my_messages', {duration:3});
	}
		
	if($('lang_tab')) {
		Event.observe(
			'lang_tab',
			'click',
			function() {
				Effect.toggle('lang_select', "appear", {duration: 0.1}); 
			}
		);
	}

	if($('login_box')) {
		Event.observe(
			'login_box',
			'click',
			function() {
				$('lang_select').fade({duration: 0.1});
			}
		);
	}
	//new PeriodicalExecuter(updateUserBalance, 60);

	//setTimeout("ajax_getLastMinuteBets()",500);
	//ajax_getLastMinuteBets();
});


function toggleRegion(li) {
	/*collapse everything */
	var regionId = li.id.split("_")[1];
	var sportId = li.id.split("_")[3];
	$$('ul.tree li ul li ul').each(function(s, index) {
		if(s.id == 'rs_' + regionId + '-' + sportId) {
			var a = $$('#' + li.id + ' > a')[0];
			//console.log(a);

			Effect.toggle(s.id, "slide", {duration: duration, 
				afterFinish:function(){
					if(s.style.display == 'none') {
						a.removeClassName('opened');
					} else {
						a.addClassName('opened');
					}
				}
			});
			
		}
	});
}

function hideRegion(li) {
	//console.log(li);
	/*collapse everything */
	var regionId = li.id.split("_")[1];
	var sportId = li.id.split("_")[3];

	$$('ul.tree li ul li ul').each(function(s, index) {
		if(s.id == 'rs_' + regionId + '-' + sportId)
			s.style.display = 'none';
	});
}
function toggleSpecialNodes() {
	$$('.specials_main_block a').each(function(s, index) {
		if(s.hasClassName('selected')) {
			if(s.parentNode.parentNode.hasClassName('collapsed')) {
				s.parentNode.parentNode.toggleClassName('opened');
			} else {
				s.parentNode.parentNode.toggleClassName('collapsed');
			}
		}
	});
}

function goToBet(obj) {
	var redirect = site_url('') + 'events/region-' + obj.regionId + '/sport-' + obj.sportsId + '/league-' + obj.leagueId + '/event-' + obj.eventId;
	window.location.href = redirect;
}


function center(element){
    try{
        element = $(element);
    }catch(e){
        return;
    }

    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    }else if ( document.documentElement && 
             ( document.documentElement.clientWidth ||
               document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body && 
            ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    element.style.position = 'absolute';
    element.style.zIndex   = 99;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    setY = 0;

    element.style.left = setX + "px";
    element.style.top  = setY + "px";
	element.style.position = 'fixed';
    element.style.display  = 'block';
}
function showFloatingBox(div) {
	Effect.Appear(div, { duration: 1 });
	new Draggable(div);
}
function hideFloatingBox(div) {
	$(div).style.display = 'none';
}
function error(title, text) {
	createAlert(title, text);
}
function createModal() {
	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	mObj.style.height = document.documentElement.scrollHeight + "px";
	return mObj;
}

function createAlert(title, txt, sysId) {
	console.log(sysId );
	if(sysId == null) {
		sysId = 'undefined';
	}
	d = document;
	if($("modalContainer")) return;
	
	mObj = createModal();

	
	// create the DIV that will be the alert 
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";
	// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	// center the alert box
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	// create an H1 element as the title bar
	h1 = alertObj.appendChild(d.createElement("h1"));
	h1.appendChild(d.createTextNode(title));

	// create a paragraph element to contain the txt argument
	//msg = alertObj.appendChild(d.createElement("p"));
	p = d.createElement("p");
	p.innerHTML = txt;
	msg = alertObj.appendChild(p);
	msg.appendChild(d.createTextNode(txt));
	msg.innerHTML = txt;

	//create an anchor element to use as the print button
	if(sysId != 'undefined'){		
		prt = alertObj.appendChild(d.createElement("a"));
		prt.id = "printBtn";
		prt.appendChild(d.createTextNode(print_button_text));
		prt.href = "#";
		//onklick event to show the printable receipt
		prt.onclick = function() {
			removeModal();
			printReceipt(sysId); 
			return false; 
		}
	
	}
	// create an anchor element to use as the confirmation button.
	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "closeBtn";
	btn.appendChild(d.createTextNode(close_button_text));
	btn.href = "#";
	btn.onclick = function() { removeModal();return false; }
	if(!sysId){
		//btn.addClassName('no_print');
	}
	new Draggable('alertBox');
	center('alertBox');
	// set up the onclick event to remove the alert when the anchor is clicked
	
	document.onkeypress = stopRKey;
}
function createProcessing(text) {
	d = document;
	if($("modalContainer")) return;
	
	mObj = createModal();

	// create the DIV that will be the alert 
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "processingBox";
	// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	// center the alert box
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	// create a paragraph element to contain the txt argument
	msg = alertObj.appendChild(d.createElement("span"));
	msg.className = 'text';
	msg.appendChild(d.createTextNode(text));

	new Draggable('processingBox');
	center('processingBox')

	document.onkeypress = stopRKey;
}

function createBettingSlipOverview(title, txt) {
	d = document;
	if($("modalContainer")) return;
	
	mObj = createModal();


	// create the DIV that will be the alert 
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "bettingSlip";
	// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	// center the alert box
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	// create an H1 element as the title bar
	left_div = alertObj.appendChild(d.createElement("div"));
	left_div.className = "alert_left";
	
	middle_div = alertObj.appendChild(d.createElement("div"));
	middle_div.className = "alert_middle";
	middle_div.appendChild(d.createTextNode(title));
	
	right_div = alertObj.appendChild(d.createElement("div"));
	right_div.className = "alert_right";
	
	// create a paragraph element to contain the txt argument
	//msg = alertObj.appendChild(d.createElement("p"));
	div = d.createElement("div");
	div.id = "bettingSlip_html";
	div.innerHTML = txt;
	msg = alertObj.appendChild(div);
	
	bottom_div = d.createElement("div");
	bottom_div.className = "bettingSlip_bottom";
	bottom_div.innerHTML = "";
	msg = alertObj.appendChild(bottom_div);
	
	//msg.appendChild(d.createTextNode(txt));
	//msg.update(txt);

	// create an anchor element to use as the confirmation button.
	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "closeBtn";
	btn.appendChild(d.createTextNode('X'));
	btn.href = "#";
	new Draggable('bettingSlip');
	center('bettingSlip');
	// set up the onclick event to remove the alert when the anchor is clicked
	btn.onclick = function() { removeModal();return false; }
	document.onkeypress = stopRKey;
}
function stopRKey(evt) {
	var evt  = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text")) { removeAlert();return false; }
}
function removeModal() {
	document.getElementsByTagName("body")[0].removeChild($("modalContainer"));
	//just for testing
	if($$('body.busy').first())
		$$('body.busy').first().removeClassName('busy');
	$('divCursor').hide();
	
}
function info(title, text) {
	$('window').show();
	$('window_title').update(title);
	$('window_contents').update("<p class='notice'>" + text + "</p>");
}
function success(title, text, sysId) {
	createAlert(title, text, sysId);
}

/*	
Ajax.Responders.register({
  onCreate: function() {
    if($$('body').first() && Ajax.activeRequestCount > 0) {
        $$('body').first().addClassName('busy');
		//$('divCursor').style.display = "block";
	}
  },
  onComplete: function() {
	return;
    if($$('body.busy') && Ajax.activeRequestCount == 0) {
        $$('body.busy').first().removeClassName('busy');
		//$('divCursor').style.display = "none";
	}
  }
});
*/

function tabsMouseoverListener(e) {
	e = e || window.event;
	var targ = e.target || e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	var tab_id = targ.parentNode.id.split("_")[0];

	$$('#slogan_menu li').each(
		function(elem) {
			if(elem.id.split("_")[0] == tab_id) {
				elem.removeClassName('collapsed');
			} else {
				elem.addClassName('collapsed');
			}
		}
	);
	
}

function tabsMouseoutListener(e) {
	$$('#slogan_menu li').each(
	function(elem) {
			if(elem.id.split("_")[0] == 'bet') {
				elem.removeClassName('collapsed');
			} else {
				elem.addClassName('collapsed');
			}
		}
	);
}

function pageLoader() {
	/*$('divCursor').style.display = "block";*/
	$$('body').first().addClassName('busy');
}

//for every submit button show loading button
window.onbeforeunload = pageLoader;

/*
Script for adding bookmark
*/
function CreateBookmarkLink(title, url) {
	url = window.location.href;
	if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
		alert('Please press Ctrl + D to add Casino770 to your favourites');
	}
	else if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true;
	}
}

//this function runs when the page is loaded, switch the checkbox with an image
//image is at header.php
function replaceChecks() {
	
	//get all the input fields on the page
	inputs = document.getElementsByTagName('input');

	//cycle trough the input fields
	for(var i=0; i < inputs.length; i++) {

		//check if the input is a checkbox
		if(inputs[i].getAttribute('type') == 'checkbox') {
			//create a new image
			var img = document.createElement('img');
			//img.className = inputs[i].className;

			//check if the checkbox is checked
			if(inputs[i].checked) {
				img.src = imgTrue;
			} else {
				img.src = imgFalse;
			}

			//set image ID and onclick action
			img.id = 'checkImage'+i;
			//set image 
			if(typeof inputs[i].onclick == 'function') {

			} else {
				img.onclick = new Function('checkChange('+i+')');
			}
			//place image in front of the checkbox
			inputs[i].parentNode.insertBefore(img, inputs[i]);
			
			//hide the checkbox
			inputs[i].style.display='none';
			img.style.cursor = 'pointer';
			//img.style.border = '1px solid #c5c5c5';
			img.style.border = '0';
			if(typeof inputs[i].onclick == 'function') {
				img.onclick = function(){
					img_id = img.id.split("checkImage")[1];
					checkChange(img_id);
				};
				Event.observe(img, "click", $(img.id).next('input').onclick);
			} else {
				img.onclick = new Function('checkChange('+i+')');
			}

		}
	}
}

//change the checkbox status and the replacement image
function checkChange(i) {
	if(inputs[i].checked) {
		inputs[i].checked = '';
		$('checkImage'+i).src = imgFalse;
	} else {
		inputs[i].checked = 'checked';
		$('checkImage'+i).src = imgTrue;
	}
}



function applyBetslipFunctionToDiv(){

	$$('.verticalBets div').each(function(s, index) {
		if(s.down('a')) {
			s.observe('click', s.down('a').onclick);

			Event.observe(
				s.down('a'),
				'click',
				function(e) {
					Event.stop(e);
					return false;
				}
			);

		}
	});
	
	$$('.result_score div').each(function(s, index) {
		if(s.down('a')) {
			s.observe('click', s.down('a').onclick);

			Event.observe(
				s.down('a'),
				'click',
				function(e) {
					Event.stop(e);
					return false;
				}
			);

		}
	});
	

}

var delaiCLOSE;
Event.observe(window, 'load', function(){	
	if($('popjv') != null) {
		new Effect.Move($('popjv'), { x: 130, y: 180, mode: 'absolute' });
		delaiCLOSE = setTimeout("closepop()",20000);
		delaiOPEN = setTimeout("showpop()",10000);
	}
});
function showpop() {
	$('popjv').show();
}
function closepop() {
	$('popjv').onclick = function(){
		return false;
	};
	$('popjv').style.visibility = 'hidden';
	clearTimeout(delaiCLOSE);
}
function goToPopUp(url, lang) {
	if($('popjv').style.visibility != 'hidden') {
		window.location.href = url;
	}
}

function toggleLangSelect(){
	Effect.toggle('lang_select', "appear", {duration: 0.1}); 
}

function applyTooltip(){
	var tooltip_links = $$('.tooltip');
	tooltip_links.each( function (t) {
		t.next().hide();
		t.onmouseover = function () {
			this.next().show();
			this.next().clonePosition(this,{setLeft: true, setTop: true, setWidth: false, setHeight: false, offsetLeft: -150, offsetTop: -130});
		}
		t.onmouseout = function () {
			this.next().hide();
		}
		
	});
}

//resize the main bg on page load
initBgResize();
var initialBgSize = 0;
function initBgResize(){
	if($('content_section_main') && $('content_section_bottom')){
		initialBgSize = $('content_section_main').getHeight();
		resizeMainBg();
	} else {
		setTimeout("initBgResize()", 1000);
	}
}
	
//function to resize the main bg when the menu is opened or closed
function resizeMainBg(){
	var currentBgSize = 0;
	if($('content_section_main').getHeight() > initialBgSize){
		currentBgSize = $('content_section_main').getHeight();
	} else {
		currentBgSize = initialBgSize;
	}
	//carousel on the homepage pushes the main part down, carousel height needs to be substracted
	var carousel_height = 0;
	if($('carousel')){
		carousel_height = 5 + $('carousel').getHeight();
	} else if ($('homepage_logo')) {
		carousel_height = 7 + $('homepage_logo').getHeight();
	}
	var leftHeight = $('left_content').getHeight(); 
	var newMainHeight = 0;
	if(!$('help_wrapper') && !!$('bet_history')){
		if ((currentBgSize + carousel_height) > leftHeight ) {
			newMainHeight = 100;
			$('content_section_main').setStyle({
				  height: newMainHeight+'%'
				});
			return;
		}else {
			newMainHeight =leftHeight;
			newMainHeight = newMainHeight -  $('content_section_bottom').getHeight();
			if($('content_section_top'))
				newMainHeight = newMainHeight +5- $('content_section_top').getHeight();
			if($('carousel'))
				newMainHeight = newMainHeight +5- $('carousel').getHeight();
			if($('homepage_logo'))
				newMainHeight = newMainHeight +7 - $('homepage_logo').getHeight();
			if($('bet_page_sports_header'))	
				newMainHeight = newMainHeight - 5;
			$('content_section_main').setStyle({
			  height: newMainHeight+'px'
			});
			if($('gototop')) {
				$('gototop').setStyle({
				  top: (newMainHeight-20)+'px'
				});
			}
		} 	
	}
}


var mini_game_loaded = false;
function gameLoaded() {
	mini_game_loaded = true;
	return mini_game_loaded;
}
function gameBalanceUpdate(value) {
	
	if(mini_game_loaded && $('balance')) {
		console.log(value);
		var balance_array = $('balance').innerHTML.split(' ');
		if(bet_slip.IsNumeric(balance_array[0])) {
			var currency = balance_array[1];
			$('balance').update(value.toFixed(2) + ' ' + currency);
		} else if(bet_slip.IsNumeric(balance_array[1])) {
			var currency = balance_array[0];
			$('balance').update(currency + ' ' + value.toFixed(2));
		}
	}
	return true;
}


function updateUserBalance(value) {
	$$('body').first().addClassName('busy');
	var url = site_url('MyAccount/ajax_get_balance/');
	new Ajax.Request(url, {
		method: 'get',
		onComplete: function(transport) {
			$$('body.busy').first().removeClassName('busy');
			var balance_array = $('balance').innerHTML.split(' ');
			var data = transport.responseText.evalJSON();
			var balance = parseFloat(data['balance']);
			if(IsNumeric(balance_array[0])) {
				var currency = balance_array[1];
				$('balance').update(balance.toFixed(2) + ' ' + currency);
			} else if(IsNumeric(balance_array[1])) {
				var currency = balance_array[0];
				$('balance').update(currency + ' ' + balance.toFixed(2));
			}
		}
	});
}
function IsNumeric(sText) {

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

}


function ajax_getLastMinuteBets() {
	$$('body').first().addClassName('busy');
	limit = 20;
	if($('home_blocks'))
		limit = 10;
	var url = site_url('?ajax=ajax_getLastMinuteBets&limit='+limit);
	new Ajax.Updater('last_minute_bets_block', url, {method: 'post',
		onComplete:function(text){
			$$('body.busy').first().removeClassName('busy');
			$('last_minute_bets_block').setStyle({ height: 'auto'});
			$('last_minute_bets_block').removeClassName('loading_block');		
			ajax_getRecommendedBets();
			/*if($$('#last_minute_bets_block .quick_bet_list li').size() == 0) {
				$('last_minute_bets_block').hide();
			}*/
		}
	   }
	);
}

function ajax_getMostPopularBets() {
	$$('body').first().addClassName('busy');
	var url = site_url('?ajax=ajax_getMostPopularBets');
	new Ajax.Updater('most_popular_bets_block', url, {method: 'post',
		onComplete:function(text){
			$$('body.busy').first().removeClassName('busy');
			$('most_popular_bets_block').setStyle({ height: 'auto'});
			$('most_popular_bets_block').removeClassName('loading_block');
			applyTooltip();
		}
	   }
	);
}

function ajax_getRecommendedBets() {
	$$('body').first().addClassName('busy');
	var url = site_url('?ajax=ajax_getRecommendedBets');
	new Ajax.Updater('default_league_block', url, {method: 'post',
		onComplete:function(text){
			$$('body.busy').first().removeClassName('busy');
			$('default_league_block').setStyle({ height: 'auto'});
			$('default_league_block').removeClassName('loading_block');
			ajax_getMostPopularBets();
			if($$('#default_league_block .quick_bet_list li').size() == 0) {
				$('default_league_block').hide();
			}
		}
	   }
	);
}
/*function ajax_getPronofootJackpot() {
	var url = site_url('?ajax=ajax_getPronofootJackpot');
	new Ajax.Updater({ success: 'jackpot' }, url, {method: 'post',
		onComplete:function(text){
			
		}
	   }
	);
}*/

Element.observe(document, 'dom:loaded', function(){
	//setInterval("ajax_getPronofootJackpot()", 60000*5);
	if( $('last_minute_bets_block') ) {
		//setTimeout("ajax_getLastMinuteBets()", 1000*5);
	}
	setTimeout("ajax_getLastMinuteBets()", 1000*5);
});

