/* site wide common js functions */

// Override IE setTimeout.
/*@cc_on
(function(f){
window.setTimeout = f(window.setTimeout);
window.setInterval = f(window.setInterval);
})(function(f){
return function(c,t){
var a = Array.prototype.slice.call(arguments,2);
if(typeof c != "function")
c = new Function(c);
return f(function(){
c.apply(this, a)
}, t)
}
});
@*/

function openWindow (url, windowname, width, height, status, scrollbars)
{	var windowFeatures = "";
	var win;

   var screenX = Math.floor(screen.availWidth/2 - width/2);
   var screenY = Math.floor(screen.availHeight/2 - height/2);

   windowFeatures  = "toolbar=0,resizable=no,dependent=yes,personalbar=0";
   windowFeatures += ",scrollbars="+scrollbars+",menubar=0";
   windowFeatures += ",height="+height+",width="+width+",status="+status;
   windowFeatures += ",screenX="+screenX+",screenY="+screenY;
   windowFeatures += ",left="+screenX+",top="+screenY;

   win = window.open(url, windowname, windowFeatures);
}

function openInfoWindow(url, windowname)
{	var windowFeatures = "";
	var win;

        if(!windowname)
        {
   	windowname ='x';
        }

	windowFeatures  = "toolbar=0,resizable=no,dependent=yes,personalbar=0";
    windowFeatures += ",scrollbars=yes,menubar=0,width=500,height=350,status=no";

	win = window.open(url, windowname, windowFeatures);
	win.focus();
}

function resizeFadeDiv() {
   var fadeDiv = document.getElementById("fadeDiv");

   if(!fadeDiv)
      return;

   //check dimensions of window
   var w = 0;
   var h = 0;
   //ff
   if (window.innerWidth) {
      w = window.innerWidth;
      h = window.innerHeight;
   }
   //ie6
   else if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
      w = document.documentElement.clientWidth;
      h = document.documentElement.clientHeight;
   }
   //ie6 quirks
   else if (document.body && document.body.clientWidth && document.body.clientHeight) {
      w = document.body.clientWidth;
      h = document.body.clientHeight;
   }
   else {
      w = 0;
      h = 0;
   }
   //now check dimensions of document to see which is larger
   var w2 = 0;
   var h2 = 0;
   //ie6
   if (document.documentElement && document.documentElement.scrollWidth && document.documentElement.scrollHeight) {
      w2 = document.documentElement.scrollWidth;
      h2 = document.documentElement.scrollHeight;
   }
   //ie6 quirks
   else if (document.body && document.body.scrollWidth && document.body.scrollHeight) {
      w2 = document.body.scrollWidth;
      h2 = document.body.scrollHeight;
   }
   //ff
   else if (document.body && document.body.clientWidth && document.body.clientHeight) {
      w2 = document.body.clientWidth;
      h2 = document.body.clientHeight;
   }
   else {
      w2 = 0;
      h2 = 0;
   }
   fadeDiv.style.height = ((h > h2) ? h : h2) + "px";
   fadeDiv.style.width = ((w > w2) ? w : w2) + "px";
}

function fade_background() {
   var fadeDiv = document.getElementById("fadeDiv");

   if(!fadeDiv)
      return;

   fadeDiv.style.display = "block";
}

//window.onload   = resizeFadeDiv;
//window.onresize = resizeFadeDiv;

function openGame(mode)
{
   jnlpArgs = '';

   if(mode == 'demo')
   {
      jnlpArgs = '?mode=demo';
   }

   if(deployJava.isWebStartInstalled('1.2') || window.opera != undefined)
   {
      url = window.location.host + '/casino_game.jnlp' + jnlpArgs;
      window.location = 'https://' + url.replace('//', '/');
   }
   else
   {
      url = window.location.host + '/download_java.html' + jnlpArgs;
      window.location = 'http://' + url.replace('//', '/');
   }
}

//opens a window with a preview image of the applet
function openGuide(id)
{
 	var url    = window.location.host + '/game_guide/guide_popup.html?gam_id=' + id;
   var width  = 550;
	var height = 500;

   var w_options = "toolbar=no,directories=no,menubar=no,width="+width+",height="+height+",location=no,scrollbars=yes,resizable=yes,status=no";
  	var screenX = Math.floor(screen.availWidth/2 - width/2);
	var screenY = Math.floor(screen.availHeight/2 - height/2);

   WN=window.open('http://' + url.replace('//', '/'), 'gameguide'+id, w_options)
   WN.focus();
}

function clearPlaceHolder(textobject, placeholdertext)
{       if ( textobject.value == placeholdertext )
        {       textobject.value = ""
        }
}


function getHTTPObject()
{
   if(window.ActiveXObject)
      return new ActiveXObject("Microsoft.XMLHTTP");
   else
      if(window.XMLHttpRequest)
         return new XMLHttpRequest();
      else
         return null;
}

