/* 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=yes,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 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 = ""
        }
}

// Ajax object
function getHTTPObject()
{
   if(window.ActiveXObject)
      return new ActiveXObject("Microsoft.XMLHTTP");
   else
      if(window.XMLHttpRequest)
         return new XMLHttpRequest();
      else
         return null;
}

/**
 * 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;