var ajaxSecureHost;
var ajaxGetBonusAmountElTermsDecline;
var ajaxGetBonusAmountElDepositAmount;
var ajaxGetBonusAmountElCouponNumber;
var ajaxGetBonusAmountElBonusCode;
var ajaxGetBonusAmountDepositType;
var ajaxGetBonusAmountOutputFunction = new Function("bonus_value" ,"");

function ajaxGetBonusAmount()
{
   objHTTP = getHTTPObject();

   if(objHTTP != null)
   {
      var acceptsTerms  = true;
      var depositType   = ajaxGetBonusAmountDepositType;
      var depositAmount = 0;
      var couponNumber  = "";
      var bonusCode     = "";

      if(ajaxGetBonusAmountElTermsDecline)
      {
         if(ajaxGetBonusAmountElTermsDecline.checked)
         {
            acceptsTerms = false;
         }
      }

      if(ajaxGetBonusAmountElDepositAmount)
      {
         if(ajaxGetBonusAmountElDepositAmount.value > 0)
         {
            depositAmount = ajaxGetBonusAmountElDepositAmount.value;
         }
      }

      if(ajaxGetBonusAmountElCouponNumber)
      {
         if(ajaxGetBonusAmountElCouponNumber.value.length > 0)
         {
            couponNumber = ajaxGetBonusAmountElCouponNumber.value;
         }
      }

      if(ajaxGetBonusAmountElBonusCode)
      {
         bonusCode = ajaxGetBonusAmountElBonusCode.value;
      }

      objHTTP.open("GET", ajaxSecureHost + "/ajaxGetBonusAmount.php?type="          + depositType + "&" +
                                                                   "amount="        + depositAmount + "&" +
                                                                   "couponnumber="  + couponNumber + "&" +
                                                                   "code="          + bonusCode + "&" +
                                                                   "accepts_terms=" + acceptsTerms,
                                                                   true);
      objHTTP.send(null);

      objHTTP.onreadystatechange = ajaxGetBonusAmountComplete;
   }
}

function ajaxGetBonusAmountComplete()
{
   if(objHTTP.readyState == 4)
   {
      ajaxGetBonusAmountOutputFunction(objHTTP.responseText);
   }
}

/* pop up window functions */

var dhtmlwindow={
imagefiles:['min.gif', 'close.gif', 'restore.gif', 'resize.gif'], //Path to 4 images used by script, in that order

minimizeorder: 0,
zIndexvalue:100,
tobjects: [], //object to contain references to dhtml window divs, for cleanup purposes
lastactivet: {}, //reference to last active DHTML window

init:function(t, name_of_back_button, url_of_back_button){
	var domwindow=document.createElement("div") //create dhtml window div
	domwindow.id=t
	domwindow.className="dhtmlwindow"
	var domwindowdata=''
	domwindowdata='<div class="drag-handle">'
	domwindowdata+='DHTML Window <div class="drag-controls"><div title="Minimize"></div><div title="Close"></div></div>'
	domwindowdata+='</div><a href = "'+url_of_back_button+'"><font color="black">'+name_of_back_button+'</font></a>'
	domwindowdata+='<div class="drag-contentarea"></div>'
	domwindowdata+='<div class="drag-statusarea"><div class="drag-resizearea" style="background: transparent url('+this.imagefiles[3]+') top right no-repeat;">&nbsp;</div></div>'
	domwindowdata+='</div>'
	domwindow.innerHTML=domwindowdata
	document.getElementById("dhtmlwindowholder").appendChild(domwindow)
	//this.zIndexvalue=(this.zIndexvalue)? this.zIndexvalue+1 : 100 //z-index value for DHTML window: starts at 0, increments whenever a window has focus
	var t=document.getElementById(t)
	var divs=t.getElementsByTagName("div")
	for (var i=0; i<divs.length; i++){ //go through divs inside dhtml window and extract all those with class="drag-" prefix
		if (/drag-/.test(divs[i].className))
			t[divs[i].className.replace(/drag-/, "")]=divs[i] //take out the "drag-" prefix for shorter access by name
	}
	//t.style.zIndex=this.zIndexvalue //set z-index of this dhtml window
	t.handle._parent=t //store back reference to dhtml window
	t.resizearea._parent=t //same
	t.controls._parent=t //same
	t.onclose=function(){return true} //custom event handler "onclose"
	t.onmousedown=function(){dhtmlwindow.setfocus(this)} //Increase z-index of window when focus is on it
	t.handle.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on handle div
	t.resizearea.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on resize div
	t.controls.onclick=dhtmlwindow.enablecontrols
	t.show=function(){dhtmlwindow.show(this)} //public function for showing dhtml window
	t.hide=function(){dhtmlwindow.hide(this)} //public function for hiding dhtml window
	t.close=function(){dhtmlwindow.close(this)} //public function for closing dhtml window (also empties DHTML window content)
	t.setSize=function(w, h){dhtmlwindow.setSize(this, w, h)} //public function for setting window dimensions
	t.moveTo=function(x, y){dhtmlwindow.moveTo(this, x, y)} //public function for moving dhtml window (relative to viewpoint)
	t.isResize=function(bol){dhtmlwindow.isResize(this, bol)} //public function for specifying if window is resizable
	t.isScrolling=function(bol){dhtmlwindow.isScrolling(this, bol)} //public function for specifying if window content contains scrollbars
	t.load=function(contenttype, contentsource, title, name_of_back_button){dhtmlwindow.load(this, contenttype, contentsource, title, name_of_back_button)} //public function for loading content into window
	this.tobjects[this.tobjects.length]=t
	return t //return reference to dhtml window div
},

open:function(t, contenttype, contentsource, title, attr, recalonload, name_of_back_button, url_of_back_button){
	var d=dhtmlwindow //reference dhtml window object

        // default the url_of_back_button argument to myaccount so that any existing
        // code does not break, but allows us to reuse this method in non customer
        // facing pages
        //
        // ben@vuetec.com

        url_of_back_button = url_of_back_button || "/myaccount/";


	function getValue(Name){
		var config=new RegExp(Name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
		return (config.test(attr))? parseInt(RegExp.$1) : 0 //return value portion (int), or 0 (false) if none found
	}
	if (document.getElementById(t)==null) //if window doesn't exist yet, create it
		t=this.init(t, name_of_back_button, url_of_back_button) //return reference to dhtml window div
	else
		t=document.getElementById(t)
	this.setfocus(t)
	t.setSize(getValue(("width")), (getValue("height"))) //Set dimensions of window
	var xpos=getValue("center")? "middle" : getValue("left") //Get x coord of window
	var ypos=1 //Get y coord of window
	//t.moveTo(xpos, ypos) //Position window
	if (typeof recalonload!="undefined" && recalonload=="recal" && this.scroll_top==0){ //reposition window when page fully loads with updated window viewpoints?
		if (window.attachEvent && !window.opera) //In IE, add another 400 milisecs on page load (viewpoint properties may return 0 b4 then)
			this.addEvent(window, function(){setTimeout(function(){t.moveTo(xpos, ypos)}, 400)}, "load")
		else
			this.addEvent(window, function(){t.moveTo(xpos, ypos)}, "load")
	}
	t.isResize(getValue("resize")) //Set whether window is resizable
	t.isScrolling(getValue("scrolling")) //Set whether window should contain scrollbars
        t.name_of_back_button = name_of_back_button;
	t.style.visibility="visible"
	t.style.display="block"
	t.contentarea.style.display="block"
	t.moveTo(xpos, ypos) //Position window
	t.load(contenttype, contentsource, title, name_of_back_button)
	if (t.state=="minimized" && t.controls.firstChild.title=="Restore"){ //If window exists and is currently minimized?
		t.controls.firstChild.setAttribute("src", dhtmlwindow.imagefiles[0]) //Change "restore" icon within window interface to "minimize" icon
		t.controls.firstChild.setAttribute("title", "Minimize")
		t.state="fullview" //indicate the state of the window as being "fullview"
	}
	return t
},

setSize:function(t, w, h){ //set window size (min is 150px wide by 100px tall)
	t.style.width=Math.max(parseInt(w), 150)+"px"
	t.contentarea.style.height=Math.max(parseInt(h), 100)+"px"
},

moveTo:function(t, x, y){ //move window. Position includes current viewpoint of document
	this.getviewpoint() //Get current viewpoint numbers
	t.style.left=(x=="middle")? this.scroll_left+(this.docwidth-t.offsetWidth)/2+"px" : this.scroll_left+parseInt(x)+"px"
	t.style.top=(y=="middle")? this.scroll_top+(this.docheight-t.offsetHeight)/2+"px" : this.scroll_top+parseInt(y)+"px"
},

isResize:function(t, bol){ //show or hide resize inteface (part of the status bar)
	t.statusarea.style.display=(bol)? "block" : "none"
	t.resizeBool=(bol)? 1 : 0
},

isScrolling:function(t, bol){ //set whether loaded content contains scrollbars
	t.contentarea.style.overflow=(bol)? "auto" : "hidden"
},

load:function(t, contenttype, contentsource, title, name_of_back_button){ //loads content into window plus set its title (3 content types: "inline", "iframe", or "ajax")

	var contenttype=contenttype.toLowerCase() //convert string to lower case
	if (typeof title!="undefined")
		t.handle.firstChild.nodeValue=title
	if (contenttype=="inline")
		t.contentarea.innerHTML=contentsource
	else if (contenttype=="div"){
		var inlinedivref=document.getElementById(contentsource)
		t.contentarea.innerHTML=(inlinedivref.defaultHTML || inlinedivref.innerHTML) //Populate window with contents of inline div on page
		if (!inlinedivref.defaultHTML)
			inlinedivref.defaultHTML=inlinedivref.innerHTML //save HTML within inline DIV
		inlinedivref.innerHTML="" //then, remove HTML within inline DIV (to prevent duplicate IDs, NAME attributes etc in contents of DHTML window
		inlinedivref.style.display="none" //hide that div
	}
	else if (contenttype=="iframe"){
		t.contentarea.style.overflow="hidden" //disable window scrollbars, as iframe already contains scrollbars
		if (!t.contentarea.firstChild || t.contentarea.firstChild.tagName!="IFRAME") //If iframe tag doesn't exist already, create it first
			t.contentarea.innerHTML='<iframe src="" style="margin:0; padding:0; width:100%; height: 100%" name="_iframe-'+t.id+'"></iframe>'
		window.frames["_iframe-"+t.id].location.replace(contentsource) //set location of iframe window to specified URL
		}
	else if (contenttype=="ajax"){
		this.ajax_connect(contentsource, t) //populate window with external contents fetched via Ajax
	}
	t.contentarea.datatype=contenttype //store contenttype of current window for future reference
},

setupdrag:function(e){
	var d=dhtmlwindow //reference dhtml window object
	var t=this._parent //reference dhtml window div
	d.etarget=this //remember div mouse is currently held down on ("handle" or "resize" div)
	var e=window.event || e
	d.initmousex=e.clientX //store x position of mouse onmousedown
	d.initmousey=e.clientY
	d.initx=parseInt(t.offsetLeft) //store offset x of window div onmousedown
	d.inity=parseInt(t.offsetTop)
	d.width=parseInt(t.offsetWidth) //store width of window div
	d.contentheight=parseInt(t.contentarea.offsetHeight) //store height of window div's content div
	if (t.contentarea.datatype=="iframe"){ //if content of this window div is "iframe"
		t.style.backgroundColor="#F8F8F8" //colorize and hide content div (while window is being dragged)
		t.contentarea.style.visibility="hidden"
	}
	document.onmousemove=d.getdistance //get distance travelled by mouse as it moves
	document.onmouseup=function(){
		if (t.contentarea.datatype=="iframe"){ //restore color and visibility of content div onmouseup
			t.contentarea.style.backgroundColor="white"
			t.contentarea.style.visibility="visible"
		}
		d.stop()
	}
	return false
},

getdistance:function(e){
	var d=dhtmlwindow
	var etarget=d.etarget
	var e=window.event || e
	d.distancex=e.clientX-d.initmousex //horizontal distance travelled relative to starting point
	d.distancey=e.clientY-d.initmousey
	if (etarget.className=="drag-handle") //if target element is "handle" div
		d.move(etarget._parent, e)
	else if (etarget.className=="drag-resizearea") //if target element is "resize" div
		d.resize(etarget._parent, e)
	return false //cancel default dragging behavior
},

getviewpoint:function(){ //get window viewpoint numbers
	var ie=document.all && !window.opera
	var domclientWidth=document.documentElement && parseInt(document.documentElement.clientWidth) || 100000 //Preliminary doc width in non IE browsers
	this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
	this.scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
	this.scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
	this.docwidth=(ie)? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(domclientWidth, window.innerWidth-16)
	this.docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
},

rememberattrs:function(t){ //remember certain attributes of the window when it's minimized or closed, such as dimensions, position on page
	this.getviewpoint() //Get current window viewpoint numbers
	t.lastx=parseInt((t.style.left || t.offsetLeft))-dhtmlwindow.scroll_left //store last known x coord of window just before minimizing
	t.lasty=parseInt((t.style.top || t.offsetTop))-dhtmlwindow.scroll_top
	t.lastwidth=parseInt(t.style.width) //store last known width of window just before minimizing/ closing
},

move:function(t, e){
	t.style.left=dhtmlwindow.distancex+dhtmlwindow.initx+"px"
	t.style.top=dhtmlwindow.distancey+dhtmlwindow.inity+"px"
},

resize:function(t, e){
	t.style.width=Math.max(dhtmlwindow.width+dhtmlwindow.distancex, 150)+"px"
	t.contentarea.style.height=Math.max(dhtmlwindow.contentheight+dhtmlwindow.distancey, 100)+"px"
},

enablecontrols:function(e){
	var d=dhtmlwindow
	var sourceobj=window.event? window.event.srcElement : e.target //Get element within "handle" div mouse is currently on (the controls)
	if (/Minimize/i.test(sourceobj.getAttribute("title"))) //if this is the "minimize" control
		d.minimize(sourceobj, this._parent)
	else if (/Restore/i.test(sourceobj.getAttribute("title"))) //if this is the "restore" control
		d.restore(sourceobj, this._parent)
	else if (/Close/i.test(sourceobj.getAttribute("title"))) //if this is the "close" control
		d.close(this._parent)
	return false
},

minimize:function(button, t){
	dhtmlwindow.rememberattrs(t)
	button.setAttribute("src", dhtmlwindow.imagefiles[2])
	button.setAttribute("title", "Restore")
	t.state="minimized" //indicate the state of the window as being "minimized"
	t.contentarea.style.display="none"
	t.statusarea.style.display="none"
	if (typeof t.minimizeorder=="undefined"){ //stack order of minmized window on screen relative to any other minimized windows
		dhtmlwindow.minimizeorder++ //increment order
		t.minimizeorder=dhtmlwindow.minimizeorder
	}
	t.style.left="10px" //left coord of minmized window
	t.style.width="200px"
	var windowspacing=t.minimizeorder*10 //spacing (gap) between each minmized window(s)
	t.style.top=dhtmlwindow.scroll_top+dhtmlwindow.docheight-(t.handle.offsetHeight*t.minimizeorder)-windowspacing+"px"
},

restore:function(button, t){
	dhtmlwindow.getviewpoint()
	button.setAttribute("src", dhtmlwindow.imagefiles[0])
	button.setAttribute("title", "Minimize")
	t.state="fullview" //indicate the state of the window as being "fullview"
	t.style.display="block"
	t.contentarea.style.display="block"
	if (t.resizeBool) //if this window is resizable, enable the resize icon
		t.statusarea.style.display="block"
	t.style.left=parseInt(t.lastx)+dhtmlwindow.scroll_left+"px" //position window to last known x coord just before minimizing
	t.style.top=parseInt(t.lasty)+dhtmlwindow.scroll_top+"px"
	t.style.width=parseInt(t.lastwidth)+"px"
},


close:function(t){
	try{
		var closewinbol=t.onclose()
	}
	catch(err){ //In non IE browsers, all errors are caught, so just run the below
		var closewinbol=true
 }
	finally{ //In IE, not all errors are caught, so check if variable isn't defined in IE in those cases
		if (typeof closewinbol=="undefined"){
			alert("An error has occured somwhere inside your \"onclose\" event handler")
			var closewinbol=true
		}
	}
	if (closewinbol){ //if custom event handler function returns true
		if (t.state!="minimized") //if this window isn't currently minimized
			dhtmlwindow.rememberattrs(t) //remember window's dimensions/position on the page before closing
		if (window.frames["_iframe-"+t.id]) //if this is an IFRAME DHTML window
			window.frames["_iframe-"+t.id].location.replace("about:blank")
		else
			t.contentarea.innerHTML=""
		t.style.display="none"
		t.isClosed=true //tell script this window is closed (for detection in t.show())
	}
	return closewinbol
},


setopacity:function(targetobject, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
	if (!targetobject)
		return
	if (targetobject.filters && targetobject.filters[0]){ //IE syntax
		if (typeof targetobject.filters[0].opacity=="number") //IE6
			targetobject.filters[0].opacity=value*100
		else //IE 5.5
			targetobject.style.filter="alpha(opacity="+value*100+")"
		}
	else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
		targetobject.style.MozOpacity=value
	else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
		targetobject.style.opacity=value
},

setfocus:function(t){ //Sets focus to the currently active window
	this.zIndexvalue++
	t.style.zIndex=this.zIndexvalue
	t.isClosed=false //tell script this window isn't closed (for detection in t.show())
	this.setopacity(this.lastactivet.handle, 0.5) //unfocus last active window
	this.setopacity(t.handle, 1) //focus currently active window
	this.lastactivet=t //remember last active window
},


show:function(t){
	if (t.isClosed){
		alert("DHTML Window has been closed, so nothing to show. Open/Create the window again.")
		return
	}
	if (t.lastx) //If there exists previously stored information such as last x position on window attributes (meaning it's been minimized or closed)
		dhtmlwindow.restore(t.controls.firstChild, t) //restore the window using that info
	else
		t.style.display="block"
	this.setfocus(t)
	t.state="fullview" //indicate the state of the window as being "fullview"
},

hide:function(t){
	t.style.display="none"
},

stop:function(){
	dhtmlwindow.etarget=null //clean up
	document.onmousemove=null
	document.onmouseup=null
},

addEvent:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false)
	else if (target.attachEvent)
		target.attachEvent(tasktype, functionref)
},

cleanup:function(){
	for (var i=0; i<dhtmlwindow.tobjects.length; i++){
		dhtmlwindow.tobjects[i].handle._parent=dhtmlwindow.tobjects[i].resizearea._parent=dhtmlwindow.tobjects[i].controls._parent=null
	}
	window.onload=null
}

} //End dhtmlwindow object

document.write('<div id="dhtmlwindowholder"><span style="display:none">.</span></div>') //container that holds all dhtml window divs on page
window.onunload=dhtmlwindow.cleanup

/**
 * Live Balance script.
 */

// Keep score of latest raw balance value.
var livebalance_raw;

// Round to decimal.
function livebalance_round(num, dec) {
  var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  return result;
}

// Select array of DOM elements by class_name and optionally a tag name and container element reference.
function livebalance_select(class_name, tag, container) {
  tag = tag || "*";
  container = container || document;
  var elements = container.getElementsByTagName(tag);
  if (!elements.length &&  tag == "*" &&  container.all) elements = container.all;
  var return_elements = new Array();
  var delim = class_name.indexOf('|') != -1  ? '|' : ' ';
  var class_array = class_name.split(delim);
  for (var i = 0, j = elements.length; i < j; i++) {
    var object_class = elements[i].className.split(' ');
    if (delim == ' ' && class_array.length > object_class.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = object_class.length; k < l; k++) {
      for (var m = 0, n = class_array.length; m < n; m++) {
        if (class_array[m] == object_class[k]) c++;
        if ((delim == '|' && c == 1) || (delim == ' ' && c == class_array.length)) {
          return_elements.push(elements[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return return_elements;
}

// Function to trim whitespace from the head and tail of strings.
function livebalance_trim(s) {
  return s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

// Function to pull numeric string from formatted currency.
function livebalance_balance(s) {
  var n = '';
  for (i=0;i<s.length;i++){
      c = s.charAt(i);
      if ((c != ' ' && !isNaN(c)) || c == '.') {
        n += c;
      }
  }
  return n;
}

// Given a balance, generate the structured HTML for it.
function livebalance_markup(inner) {
  inner = livebalance_trim(inner);
  var balance = livebalance_balance(inner);
  var bal_parts = balance.split('.', 2);
  var html = '';
  var column = bal_parts[0].length;
  var stages = new Array(5);
  stages[0] = 'prefix';
  stages[1] = 'integer';
  stages[2] = 'radix';
  stages[3] = 'fraction';
  stages[4] = 'suffix';
  var stage = 0;
  for (i=0;i<inner.length;i++) {
    var classes = [];
    c = inner.charAt(i);
    if (!isNaN(parseInt(c))) {
      if (stage == 0 || stage == 2) {
        stage++;
      }
      classes.push('number');
      classes.push(stages[stage]+'-'+column);
      (stage > 2 ? column++ : column--);
      if (column == 0) {
        column = 1;
      }
    }
    else {
      if ((c == '.' && stage == 1) || stage == 3) {
        stage++;
      }
      classes.push('symbol');
      classes.push('symbol-'+c.charCodeAt(0));
    }
    classes.push(stages[stage]+'-stage');
    if (c == ' ') {
      c = '&nbsp;';
    }
    html += '<span class="'+classes.join(' ')+'">'+c+'</span>';
  }
  return html;
}

// Add sliding strips of numbers to the markup.
function livebalance_markup_strips(livebalance) {
  var numbers = livebalance_select('number', 'span', livebalance);
  var init;
  var num;
  var height = livebalance.offsetHeight;
  var width = 0;
  var units;
  var offsetwidth;
  var width_total = 0;
  livebalance.style.position = 'relative';
  for (var i in numbers) {
    var default_number = parseInt(numbers[i].innerHTML);
    numbers[i].innerHTML = '';
    for (j=10;j>=0;j--) {
      numbers[i].innerHTML += '<span class="unit unit-'+j+'">'+(j < 10 ? j : 0)+'</span>';
    }
    units = livebalance_select('unit', 'span', numbers[i]);
    for (var j in units) {
      offsetwidth = units[j].offsetWidth;
      width = offsetwidth > width ? offsetwidth : width;
      units[j].style.display = 'block';
    }
    numbers[i].style.display = 'inline-block';
    numbers[i].style.height = height+'px';
    numbers[i].style.width = width+'px';
    numbers[i].style.cssFloat = 'left';
    numbers[i].style.styleFloat = 'left';
    numbers[i].style.position = 'relative';
    numbers[i].style.top = -((height*10)-(default_number*height))+'px';
    width_total += width;
  }
  var symbols = livebalance_select('symbol', 'span', livebalance);
  for (var i in symbols) {
    symbols[i].style.display = 'inline-block';
    symbols[i].style.height = height+'px';
    symbols[i].style.cssFloat = 'left';
    symbols[i].style.styleFloat = 'left';
    symbols[i].style.position = 'relative';
    symbols[i].style.verticalAlign = 'top';
    width_total += symbols[i].offsetWidth;
  }
  var livebalance = document.getElementById("livebalance");
  livebalance.style.width = width_total+'px';
}

// Linear easing calculation.
// t: current time, b: beginning, c: difference, d: duration.
function livebalance_linear(t, b, c, d) {
    return c*t/d+b;
};

// Acceleration quadratic easing calculation.
// t: current time, b: beginning, c: difference, d: duration.
function livebalance_accelerate(t, b, c, d) {
    return c*(t/=d)*t+b;
};

// Elastic bounce out easing calculation.
// t: current time, b: beginning, c: difference, d: duration, a: amplitude, p: period.
function livebalance_elastic(t, b, c, d, a, p) {
  if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
  if (a < Math.abs(c)) { a=c; var s=p/4; }
  else var s = p/(2*Math.PI)*Math.asin(c/a);
  return a*Math.pow(2,-10*t)*Math.sin((t*d-s)*(2*Math.PI)/p)+c+b;
};

// Moves one column number to the next digit.
// e: element, t: current time, b: beginning, h: digit height, dur: digit duration, z: 10 digit height,
// mrd ao mrc oto oo td dl hh op: precalculated values.
// del: controls the "framerate".
function livebalance_tween(e, t, b, h, dur, z, mrd, ao, mrc, oto, oo, td, dl, hh, op, del) {
    setTimeout(
      function (e, t, b, h, dur, z, mrd, ao, mrc, oto, oo, td, dl, hh, op, del) {
          // Get offset value from easing function.
          if (t < dur) {  // in
            var current = livebalance_accelerate(t, b, h, dur);
          }
          else if (t < oto) { // linear
            var current = livebalance_linear(t-dur, ao, mrc, mrd);
          }
          else { // out
            var current = livebalance_elastic(t-oto, oo, hh, td, hh, op);
            del -= ((t-oto)/td)*del/2; // The bigger the constant at the end the less the delay decays.
          }
          // Compensate for strip offsets greater than the size of the strip
          current = Math.round(current % z);
          if (current > 0) {
            current -= z;
          }
          // Move the strip to the correct position
            e.style.top = current+'px';
          // Increment time
            t++;
          // If within duration, queue another loop
          if (t <= dl) {
              livebalance_tween(e, t, b, h, dur, z, mrd, ao, mrc, oto, oo, td, dl, hh, op, del);
          }
      },
      del, e, t, b, h, dur, z, mrd, ao, mrc, oto, oo, td, dl, hh, op, del
    );
}

//Animates from 'from' to 'to' - string patterns should match.
//spin_all: if true will spin all the numbers even if not needed.
//Return estimated animation time.
function livebalance_animate(livebalance, from, to, spin_all) {
    var dur = 30;  // approximate duration of one digit ticking over, used in calculations.
    var del = 20;
    var from_val = livebalance_trim(livebalance_balance(from));
    var to_val = livebalance_trim(livebalance_balance(to));
    // Do an early return if no processing required.
    if (from_val == to_val) {
     return false;
    }
    var from_val_parts = from_val.split('.', 2);
    var to_val_parts = to_val.split('.', 2);
    var i, j, p, v, x, e, bpx, b, h, tg, c, d, z, t, a, mrd, ao, c, oto, oo, dd, td, dl;
    var anim_time = 0;
    for (i = 0; i <= 1; i++) {
     if (from_val_parts[i] != undefined){
       for (j = 1; j <= from_val_parts[i].length; j++) {
         // Get position of the number
         p = (i == 0) ? from_val_parts[i].length-j : j-1;
         // Get the value of the number at that position
         v = parseInt(to_val_parts[i].charAt(p));
         x = parseInt(from_val_parts[i].charAt(p));
         if (spin_all || v != x) { // Only spin the number if it has to change
           e = livebalance_select((i == 0 ? 'integer-'+j : 'fraction-'+j), 'span', livebalance); // Element
           bpx = e[0].style.top; // Current offset in CSS
           b = parseInt(bpx.replace('px', '')); // Current offset in int
           h = e[0].offsetHeight; // Height of one number
           z = h*10; // The height of 10 digits ('zero' wraparound)
           tg = -(z-v*h); // Go to nearest number (target)
           // Force spinning in one direction (next digit instead of nearest digit)
           if (tg <= b/*+h*/) {  // The +h would force consecutive number changes to do a full spin first.
             tg += z;
           }
           c = tg-b; // Get the diff between beginning and end
           d = dur*Math.abs(c/h); // The duration of the spin for this number
           t = 0; // Time
           mrd = (d-(dur*2))/2; // Max 'run' duration
           ao = b+h; // Acceleration offset
           oto = dur+mrd; // Overshoot time offset
           mrc = c-(h*2)+(h/2); // Max 'run' displacement
           oo = ao+mrc; // Overshoot (distance) offset
           td = dur*3; // Triple duration
           dl = td+mrd; // Duration limit
           hh = h/2; // Half height
           op = dur*1.2; // One point (two)
           livebalance_tween(e[0], t, b, h, dur, z, mrd, ao, mrc, oto, oo, td, dl, hh, op, del);
         }
         if (dl > anim_time) {
           anim_time = dl;
         }
        }
      }
    }
    return anim_time;
}

// Perform a source/pattern replacement (helper for livebalance_reformat_pattern()).
function livebalance_source_pattern_replace(source, pattern, i, j) {

  var replacement = new Array(pattern.length);
  var c;
  while (i != j) {
    c = pattern[i];
    if (!isNaN(parseInt(c))) {
      replacement[i] = source.charAt(i<j ? c : source.length-c);
      if (replacement[i] == '') {
        replacement[i] = 0;
      }
    }
    else {
      replacement[i] = c;
    }
    i<j ? i++ : i--;
  }
  return replacement;
}

// Rewrite old_balance using the format of new_balance if the new balance's integer section is longer than the old balance
function livebalance_reformat_pattern(old_inner, new_inner) {
  // Trim both incoming values to make it fair.

  old_inner = livebalance_trim(old_inner);
  new_inner = livebalance_trim(new_inner);

  // Do an early return if no processing required.
  if (old_inner == new_inner) {
    return old_inner;
  }
  // Figure out some shit about the numbers.
  var old_balance = livebalance_balance(old_inner);
  var new_balance = livebalance_balance(new_inner);
  var old_bal_parts = old_balance.split('.', 2);
  var new_bal_parts = new_balance.split('.', 2);

  // Now the pattern to use is decided.  We are to assume fractions don't change.
  var source_number = old_bal_parts;
  var target_pattern = new_inner;
  var target_parts = new_bal_parts;
  var column = target_parts[0].length;
  var stage = 0;
  var pattern = new Array(5);
  pattern[0] = []; // prefix
  pattern[1] = []; // integer
  pattern[2] = []; // radix
  pattern[3] = []; // fraction
  pattern[4] = []; // suffix

  for (i=0;i<target_pattern.length;i++) {
    c = target_pattern.charAt(i);
    if ((c == '.' && stage == 1) || (isNaN(parseInt(c)) && stage == 3)) {  // to do: this assumes first NAN hit after the decimal is the suffix (no way around that?? remove suffix section?)
      stage++;
    }
    if (c != ' ' && !isNaN(parseInt(c))) {
      if (stage == 0 || stage == 2) {
        stage++;
      }
      pattern[stage].push(column);
      (stage > 2 ? column++ : column--);
    }
    else {
      pattern[stage].push(c);
    }
  }

  pattern[1] = livebalance_source_pattern_replace(source_number[0], pattern[1], pattern[1].length-1, -1);
  pattern[3] = livebalance_source_pattern_replace(source_number[1], pattern[3], 0, pattern[3].length+1);
  for (var i in pattern) {
    pattern[i] = pattern[i].join('');
  }
  return pattern.join('');
}

// Live Balance script - updated account balance every 60 seconds
var livebalanceHTTP = getHTTPObject();
function livebalance_go(request) {
  if (request == true) {
    livebalanceHTTP.open('get', '/livebalance');
    livebalanceHTTP.onreadystatechange = livebalance_response;
    livebalanceHTTP.send(null);
  }
  setTimeout("livebalance_go(true)", 60000);
}

// Live Balance AJAX updater.
function livebalance_response() {
  if (livebalanceHTTP.readyState == 4) {
    if (livebalanceHTTP.responseText.length > 0) {
      var livebalance = document.getElementById("livebalance");
      // Incoming ajax
      var new_balance = livebalanceHTTP.responseText;
      // Process ajax
      var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
      if (isIE6) {
        // If this is IE6, simply change the number, but do not animate.
        livebalance.innerHTML = livebalance_markup(new_balance);  // update live balance
        livebalance_raw = new_balance; // update global var
        var livebalance_account = document.getElementById("livebalance_account");
        if (livebalance_account) {
          livebalance_account.innerHTML = new_balance;  // update account balance
        }
      }
      else {
        var temp_balance = livebalance_reformat_pattern(livebalance_raw, new_balance);  // convert old price to new price's format
        livebalance.innerHTML = livebalance_markup(temp_balance);  // update live balance
        livebalance_markup_strips(livebalance); // add strips of surrounding numbers
        livebalance_raw = new_balance; // update global var
        // animate
        var del = livebalance_animate(livebalance, temp_balance, new_balance, true);
        if (del != false && del > 0) {
          // Update account page balance
          var livebalance_account = document.getElementById("livebalance_account");
          if (livebalance_account) {
            setTimeout(
              function (livebalance_account, new_balance) {
                livebalance_account.innerHTML = new_balance;  // update account balance
              },
              del*20, livebalance_account, new_balance  // 20ms is the del factored into the recursion
            );
          }
        }
      }
    }
    else {
      location.reload(true);
    }
  }
}

// Loader for Live Balance, gets things going.
function livebalance_loader() {
  var lb_wrapper = document.getElementById("livebalance_wrapper");
  if (lb_wrapper) {
    lb_wrapper.style.height = lb_wrapper.offsetHeight+'px';
    lb_wrapper.style.width = '100%';
    var livebalance = document.getElementById("livebalance");
    livebalance.style.height = livebalance.offsetHeight+'px';
    livebalance.style.overflow = 'hidden';
    livebalance.style.cssFloat = 'right';
    livebalance.style.styleFloat = 'right';
    // Set the current raw balance value
    livebalance_raw = livebalance.innerHTML;
    livebalance_go();
  }
}

window.onload = livebalance_loader;


// MoneyBookers receipt AJAX script - check transaction status every 5 seconds.
var mbreceiptHTTP = getHTTPObject();
function moneybookers_receipt_go() {
  mbreceiptHTTP.open('get', window.location.href + "&moneybookers=1&ajax=1");
  mbreceiptHTTP.onreadystatechange = moneybookers_receipt_response;
  mbreceiptHTTP.send(null);
  setTimeout("moneybookers_receipt_go()", 5000);
}

// MoneyBookers receipt AJAX updater.
function moneybookers_receipt_response() {
  if (mbreceiptHTTP.readyState == 4) {
    if (mbreceiptHTTP.responseText.length > 0) {
      // Incoming ajax
      if (mbreceiptHTTP.responseText != 'PENDING')
      {
        //location.reload(true);
        location.href = window.location.href + "&moneybookers=1";
      }
    }
  }
}

// Loader for MoneyBookers receipt AJAX, gets things going.
function moneybookers_receipt_loader() {
  var mb_element = document.getElementById("moneybookers-receipt-ajax");
  if (mb_element) {
    setTimeout("moneybookers_receipt_go()", 2000);
  }
}

window.onload = moneybookers_receipt_loader;


