/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
/*  Prototype JavaScript framework, version 1.4.0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  THIS FILE IS AUTOMATICALLY GENERATED. When sending patches, please diff
 *  against the source tree, available from the Prototype darcs repository.
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.4.0',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.inspect = function(object) {
  try {
    if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}

/*--------------------------------------------------------------------------*/

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}
Object.extend(String.prototype, {
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(eval);
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function() {
    return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
  }
});

String.prototype.parseQuery = String.prototype.toQueryParams;

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value >= (result || value))
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value <= (result || value))
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      iterator(value = collections.pluck(index));
      return value;
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  shift: function() {
    var result = this[0];
    for (var i = 0; i < this.length - 1; i++)
      this[i] = this[i + 1];
    this.length--;
    return result;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    do {
      iterator(value);
      value = value.succ();
    } while (this.include(value));
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type',
        'application/x-www-form-urlencoded');

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval(this.header('X-JSON'));
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(child);
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element) {
  var Element = new Object();
}

Object.extend(Element, {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      Element[Element.visible(element) ? 'hide' : 'show'](element);
    }
  },

  hide: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = 'none';
    }
  },

  show: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = '';
    }
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).add(className);
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).remove(className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i];
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        Element.remove(node);
    }
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (name in style)
      element.style[name.camelize()] = style[name];
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow;
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
  },

  undoClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element.style.overflow = element._overflow;
    element._overflow = undefined;
  }
});

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        if (this.element.tagName.toLowerCase() == 'tbody') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Field = {
  clear: function() {
    for (var i = 0; i < arguments.length; i++)
      $(arguments[i]).value = '';
  },

  focus: function(element) {
    $(element).focus();
  },

  present: function() {
    for (var i = 0; i < arguments.length; i++)
      if ($(arguments[i]).value == '') return false;
    return true;
  },

  select: function(element) {
    $(element).select();
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
  }
}

/*--------------------------------------------------------------------------*/

var Form = {
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name)
      return inputs;

    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
          (name && input.name != name))
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

  disable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
  },

  enable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
  },

  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    Field.activate(Form.findFirstElement(form));
  },

  reset: function(form) {
    $(form).reset();
  }
}

Form.Element = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter)
      return parameter[1];
  }
}

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.Serializers.textarea(element);
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
    }
    return false;
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value;
      if (!value && !('value' in opt))
        value = opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = new Array();
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected) {
        var optValue = opt.value;
        if (!optValue && !('value' in opt))
          optValue = opt.text;
        value.push(optValue);
      }
    }
    return [element.name, value];
  }
}

/*--------------------------------------------------------------------------*/

var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        case 'password':
        case 'text':
        case 'textarea':
        case 'select-one':
        case 'select-multiple':
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    this._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + name, observer);
    }
  }
});

/* prevent memory leaks in IE */
Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  clone: function(source, target) {
    source = $(source);
    target = $(target);
    target.style.position = 'absolute';
    var offsets = this.cumulativeOffset(source);
    target.style.top    = offsets[1] + 'px';
    target.style.left   = offsets[0] + 'px';
    target.style.width  = source.offsetWidth + 'px';
    target.style.height = source.offsetHeight + 'px';
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      valueT -= element.scrollTop  || 0;
      valueL -= element.scrollLeft || 0;
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}
//make sure that page isn't loaded in frameset.
if (self != top) { top.location.href = self.location.href }

try {
	var $j = jQuery.noConflict();
} catch(e) {}
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
	if(timeout)
	{
		timeout.set(); //reset page timeout
	}
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

function addEvent(obj, e, func) {
	try{
		if (isIe()) {
			obj.attachEvent('on' + e, func);
		} else {
			obj.addEventListener(e, func, false);
		}
	}catch(e){}
}

function getTarget(e) {
	return (isIe() ? e.srcElement : e.target);
}

function mu_menu_over(oObj) {
	oObj.className = 'hover';
}

function mu_menu_out(oObj) {
	oObj.className = '';
}

function mu_menu_goto(oObj) {
	var link = oObj.getElementsByTagName('a');
	location.href = link[0].href;
}

function popWindow(url, sizeX, sizeY)
{
	return window.open(url, "_blank", "width=" + sizeX + ",height=" + sizeY + ",status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
}
function popGamingTest(url, sizeX, sizeY)
{
	window.open(url, "g4gaming", "width=" + sizeX + ",height=" + sizeY + ",status=no,toolbar=no,menubar=no,location=no,scrollbars=no");
}
function popThawte(url)
{
	var sizeX = 500;
	var sizeY = 625;
	window.open("https://www.thawte.com/core/process?process=public-site-seal-cert-details&public-site-seal-cert-details.referer=http://" + url, "thawtePopup", "width=" + sizeX + ",height=" + sizeY + ",status=no,toolbar=no,menubar=no,location=no,scrollbars=no");
}
function popAgeVerification(url, sizeX, sizeY)
{
	window.open(url, "ageVer", "width=" + sizeX + ",height=" + sizeY + ",status=no,toolbar=no,menubar=no,location=no,scrollbars=no");
}
function openHelpCenter(url)
{
	window.open(url, "iCenter", "width=745, height=600, status=no, toolbar=no, menubar=no, location=no");
}

var activeInfoIcon;
function showInfoTip(obj,h3_text,paragraph_text) {

	if(activeInfoIcon == obj && document.getElementById('tooltip').style.display == 'block'){
		hideInfoTip();
	}else{
		activeInfoIcon = obj;

		var iconPosition = Position.cumulativeOffset(activeInfoIcon);
		var offsetLeftToIcon;
		if (iconPosition[0] > 800) {
			// If position is on the right side of the page
			// the tooltip should be shown to the left of the info icon.
			offsetLeftToIcon = -260;
		} else {
			offsetLeftToIcon = 20;
		}

		Position.clone(activeInfoIcon, document.getElementById('tooltip'), {setHeight: false, setWidth: false, offsetLeft: offsetLeftToIcon});

		var h3 = document.getElementById('tooltip').getElementsByTagName('h3')[0];
		var p = document.getElementById('tooltip').getElementsByTagName('p')[0];

		h3.innerHTML = h3_text;
		p.innerHTML = paragraph_text;

		document.getElementById('tooltip').style.display = 'block';
	}
}

function hideInfoTip() {
	document.getElementById('tooltip').style.display = "none";
}

function enumerate(arr) {
	for (var i=0; i < arr.length; i++){
		eval(arr[i] + ' = ' + i + ';');
	}
}
function isIe() {
	return browserCheck('msie');
}
function isGecko() {
	return browserCheck('gecko');
}
function isOpera() {
	return browserCheck('opera');
}
function browserCheck(string) {
	return (navigator.userAgent.toLowerCase().indexOf(string) > -1) ? true : false;
}
function hideLoggedOutMsg() {
	location.reload();
	//document.body.className = 'active';
	//document.body.parentNode.className = 'active';
}
function showLoggedOutMsg() {
	document.body.className = 'inactive';
	document.body.parentNode.className = 'inactive';
}

var globalTimer = new Array();
function Timer(m) {

    var nr = globalTimer.length;
	globalTimer[nr] = this;
	var ms = m * 60000;
	var timer;

	this.set = set;
	this.pageReload = pageReload;
	this.showTimeout = showTimeout;
	set();

	function set() {
		clearTimeout(timer);
		timer = setTimeout('globalTimer[' + nr + '].showTimeout()', ms);
	}

	function pageReload() {
		location.reload();
	}

	function showTimeout() {
		document.body.className = 'inactive';
		document.body.parentNode.className = 'inactive';
	}

}

var BrowserDetect = {
	run: addEvent(window, 'load', function() { BrowserDetect.init(); }),
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
function displayHelpText(obj, hideObj) {
	var info = obj.parentNode.parentNode.getElementsByTagName("div");
		if(!info.length)
			return;

		for(var i=0;i<info.length;i++)
		{
			if(info[i].className == "info")
			{
				info[i].style.display = "block";
				break;
			}
		}

		if(hideObj != null)
		{
			hideObj = document.getElementById(hideObj);
			hideObj.showStatus = hideObj.style.display;
			hideObj.style.display = "none";
		}
}

function hideHelpText(obj, hideObj) {
	var info = obj.parentNode.parentNode.getElementsByTagName("div");
		if(!info.length)
			return;

		for(var i=0;i<info.length;i++)
		{
			if(info[i].className == "info")
			{
				info[i].style.display = "none";
				break;
			}
		}

		if(hideObj != null)
		{
			hideObj = document.getElementById(hideObj);
			hideObj.style.display = hideObj.showStatus;
		}
}

var flashhover_id = null;
function flashhover(id) {
	if (flashhover_id === null && id) {
		document.getElementById(id).className = 'go';
		document.getElementById('flashhover').className = 'go';
		flashhover_id = id;
	} else if (flashhover_id !== null) {
		document.getElementById(flashhover_id).className = 'wait';
		document.getElementById('flashhover').className = 'wait';
		flashhover_id = null;
	}
}

// TODO: Activate the timer instead of setting it to a bogus value
//var timeout = new Timer(1);
var timeout = false;

function toggleMe(id) {
	document.getElementById(id).style.display = (document.getElementById(id).style.display == 'none' || document.getElementById(id).style.display == '') ? 'inline' : 'none';
}

function checkVista() {
	if (!navigator.userAgent.match("Windows NT 6.0")) {
		document.getElementById('winVista').style.display = "none";
	} else {
		document.getElementById('win32').style.display = "none";
	}
}

var Footer = {
	run: addEvent(window, 'load', function() { Footer.init(); }),
	init: function() {
		var pageFooter = document.getElementById('pageFooter');
		if (pageFooter == null) return;
		var footerAnchors = pageFooter.getElementsByTagName('a');
		for (var i = 0; i < footerAnchors.length; i++) {
			if (footerAnchors[i].className.indexOf('footerLink') > -1) {
				try {
					eval("addEvent(footerAnchors[i], 'click', function () { Footer.popup('" + footerAnchors[i].getAttribute('href') + "'); });");
					footerAnchors[i].setAttribute('target', '_self');
					footerAnchors[i].setAttribute('href', 'javascript:void(0)');
				} catch(e) {}
			}
			if (footerAnchors[i].className.indexOf('footerButton') > -1) {
				try {
					addEvent(footerAnchors[i], 'mouseover', Footer.uTooltipShow);
					addEvent(footerAnchors[i], 'mouseout', Footer.tooltipHide);
				} catch(e) {}
			}
		}

		// enable tooltips for divs as well
		var footerDivs = pageFooter.getElementsByTagName('div');
		for (var j = 0; j < footerDivs.length; j++) {
			if (footerDivs[j].getAttribute('tooltip')) {
				try {
					addEvent(footerDivs[j], 'mouseover', Footer.tooltipShow);
					addEvent(footerDivs[j], 'mouseout', Footer.tooltipHide);
				} catch(e) {}
			}
		}
	},
	popup: function(href) {
		window.open(href,'win_terms','toolbar=0,rezisable=0,scrollbars=1,width=500,height=450');
	},
	tooltipShow: function(e) {
		var target = getTarget(e);
		var tt = document.getElementById('footerTooltip');
		var tip = target.getAttribute('tooltip');
		if (tip != '') {
			tt.getElementsByTagName('div')[0].innerHTML = tip;
			tt.style.display = 'block';
			Position.clone(target, tt, {setHeight: false, setWidth: false, offsetLeft: 10, offsetTop: (-tt.offsetHeight - 5)});
		}
	},
	uTooltipShow: function(e) {
		var target = getTarget(e);
		var tt = document.getElementById('footerTooltip');
		var tip = document.getElementById(target.id + 'Content').innerHTML;
		if (tip != '') {
			tt.getElementsByTagName('div')[0].innerHTML = tip;
			tt.style.display = 'block';
			Position.clone(target, tt, {setHeight: false, setWidth: false, offsetLeft: 10, offsetTop: (-tt.offsetHeight - 5)});
		}
	},
	tooltipHide: function() {
		var tt = document.getElementById('footerTooltip');
		tt.style.display = 'none';
	}
};

function getIframeDocument(name){
	try {
		var oIframe = document.getElementById(name);
		var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
		if (oDoc.document) oDoc = oDoc.document;
		return oDoc;
	} catch(e) {
		return null;
	}
}

var sessionExpired_savedYpos;
function sessionExpired(enabled) {

    // Handle height and overflow to prevent scrolling down past the overlay
    var height = enabled ? '100%' : 'auto';
    var overflow = enabled ? 'hidden' : 'auto';

    bod = document.getElementsByTagName('body').item(0);
    bod.style.height = height;
    bod.style.overflow = overflow;
    htm = document.getElementsByTagName('html').item(0);
    htm.style.height = height;
    htm.style.overflow = overflow;


	var ie = navigator.userAgent.toLowerCase().indexOf('msie') + 1;
	if (ie) {
        if(enabled) {
        	if (self.pageYOffset) {
        		sessionExpired_savedYpos = self.pageYOffset;
        	} else if (document.documentElement && document.documentElement.scrollTop){
        		sessionExpired_savedYpos = document.documentElement.scrollTop;
        	} else if (document.body) {
        		sessionExpired_savedYpos = document.body.scrollTop;
        	}
        } else {
            window.scrollTo(0, sessionExpired_savedYpos);
        }
    }

    if(enabled) {
        window.scrollTo(0,0);
        $('sessionExpireOverlay').style.height = document.body.clientHeight + "px";
        $('sessionExpireOverlay').style.width = document.body.clientWidth + "px";
    	uHideSelect('none');
    }else{
    	uHideSelect('block');
    }
    try {
		$('sessionExpireOverlay').blur(); // fix for FF first click bug
		$('sessionExpireOverlay').style.display = enabled ? 'block' : 'none';
		$('sessionExpireBox').style.display = enabled ? 'block' : 'none';
	} catch(e) {}


}

function clearPwd(defaultUsername) {
	if ($('loginPassword').value == 'password') {
		$('loginPassword').value = '';
	}
	
	if ($('loginUsername').value == defaultUsername) {
		$('loginUsername').value = '';
	}
}
function uHideSelect(vShow) {
  var xSelects = document.getElementsByTagName('SELECT');
	for (var j = 0; j < xSelects.length; j++) {
			xSelects[j].style.display = vShow;
		}
}


function isIe() {
	return browserCheck('msie');
}

function isGecko() {
	return browserCheck('gecko');
}

function isOpera() {
	return browserCheck('opera');
}

function browserCheck(string) {
	return (navigator.userAgent.toLowerCase().indexOf(string) > -1) ? true : false;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
window.pageIsLoaded= false;

/**
* Utility method for opening a tooltip related to any node in a document. To prevent bug
* in IE when the toltip tries to display before the page is fully loaded, this event
* handler needs to be added to each page body that want to use it: 
* body onload="window.pageIsLoaded= true;"
* 
* Usage:
* onmouseover="showTooltip(this, event, 'A text');
* onmouseover="showTooltip(this, event, 'Another text','#DCEDB8','#333333','#333333');
*
* @param invoker the element that the mouseover function is tied to. Just the "this" reference.
* @param theEvent the event that the mouseover event throws. The reference to the event
*				  object needs to be passed in exactly as in the usage instruction to 
*				  make the function event handling cross browser.
* @param text the text to display in the tooltip
* @param backcolor the background color of the tooltip. Any valid html color code. Optional.
* @param bordercolor the border color of the tooltip. Any valid html color code. Optional.
* @param textcolor the text color of the tooltip. Any valid html color code. Optional.
* @param width the width of the tooltip in pixels. Any positive number. Optional.
*/
function showTooltip(invoker, theEvent, text, backcolor, bordercolor, textcolor, width){
	if(window.pageIsLoaded){
	
		if(!text || text == '')
			return;
			
		var localEvent = theEvent ? theEvent : window.event;
	
		var containerId= "newDHTMLToolTip";	
		var contentId= "newDHTMLToolTipContent";
		
		backcolor= backcolor ? backcolor : "#DCEDB8";
		bordercolor= bordercolor ? bordercolor : "#333333";
		textcolor= textcolor ? textcolor : "#333333";

		var toolTip= document.getElementById(containerId);
		if(!toolTip){
			var toolTip= document.createElement("div");
			toolTip.id= containerId;
			toolTip.style.position= "absolute";
			toolTip.style.visibility= "hidden";
			toolTip.style.height= "10";
			toolTip.style.zIndex= 1000;
			toolTip.style.left= "0";
			toolTip.style.top= "0";
		
			var table= toolTip.appendChild(document.createElement("table"));
			table.style.borderColor= bordercolor;
			table.style.borderStyle= "solid";
			table.style.borderWidth= "1px";
			table.style.backgroundColor= backcolor;
			var tbody= table.appendChild(document.createElement("tbody"));
			var tr= tbody.appendChild(document.createElement("tr"));
			var td= tr.appendChild(document.createElement("td"));
			td.id= contentId;
			td.style.fontFamily= "Tahoma, Arial, Helvetica, sans-serif";
			td.style.fontSize= "11px";
			td.style.color= textcolor;
		
			document.body.appendChild(toolTip);
		}

		var contentContainer= document.getElementById(contentId);
		if(contentContainer.childNodes[0]){
			var node= contentContainer.childNodes[0];	
			node.parentNode.removeChild(node);
		}
		contentContainer.appendChild(document.createTextNode(text));
		
		if(width){
			contentContainer.style.width= width + "px";
		}
	
		toolTip.style.top=document.body.scrollTop+localEvent.clientY+20;
	
		if ((localEvent.x + toolTip.clientWidth) > (document.body.clientWidth + document.body.scrollLeft)){	
			toolTip.style.left = (document.body.clientWidth + document.body.scrollLeft) - toolTip.clientWidth-10;
		} else {
			toolTip.style.left=document.body.scrollLeft+localEvent.clientX
		}
		
		invoker.toolTip= toolTip;
		invoker.onmouseout= internal_hideTooltip;	
			
		toolTip.style.visibility="visible"
	}
}
function internal_hideTooltip(){
	var toolTip= this.toolTip;
	
	if(toolTip != null){
    	toolTip.style.visibility= "hidden"
    	toolTip.style.left = 1;
    	toolTip.style.top = 1;
    	    
    	return false;
    }
}

/**
* Helper method that dynamically builds an url from the content
* and action of a form and opens a new window with the newly created url
*
* Usage:
* openPopupFromForm("aFormId", 
*			  "aWindowName",
* 			  "scrollbars_yes,width=460", 
*			  "paramOne", "aValue", "paramTwo", "anotherValue");
* 
* @param action the action url to forward to
* @param formId the id of the form to construct the url params from
* @param windowName the name of the newvly opened window. Used to get a handle to it.
* @param windowArgs the string that defines the behaviour of the window (height, width etc.)
* @param extraParamName the name of a variable length argument list of extra parameters
*				that should be appended to the url
* @param extraparamValue the value of a variable length argument list of extra parameters
*				that should be appended to the url
*/
function openPopupFromForm(formId, action, windowId, windowArgs, extraparamName, extraParamValue){
	var url= action;

	var form= document.getElementById(formId);

	//Copy fields in array
	for(var i=0;i<form.elements.length;i++){
		var element= form.elements[i];
			
		url+= url.indexOf("?") == -1 ? "?" : "&";
		url+= element.name + "=" + element.value;
	}
	
	//Add extra arguments
	for(var i=3;i<arguments.length;i+=2){
		url+= url.indexOf("?") == -1 ? "?" : "&";
		url+= arguments[i] + "=" + arguments[i+1];
	}				

	window.open(url, windowId, windowArgs);
}

/**
* Convenience method to get a reference to an element. 
*
* @param elementId the id of the element
*/
function getElm(id){
	return document.getElementById(id);
}

/**
* Convenience method to set the content of an element with innerHTML 
*
* @param elementId the id of the element
* @param content the html content of the element
* @param setOnlyIfExists optional parameter used to make the setting of the content
*		silently stop if no element is found. If parameter is not specified or false, 
*		an error will occur if the element does not exist
*/
function setElm(id, content, setOnlyIfExists){
	var elm= getElm(id);
	if(elm == null && setOnlyIfExists){
		return;
	}
	elm.innerHTML= content;
}

/**
* Convenience method to show or hide an element. 
*
* @param elementId the id of the element, if the element can't be found, nothing happens.
* @param show boolean indicating if the element should show or not
*/
function showElm(elementId, show){
	var element= getElm(elementId);
	if(element){
		if(show){
			element.style.display = "block";
    		element.style.visibility = "visible";
		}else{
    		element.style.display = "none";
			element.style.visibility = "hidden";
		}
	}
}

/**
* Convenience method to set the top position of an element
*
* @param elementId the id of the element, if the element can't be found, nothing happens.
* @param topValue the top position in pixels, ex. "55"
*/
function setElmTop(elementId, topValue){
	var element= getElement(elementId);
	if(element){
		element.style.top= topValue;
	}
}

function getParentElement(elm, tagName){
	var obj = elm;

	if(obj.parentNode){
		while (obj = obj.parentNode) {
			if(obj.tagName == tagName){
				return obj;
			}
		}
	}
} 

<!-- Retrieve password functions -->
function retPwd_showRetrievePasswordBox()
{
	var obj = document.getElementById("retrieve-password");

	document.getElementById("retrieve-area-lost").style.display = "block";
	document.getElementById("retrieve-area-send").style.display = "block";

	if(obj.style.display == "block")
	{
		obj.style.display = "";
	}
	else
	{
		obj.style.display = "block";
	}
}

/*
	Use this script to construct messages displayed for end users. The function takes a set of objects,
	formats them, then inserts the formatted strings into the pattern at the appropriate places.

	Example:
	var msg="This is the {0} time I'm {1} today";
	alert(msgFormat.format(msg, "7th", "eating"));
	returns This is the 7th time I'm eating today

	Created by: Yossi Admon
*/
if(typeof(msgFormat)=='undefined'){
  msgFormat=new Object();
  msgFormat.format=function(s){
    var i=1;
    while(i<arguments.length) s=s.replace("{"+(i-1)+"}",arguments[i++]);
    return s;
  }
}

function retPwd_postRetrievePassword(url)
{
	var oObj = document.getElementById("lost_username");
	var myConn = new XHConn();
	if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
	myConn.connect(url, "POST", "username=" + escape(oObj.value), retPwd_data_postRetrievePassword);
}

function retPwd_data_postRetrievePassword(oResult)
{
	document.getElementById("retrieve-area-lost").style.display = "none";
	document.getElementById("retrieve-area-send").style.display = "block";
	document.getElementById("retrieve-area-send").innerHTML = oResult.responseText;
}


<!-- SITE_TEXT_NOT_DONE -->
var ERROR_CURRENCY = "The amount you have specified is not a transfer amount!";

function doAccountSummaryRefresh(){
	refreshAllAccountSummary();
}

function refreshAllAccountSummary() {
	getHttpConnection().connect("/myunibet/refresh.do?r=0&lobby="+selectedLobby, "POST", "", handleRefreshAllResponse);
}
function refreshAccountInfo() {
	getHttpConnection().connect("/myunibet/refresh.do?r=1&lobby="+selectedLobby, "POST", "", handleAccountInfoResponse);
}
function refreshBingoInfo() {
	getHttpConnection().connect("/myunibet/refresh.do?r=2&lobby="+selectedLobby, "POST", "", handleBingoInfoResponse);
}
function refreshCasinoInfo() {
	getHttpConnection().connect("/myunibet/refresh.do?r=3&lobby="+selectedLobby, "POST", "", handleCasinoInfoResponse);
}
function refreshPokerInfo() {
	getHttpConnection().connect("/myunibet/refresh.do?r=4&lobby="+selectedLobby, "POST", "", handlePokerInfoResponse);
}

function refreshCasinoWallet() {
	if (casinoOpened) {
		getHttpConnection().connect("/myunibet/refresh.do?r=5&lobby="+selectedLobby, "POST", "", toggleSubAccountSilent);
	}
}

function refreshBingoWallet() {
	getHttpConnection().connect("/myunibet/refresh.do?r=7&lobby="+selectedLobby, "POST", "", toggleSubAccountSilent);
}

function refreshUnibetcasinoWallet() {
  getHttpConnection().connect("/myunibet/refresh.do?r=8&lobby="+selectedLobby, "POST", "", toggleSubAccountSilent);
}


function handleRefreshAllResponse(response) {
    handleRefreshAll(eval(response.responseText));
}

function handleRefreshAll(objRes) {
	setElm("userName", objRes.userName);
	setElm("userNumber", objRes.userNumber);
	setElm("accountCashWithBonus", objRes.accountCashWithBonus);
	setElm("accountCashWithoutBonus", objRes.accountCashWithoutBonus);

	accountInfoActivateAccount("bingo", objRes.bingoConnectError, objRes.registeredAtBingo);
	if (selectedLobby == 'bingo' && objRes.registeredAtBingo) {
		makeOtherAccountVisible();
		setWalletVisibility(true);
		openSubAccount('bingo');
	}

	accountInfoActivateAccount("casino", objRes.casinoConnectError, objRes.registeredAtCasino);
	if (selectedLobby == 'casino' && objRes.registeredAtCasino) {
	 	makeOtherAccountVisible();
		setWalletVisibility(true);
		clickSubAccount('casino');
	}

  accountInfoActivateAccount("unibetcasino", objRes.unibetcasinoConnectError, objRes.registeredAtUnibetcasino);

	accountInfoActivateAccount("poker", objRes.pokerConnectError, objRes.registeredAtPoker);
	if (selectedLobby == 'poker' && objRes.registeredAtPoker) {
		makeOtherAccountVisible();
		setWalletVisibility(true);
		clickSubAccount('poker');
	}
}

function handleAccountInfoResponse(response) {
    var objRes = eval(response.responseText);
	setElm("userName", objRes.userName);
	setElm("userNumber", objRes.userNumber);
	setElm("accountCashWithBonus", objRes.accountCashWithBonus);
	setElm("accountCashWithoutBonus", objRes.accountCashWithoutBonus);
}

function handleBingoInfoResponse(response) {
    var objRes = eval(response.responseText);
	accountInfoActivateAccount("bingo", objRes.bingoConnectError, objRes.registeredAtBingo);
	if (selectedLobby == 'bingo' && objRes.registeredAtBingo) {
		makeOtherAccountVisible();
		setWalletVisibility(true);
		openSubAccount('bingo');
	}
}

function handleCasinoInfoResponse(response) {
    var objRes = eval(response.responseText);
	accountInfoActivateAccount("casino", objRes.casinoConnectError, objRes.registeredAtCasino);
	if (selectedLobby == 'casino' && objRes.registeredAtCasino) {
	 	makeOtherAccountVisible();
		setWalletVisibility(true);
		clickSubAccount('casino');
	}
}

function handleUnibetcasinoInfoResponse(response) {
    var objRes = eval(response.responseText);
  accountInfoActivateAccount("unibetcasino", objRes.unibetcasinoConnectError, objRes.registeredAtUnibetasino);
}

function handlePokerInfoResponse(response) {
    var objRes = eval(response.responseText);
	accountInfoActivateAccount("poker", objRes.pokerConnectError, objRes.registeredAtPoker);
	if (selectedLobby == 'poker' && objRes.registeredAtPoker) {
		makeOtherAccountVisible();
		setWalletVisibility(true);
		clickSubAccount('poker');
	}
}

function accountInfoActivateAccount(subAccount, connectError, userRegistered){
	if(connectError || userRegistered){
		if(connectError){
			changeAccountVisibility(subAccount, false, false, false, true);
			getElm("subAccount" + subAccount).onclick= null;
		}
		makeOtherAccountVisible();
		toggleAccountDisplay(subAccount, true);
	}
}

function doMoneyTransfer(subaccountName, action){
	var requestParams= "action=" + action;

	var amount = null;
	if(action != "withdrawall"){
		var amountField= getElm(action + subaccountName);
		amount= amountField.value;
		requestParams+= "&amount=" + amount;
	} else {
		amount = getElm("transferTotal" + subaccountName).value;
		amount = amount.replace(",", ".");
	}

	if(amount != null && !validateCurrency(amount)){
		alert(ERROR_CURRENCY);
		return;
	}
	var showConfirmationBox = false;
	showConfirmationBox = (getElm("confirmTransfer" + subaccountName).value == 'true');

	if (showConfirmationBox) {
		showTransferConfirmation(subaccountName, action);
	}
	else {
		confirmTransferNoconversion(subaccountName, requestParams);
	}
}

function accountInfo_doUnibetcasinoMoneyTransfer(action){
  var requestParams= null;
  var amount = null;
  var currency = null;
  if(action != "withdrawall"){
    requestParams="action=" + action;
    amount = getElm(action + "unibetcasino").value;
    currency = getElm("currency" + action + "_unibetcasino").value;
  } else {
    requestParams="action=withdraw";
    amount = getElm("transferTotalunibetcasino").value;
    currency = getElm("currencywithdraw_unibetcasino").value;
  }
  requestParams+= "&amount=" + amount + "&currency=" + currency;
  
  if(amount != null && !validateCurrency(amount)){
    alert(ERROR_CURRENCY);
    return;
  }

  getElm("depositunibetcasino").value= "";
  getElm("withdrawunibetcasino").value= "";

  showProcessing("unibetcasino");
  TransferAjaxObject.startRequest("/myunibet/unibetcasinotransfer.do", requestParams);
}

var TransferAjaxObject = { 
 
    handleSuccess:function(o){ 
        this.processResult(o); 
    }, 
 
    handleFailure:function(o){ 
    }, 
 
    processResult:function(o){
        handleTransferResponse(o); 
    }, 
 
    startRequest:function(address, requestParams) { 
       YAHOO.util.Connect.asyncRequest('POST', address, callback, requestParams); 
    } 
 
}; 
 
var callback = 
{ 
    success:TransferAjaxObject.handleSuccess, 
    failure:TransferAjaxObject.handleFailure, 
    scope: TransferAjaxObject 
}; 

function showTransferConfirmation(subaccountName, action) {
	getElm("transferType" + subaccountName).value = action;
	getElm(subaccountName + "_form").className = 'uHide';
	getElm(subaccountName + "_confirmation").className = 'uBlock';

	var amount = 0;
	/* 	This could be used for also bingo and casino in
		the future with minor changes to accountsummarybox.jsp*/
	if(subaccountName == 'poker') {
		/* 	deposit conversion is punterCurrency -> pokerCurrency
			and withdraw is pokerCurrency -> punterCurrency */
		setElm(subaccountName + "ConvertedFrom", "0");
		setElm(subaccountName + "ConvertedTo", "0");

		if (action == 'deposit') {
			amount = getElm("deposit" + subaccountName).value;
			setElm(subaccountName+"ConvertedToCurrency", getElm("punterCurrency").value);
			setElm(subaccountName+"ConvertedFromCurrency", getElm("pokerCurrency").value);
		} else if (action == 'withdraw') {
			amount = getElm("withdraw" + subaccountName).value;
			setElm(subaccountName+"ConvertedToCurrency", getElm("pokerCurrency").value);
			setElm(subaccountName+"ConvertedFromCurrency", getElm("punterCurrency").value);
		}
		else if (action == 'withdrawall') {
			amount = getElm("transferTotal" + subaccountName).value;
			amount = amount.replace(",", ".");
			setElm(subaccountName+"ConvertedToCurrency", getElm("pokerCurrency").value);
			setElm(subaccountName+"ConvertedFromCurrency", getElm("punterCurrency").value);
		}

		var actionName = action;
		//use same elements as withdraw
		if(action == 'withdrawall')actionName = 'withdraw';

		setElm(subaccountName+"ConversionRate", getElm(subaccountName+"_"+actionName+"ConversionString").value);
		var conversionRate = getElm(subaccountName+"_"+actionName+"ConversionRateHidden").value;
		var converted = Math.round((amount * conversionRate) * 100) / 100;

		setElm(subaccountName + "ConvertedFrom", amount);
		setElm(subaccountName + "ConvertedTo", converted);

		var toCurr = getElm("pokerConvertedToCurrency").innerHTML;
		var fromCurr = getElm("pokerConvertedFromCurrency").innerHTML;
		var myAjax = new Ajax.Updater(subaccountName + "ConvertedFrom","/myunibet/currency.do?amount=" + amount + "&curr=" + toCurr, {method: 'get', evalScripts: true});
		var myAjax2 = new Ajax.Updater(subaccountName + "ConvertedTo","/myunibet/currency.do?amount=" + converted + "&curr=" + fromCurr, {method: 'get', evalScripts: true});
	} else {
		/* casino and bingo */
		setElm("convertedFrom" + subaccountName, "0");
		setElm("convertedTo" + subaccountName, "0");

		if (action == 'deposit') {
			amount = getElm("deposit" + subaccountName).value;
		} else if (action == 'withdraw') {
			amount = getElm("withdraw" + subaccountName).value;
		}
		else if (action == 'withdrawall') {
			amount = getElm("transferTotal" + subaccountName).value;
			amount = amount.replace(",", ".");
		}

		var conversionRate = getElm("converted_" + subaccountName + "ConversionRateHidden").value;
		var converted = Math.round((amount / conversionRate) * 100) / 100;

		setElm("convertedFrom" + subaccountName, amount);
		setElm("convertedTo" + subaccountName, converted);

		var curr = getElm("converted_" + subaccountName + "TargetCurrency").innerHTML;
		var myAjax = new Ajax.Updater("convertedFrom" + subaccountName,"/myunibet/currency.do?amount=" + amount + "&curr=" + curr, {method: 'get', evalScripts: true});
		var myAjax2 = new Ajax.Updater("convertedTo" + subaccountName,"/myunibet/currency.do?amount=" + converted, {method: 'get', evalScripts: true});
	}

}

function confirmTransferNoconversion(subaccountName, requestParams) {
	getElm("deposit" + subaccountName).value= "";
	getElm("withdraw" + subaccountName).value= "";

	showProcessing(subaccountName);
	getHttpConnection().connect("/myunibet/" + subaccountName + "transfer.do?" + requestParams, "POST", "", handleTransferResponse);
}

function confirmTransfer(subaccountName) {
	var action = getElm("transferType" + subaccountName).value;
	var requestParams= "action=" + action;

	if(action != "withdrawall"){
		var amountField = getElm(action + subaccountName);
		var amount= amountField.value;
		requestParams+= "&amount=" + amount;

		if(!validateCurrency(amount)){
			alert(ERROR_CURRENCY);
			return;
		}
	}

	getElm("deposit" + subaccountName).value= "";
	getElm("withdraw" + subaccountName).value= "";

	getElm(subaccountName + "_form").className = 'uBlock';
	getElm(subaccountName + "_confirmation").className = 'uHide';

	showProcessing(subaccountName);
	getHttpConnection().connect("/myunibet/" + subaccountName + "transfer.do?" + requestParams, "POST", "" , handleTransferResponse);
}

function cancelTransfer(subaccountName) {
	getElm("deposit" + subaccountName).value= "";
	getElm("withdraw" + subaccountName).value= "";
	getElm(subaccountName + "_form").className = 'uBlock';
	getElm(subaccountName + "_confirmation").className = 'uHide';
}

function handleTransferResponse(response) {
	var ar = eval(response.responseText);
	if (ar.approved) {
		showForm(ar.subAccount);
		setElm("accountCashWithBonus", ar.accountCashWithBonus);
		setElm(ar.subAccount + "Balance", ar.subAccountCashWithBonus);
		setElm("maxTo" + ar.subAccount, ar.maxTransferToSubAccount);
		if (getElm("maxFrom" + ar.subAccount)) {
			setElm("maxFrom" + ar.subAccount, ar.maxTransferFromSubAccount);
		}
		getElm("transferTotal" + ar.subAccount).value =  ar.subAccountCashRaw;
		var withdrawal = ar.subAccountCash;

		if (ar.subAccount == 'casino') {
			if (getElm("openedbingo").value == '1') {
				refreshAccount("bingo", false);
			}
			if (getElm("openedpoker").value == '1') {
				refreshAccount("poker", false);
			}
      if (getElm("openedunibetcasino").value == '1') {
        refreshAccount("unibetcasino", false);
      }
		}
		else if (ar.subAccount == 'poker') {
			refreshAccountInfo();
			if (getElm("openedbingo").value == '1') {
				refreshAccount("bingo", false);
			}
			if (getElm("openedcasino").value == '1') {
				refreshAccount("casino", false);
			}
      if (getElm("openedunibetcasino").value == '1') {
        refreshAccount("unibetcasino", false);
      }
		}
		else if (ar.subAccount == 'bingo') {
			if (getElm("openedcasino").value == '1') {
				refreshAccount("casino", false);
			}
			if (getElm("openedpoker").value == '1') {
				refreshAccount("poker", false);
			}
      if (getElm("openedunibetcasino").value == '1') {
        refreshAccount("unibetcasino", false);
      }
		}
    if (ar.subAccount == 'unibetcasino') {
      if (getElm("openedcasino").value == '1') {
        refreshAccount("casino", false);
      }
      if (getElm("openedbingo").value == '1') {
        refreshAccount("bingo", false);
      }
      if (getElm("openedpoker").value == '1') {
        refreshAccount("poker", false);
      }
    }

		if (withdrawal) {
			var elm = getElm(ar.subAccount + "AvailableForWithdrawal");
			if(elm){
				elm.innerHTML= withdrawal;
			}
			else {
				var bakElm = getElm(ar.subAccount + "Cash");
				if(bakElm){
					bakElm.innerHTML = withdrawal;
				}
			}
		}
	}else{
		showError(ar.subAccount, ar.errorMessage);
	}
}

function showError(subAccount, message){
	var namePrefix= "subAccount" + subAccount;
	setElm(namePrefix + "_errormessage", message);

	changeAccountVisibility(subAccount, false, false, true, false);
}

function showForm(subAccount){
	changeAccountVisibility(subAccount, true, false, false, false);
	toggleAccountDisplay(subAccount, true);
}

function showProcessing(subAccount){
	changeAccountVisibility(subAccount, false, true, false, false);
}
function changeAccountVisibility(subAccount, wrapperDisplay, processDisplay, errorDisplay, connectErrorDisplay){
	var namePrefix= "subAccount" + subAccount;
	showElm(namePrefix + "_Wrapper", wrapperDisplay);
	showElm(namePrefix + "_Processing", processDisplay);
	showElm(namePrefix + "_Error", errorDisplay);
	showElm(namePrefix + "_ConnectError", connectErrorDisplay);
}

function makeOtherAccountVisible() {
	var sw = document.getElementById("subWallets");
	sw.style.display = "block";
	sw.style.visibility = "visible";

}

function validateCurrency(value){
	if (isNaN(value)) return false;
	if (value < 1) return false;
	return true;
}

function toggleAccountDisplay(subAccount, show){
	var display= "none";
	if(show){
		display= "block";
	}
	getElm("subAccount" + subAccount + "_container").style.display= display;
}

function hoverRow(rowElm){
	if(rowElm.className == "rowSelected pointer") return;
	rowElm.className = "rowHighlighted pointer";
}

function unHoverRow(rowElm){
	if(rowElm.className == "rowSelected pointer") return;
	rowElm.className = "row pointer";
}


function toggleSubAccountSilent(response) {
	var objRes = eval(response.responseText);

	if (objRes.accountName == 'bingo') {
		setElm("bingoBalance", objRes.bingoCashWithBonus);
		setElm("bingoBonus", objRes.bingoBonus);
		var bingoCurrency= objRes.bingoCurrency;
		if (bingoCurrency != ""){
			bingoCurrency= "(" + bingoCurrency + ")";
		}
		setElm("bingoCurrency2", bingoCurrency);
		setElm("bingoCurrency3", bingoCurrency);
		setElm("maxFrombingo", objRes.bingoCash);
		getElm("bingoTransferAllCash").value = objRes.bingoCashRawUF;

		setElm("converted_bingoConversionRate", objRes.bingoConversionRate);
		setElm("converted_bingoTargetCurrency", objRes.bingoCurrency);
		setElm("converted_bingoSourceCurrency", objRes.accountCurrency);
		getElm("converted_bingoConversionRateHidden").value = objRes.bingoConversionRateHidden;
		getElm("confirmTransferbingo").value = objRes.bingoNeedsConversion;
		getElm("transferTotalbingo").value = objRes.bingoCashRaw;
		getElm("openedbingo").value = '1';
		setElm("maxTobingo", objRes.bingoMaxTransfer);

		if (objRes.bingoConnectError) {
			getElm("subAccountbingo").onclick= null;
			getElm("bingoBalance").style.display = 'none';
			changeAccountVisibility('bingo', false, false, false, true);
		}
	} else if (objRes.accountName == 'casino') {
		setElm("casinoBalance", objRes.casinoTotalBalance);
		setElm("casinoBonus", "(" + objRes.casinoBonus + ")");
		$("casinoBonusRawUF").value = objRes.casinoBonusRawUF;
		var casinoCurrency= objRes.casinoCurrency;
		if(casinoCurrency != ""){
			casinoCurrency= "(" + casinoCurrency + ")";
		}
		setElm("casinoCurrency2", casinoCurrency);
		setElm("casinoCurrency3", casinoCurrency);

		var msg = $("subAccountcasino_container").casinoWageringReqInfo;
	    setElm("casinoBonusReqInfo",
	    		msgFormat.format(msg,
	    						'<b>' + objRes.casinoBonus + '</b>',
	    						'<b>' + objRes.casinoRequirements + '</b>',
	    						'<b>' + objRes.casinoWageringAmount + '</b>',
	    						'<b>' + objRes.casinoRemainingWageringRequirements + '</b>',
	    						'<b>' + objRes.casinoBonus + '</b>'));

		setElm("converted_casinoConversionRate", objRes.casinoConversionRate);
		setElm("converted_casinoTargetCurrency", objRes.casinoCurrency);
		setElm("converted_casinoSourceCurrency", objRes.accountCurrency);
		getElm("converted_casinoConversionRateHidden").value = objRes.casinoConversionRateHidden;
		getElm("confirmTransfercasino").value = objRes.casinoNeedsConversion;
		getElm("transferTotalcasino").value = (objRes.casinoTotalBalanceRawUF - objRes.casinoBonusRawUF);
		getElm("openedcasino").value = '1';
		setElm("maxTocasino", objRes.casinoMaxTransfer);
		setElm("maxFromcasino", objRes.casinoMaxWithdraw);
	} else if (objRes.accountName == 'poker') {
		setElm("pokerBalance", objRes.pokerCash);

		var pokerCurrency = objRes.pokerCurrency;
		if (pokerCurrency != "") {
			pokerCurrency= "(" + pokerCurrency + ")";
		}

		var accountCurrency = objRes.accountCurrency;
		if (accountCurrency != "") {
			accountCurrency= "(" + accountCurrency + ")";
		}

		setElm("pokerDepositCurrency", accountCurrency);
		setElm("pokerWithdrawCurrency", pokerCurrency);
		setElm("pokerVipPoints", objRes.pokerVipPoints);

		getElm("pokerCurrency").value = objRes.pokerCurrency;
		getElm("punterCurrency").value = objRes.accountCurrency;
		getElm("poker_depositConversionString").value = objRes.pokerDepositConversionString;
		getElm("poker_withdrawConversionString").value = objRes.pokerWithdrawConversionString;
		getElm("poker_depositConversionRateHidden").value = objRes.pokerDepositConversionRateHidden;
		getElm("poker_withdrawConversionRateHidden").value = objRes.pokerWithdrawConversionRateHidden;
		getElm("confirmTransferpoker").value = objRes.pokerNeedsConversion;
		getElm("transferTotalpoker").value = objRes.pokerCashRaw;
		getElm("openedpoker").value = '1';
		setElm("maxTopoker", objRes.pokerMaxTransfer);
	}
}

function toggleSubAccount(response) {
	var objRes = eval(response.responseText);

	if (objRes.accountName == 'bingo') {
		setElm("bingoBalance", objRes.bingoCashWithBonus);
		setElm("bingoBonus", objRes.bingoBonus);
		var bingoCurrency= objRes.bingoCurrency;
		if (bingoCurrency != ""){
			bingoCurrency= "(" + bingoCurrency + ")";
		}
		setElm("bingoCurrency2", bingoCurrency);
		setElm("bingoCurrency3", bingoCurrency);
		setElm("maxFrombingo", objRes.bingoCash);
		getElm("bingoTransferAllCash").value = objRes.bingoCashRawUF;

		setElm("converted_bingoConversionRate", objRes.bingoConversionRate);
		setElm("converted_bingoTargetCurrency", objRes.bingoCurrency);
		setElm("converted_bingoSourceCurrency", objRes.accountCurrency);
		getElm("converted_bingoConversionRateHidden").value = objRes.bingoConversionRateHidden;
		getElm("confirmTransferbingo").value = objRes.bingoNeedsConversion;
		getElm("transferTotalbingo").value = objRes.bingoCashRaw;
		setElm("maxTobingo", objRes.bingoMaxTransfer);

		if (objRes.bingoConnectError) {
            getElm("openedbingo").value = '0';
			getElm("bingoBalance").style.display = 'none';
			changeAccountVisibility('bingo', false, false, false, true);
		} else {
            getElm("openedbingo").value = '1';
			showForm(objRes.accountName);
		}

	} else if (objRes.accountName == 'casino') {
		setElm("casinoBalance", objRes.casinoTotalBalance);
		setElm("casinoBonus", "(" + objRes.casinoBonus + ")");
		$("casinoBonusRawUF").value = objRes.casinoBonusRawUF;
		var casinoCurrency= objRes.casinoCurrency;
		if(casinoCurrency != ""){
			casinoCurrency= "(" + casinoCurrency + ")";
		}
		setElm("casinoCurrency2", casinoCurrency);
		setElm("casinoCurrency3", casinoCurrency);

		var msg = $("subAccountcasino_container").casinoWageringReqInfo;
	    setElm("casinoBonusReqInfo",
	    		msgFormat.format(msg,
	    						'<b>' + objRes.casinoBonus + '</b>',
	    						'<b>' + objRes.casinoRequirements + '</b>',
	    						'<b>' + objRes.casinoWageringAmount + '</b>',
	    						'<b>' + objRes.casinoRemainingWageringRequirements + '</b>',
	    						'<b>' + objRes.casinoBonus + '</b>'));

		setElm("converted_casinoConversionRate", objRes.casinoConversionRate);
		setElm("converted_casinoTargetCurrency", objRes.casinoCurrency);
		setElm("converted_casinoSourceCurrency", objRes.accountCurrency);
		getElm("converted_casinoConversionRateHidden").value = objRes.casinoConversionRateHidden;
		getElm("confirmTransfercasino").value = objRes.casinoNeedsConversion;
		getElm("transferTotalcasino").value = (objRes.casinoTotalBalanceRawUF - objRes.casinoBonusRawUF);
		setElm("maxTocasino", objRes.casinoMaxTransfer);
		setElm("maxFromcasino", objRes.casinoMaxWithdraw);

		if (objRes.casinoConnectError) {
            getElm("openedcasino").value = '0';
			getElm("casinoBalance").style.display = 'none';
			changeAccountVisibility('casino', false, false, false, true);
		} else {
            getElm("openedcasino").value = '1';
			showForm(objRes.accountName);
		}

  } else if (objRes.accountName == 'unibetcasino') {
    setElm("unibetcasinoBalance", objRes.unibetcasinoCashWithBonus);
    setElm("unibetcasinoBonus", "(" + objRes.unibetcasinoBonus + ")");
    var unibetcasinoCurrency= objRes.unibetcasinoCurrency;
    
    if(unibetcasinoCurrency != ""){
      unibetcasinoCurrency= "(" + unibetcasinoCurrency + ")";
    }

    var accountCurrency= objRes.accountCurrency;
    
    if(accountCurrency != ""){
      accountCurrency= "(" + accountCurrency + ")";
    }

    setElm("unibetcasinoCurrency2", accountCurrency);
    setElm("unibetcasinoCurrency3", unibetcasinoCurrency);

    setElm("converted_unibetcasinoConversionRate", objRes.unibetcasinoConversionRate);
    setElm("converted_unibetcasinoTargetCurrency", objRes.unibetcasinoCurrency);
    setElm("converted_unibetcasinoSourceCurrency", objRes.accountCurrency);
    getElm("converted_unibetcasinoConversionRateHidden").value = objRes.unibetcasinoConversionRateHidden;
    getElm("currencydeposit_unibetcasino").value = objRes.accountCurrency;
    getElm("currencywithdraw_unibetcasino").value = objRes.unibetcasinoCurrency;
    getElm("confirmTransferunibetcasino").value = objRes.unibetcasinoNeedsConversion;
    getElm("transferTotalunibetcasino").value = (objRes.unibetcasinoTotalBalanceRawUF - objRes.unibetcasinoBonusRawUF);
    setElm("maxTounibetcasino", objRes.unibetcasinoMaxTransfer);
    setElm("maxFromunibetcasino", objRes.unibetcasinoMaxWithdraw);

    if (objRes.unibetcasinoConnectError) {
            getElm("openedunibetcasino").value = '0';
      getElm("unibetcasinoBalance").style.display = 'none';
      changeAccountVisibility('unibetcasino', false, false, false, true);
    } else {
            getElm("openedunibetcasino").value = '1';
      showForm(objRes.accountName);
    }

	} else if (objRes.accountName == 'poker') {
		setElm("pokerBalance", objRes.pokerCash);

		var pokerCurrency = objRes.pokerCurrency;
		if (pokerCurrency != "") {
			pokerCurrency= "(" + pokerCurrency + ")";
		}

		var accountCurrency = objRes.accountCurrency;
		if (accountCurrency != "") {
			accountCurrency= "(" + accountCurrency + ")";
		}

		setElm("pokerDepositCurrency", accountCurrency);
		setElm("pokerWithdrawCurrency", pokerCurrency);
		setElm("pokerVipPoints", objRes.pokerVipPoints);

		getElm("pokerCurrency").value = objRes.pokerCurrency;
		getElm("punterCurrency").value = objRes.accountCurrency;
		getElm("poker_depositConversionString").value = objRes.pokerDepositConversionString;
		getElm("poker_withdrawConversionString").value = objRes.pokerWithdrawConversionString;
		getElm("poker_depositConversionRateHidden").value = objRes.pokerDepositConversionRateHidden;
		getElm("poker_withdrawConversionRateHidden").value = objRes.pokerWithdrawConversionRateHidden;
		getElm("confirmTransferpoker").value = objRes.pokerNeedsConversion;
		getElm("transferTotalpoker").value = objRes.pokerCashRaw;
		setElm("maxTopoker", objRes.pokerMaxTransfer);

		if (objRes.pokerConnectError) {
            getElm("openedpoker").value = '0';
			getElm("pokerBalance").style.display = 'none';
			changeAccountVisibility('poker', false, false, false, true);
		} else {
            getElm("openedpoker").value = '1';
			showForm(objRes.accountName);
		}
	}
}

var casinoOpened = false;

function refreshAccount(subAccount, forceOpen) {
	var accId = -1;
	if (subAccount == 'casino') {
		casinoOpened = true;
		accId = 5;
	} else if (subAccount == 'poker') {
		accId = 6;
	} else if (subAccount == 'bingo') {
		accId = 7;
	} else if (subAccount == 'unibetcasino') {
    accId = 8;
  }

	if (forceOpen) {
		getHttpConnection().connect("/myunibet/refresh.do?r=" + accId, "POST", "", toggleSubAccount);
	}
	else {
		getHttpConnection().connect("/myunibet/refresh.do?r=" + accId, "POST", "", toggleSubAccountSilent);
	}
}

function clickSubAccount(subAccount){
	var idPrefix= "subAccount" + subAccount;

	var hDiv = getElm(idPrefix + "_Header");
	var isOpen = (hDiv.className == "rowArrowDown");

	if (isOpen == true) {
		closeSubAccount(subAccount);
	} else {
		openSubAccount(subAccount);
	}
}

function openSubAccount (subAccount) {
	var idPrefix= "subAccount" + subAccount;

	var rowElm = getElm(idPrefix);
	var hDiv = getElm(idPrefix + "_Header");

	hDiv.className = "rowArrowDown";
	rowElm.className = "rowSelected pointer";
	changeAccountVisibility(subAccount, true, false, false, false);

	if (getElm("opened" + subAccount).value == '1') {
		getElm(subAccount + "Balance").style.display = '';
		showForm(subAccount);
	}
	else {
		showProcessing(subAccount);
		refreshAccount(subAccount, true);
	}
}

function closeSubAccount (subAccount) {
	var idPrefix= "subAccount" + subAccount;

	var rowElm = getElm(idPrefix);
	var hDiv = getElm(idPrefix + "_Header");

	hDiv.className = "rowArrowDown";
	rowElm.className = "rowSelected pointer";

	hDiv.className = "rowArrow";
	rowElm.className = "row pointer";
	getElm(subAccount + "Balance").style.display = 'none';
	changeAccountVisibility(subAccount, false, false, false, false);
}

function clickBonus(){
	var idPrefix= "bonus";

	var rowElm = getElm(idPrefix);
	var hDiv = getElm(idPrefix + "_Header");
	var isOpen = (hDiv.className == "rowArrowDown");

	if(isOpen == true){
		hDiv.className = "rowArrow";
		rowElm.className = "row pointer";
		getElm("bonusList").style.display = 'none';
		showElm("bonus_Wrapper", false);
	}else{
		hDiv.className = "rowArrowDown";
		rowElm.className = "rowSelected pointer";
		getElm("bonusList").style.display = '';
		showElm("bonus_Wrapper", true);
	}
}

function toggleWallets(){
	var wc = document.getElementById("wallet_container");
	var wr = document.getElementById("wallets_Header");

	if(wc.style.display == "inline"){
		wc.style.display = "none";
		wr.className = "rowArrow";
	}else{
		wc.style.display = "inline";
		wr.className = "rowArrowDown";
	}
}

function setWalletVisibility(show){
	var wc = document.getElementById("wallet_container");
	var wr = document.getElementById("wallets_Header");

	if(show){
		wc.style.display = "inline";
		wr.className = "rowArrowDown";
	}else{
		wc.style.display = "none";
		wr.className = "rowArrow";
	}
}

function cancelLogout() {
	getElm('logout_warning').className = getElm('logout_warning').className + ' uHide';
	getElm("accountSummary_normal").style.display = '';
}

function showLogoutWarning() {
	getElm('logout_warning').className = getElm('logout_warning').className.replace('uHide', '');
	getElm("accountSummary_normal").style.display = 'none';
}

function checkForUnconfirmedBetsInCoupon(response) {
	if (response.responseText == '<html>true</html>') {
		showLogoutWarning();
	}
	else {
		getHttpConnection().connect("/racingb3/isempty.slip", "GET", "", checkForEmptyCouponFHR)
	}
}

function checkForEmptyCouponFHR(response) {
	if (response.responseText != '<html>true</html>') {
		showLogoutWarning();
	}
	else {
		getElm("logoutForm").submit();
	}
}

function logout() {
	getHttpConnection().connect("/betting/unconfirmedBetsCheck.do", "GET", "", checkForUnconfirmedBetsInCoupon);
}
// Info Centre Popup Script
var win = null;
var winWidth = 800;
var winHeight = 630;
var posTop = 50;
var posLeft = 50;

function icOpenChild(url) {
	win = window.open(url, 'icPopup', 'width=' + winWidth + ',height=' + winHeight + ',top=' + posTop + ',left=' + posLeft + ',status=0,toolbar=0,menubar=0,location=0,scrollbars=0');
	win.focus();
}

function icOpenParent(url) {
	try {
		opener.window.location.href = url;
		opener.window.focus();
	} catch(e) {
		try {
			win.location.href = url;
			win.focus();
		} catch(e) {
			win = window.open(url, 'Unibet', 'status=1,toolbar=1,menubar=1,location=1,scrollbars=1,resizable=1');
			try {
				win.moveTo(0,0);
			} catch(e) {}
			win.resizeTo(screen.width, screen.height);
			win.focus();
		}
	}
}

function icPopupLinks() {
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++) {
		if (links[i].className.indexOf('icLink') > -1) {
			try {
				if (icPopup) {
					eval("addEvent(links[i], 'click', function () { icOpenParent('" + links[i].getAttribute('href') + "'); });");
				}
			} catch(e) {
				eval("addEvent(links[i], 'click', function () { icOpenChild('" + links[i].getAttribute('href') + "'); });");
			}
			links[i].setAttribute('target', '_self');
			links[i].setAttribute('href', 'javascript:void(0)');
		}
	}
}

addEvent(window, 'load', icPopupLinks);
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}
function postCallMeNumber(oObj)
{
	var oObj = document.getElementById("phoneNumber");
	var myConn = new XHConn();
	if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
	myConn.connect(callback_URL, "POST", "phone=" + encodeURIComponent(oObj.value), data_postCallMeAnswer);
}
function data_postCallMeAnswer(oResult)
{
    var error = oResult.responseXML.getElementsByTagName("error");
    var closed = oResult.responseXML.getElementsByTagName("closed");
	var text = oResult.responseXML.getElementsByTagName("text")[0].childNodes[0].nodeValue;
	var replaceNode = "retrieve-area";
	if (error.length > 0) {
		text = '<div class="callme_error"><p><em>' + text + '</em></p></div>';
		replaceNode = "retrieve-area-text";
	}
	else if (closed.length > 0) {
		text = '<div class="callme_error"><p><em>' + text + '</em></p></div>';
	}
	else {
		text = '<div><p>' + text + '</p></div>';
	}
	document.getElementById(replaceNode).innerHTML = text;
}


function viewSubLobby(id) {
  	var url = '/betting/ajax/lobby.do';
  	var target = $('main-mid');
  	var pars = "lobbyId=" + id;
  	startProgress();
  	var myAjax = new Ajax.Updater(target, url, {method: 'get',  parameters: pars, onComplete: stopProgress, evalScripts: true});
}

function startProgress() {
	document.getElementsByTagName('body').item(0).style.cursor='progress';
}

function stopProgress() {
	document.getElementsByTagName('body').item(0).style.cursor='default';
}

function showLiveBets() {
    var popupUrl = '/livebetting/flash.do';
    var popup = window.open(popupUrl, '_blank', "toolbar=no,alwaysRaised=yes,dependent=yes,menubar=no,resizable=yes,scrollbars=yes,height=600,width=1009");
	popup.focus();
}

function goToMobile() {
	var url = '/mobile-b3/activate.do';
	startProgress();
	var myAjax = new Ajax.Updater('main-mid', url, {method: 'get', parameters: null, onComplete: stopProgress, evalScripts: true});
}

function fetchResults() {
	var pars = Form.serialize($('resultsForm'));
	var f = $('resultsForm');
	if (f) {
		var n = 0;
		for (var i = 0; i < f.elements.length; i++) {
			if (f.elements[i].type == 'checkbox' && f.elements[i].checked) {
				pars += '&path[' + n + ']=' + f.elements[i].value;
				n++;
			}
		}
	}
	startSearchProgress();
	var myAjax = new Ajax.Updater('main-mid', 'ajax/results.do', {method: 'post', onComplete: stopSearchProgress, parameters: pars});
}


var MAIN_MID_MIN_SIZE = 600;

function grid_showBetOffers(pars) {
	startSearchProgress();
	var ifrmBetOffer = getBetofferIframe();
	//var url = '/betoffer/betOfferGrid.do' + "?" + pars;
	var url = '/betoffer/betOfferGrid.do' + "?" + pars;
	ifrmBetOffer.src = url;
}


function resizeMainMid(){

	if($("promoflashcontent")){ return; }

	var pageSubmenu = $("pageSubmenu");
	var ibo = $("ifrmBetOffer");
	if (!ibo) ibo = $("main-mid");
	if(!ibo){
		 return;
	}

	var xTop = $('mainDiv').offsetTop;
	var minHeight = 400;
	var offset = 150;
	var windowHeight = 0;

	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
	windowHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	//IE 6+ in 'standards compliant mode'
	windowHeight= document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	//IE 4 compatible
	windowHeight= document.body.clientHeight;
	}
	var bgpHeight = parseInt(windowHeight - offset);
	if(bgpHeight > minHeight){
		ibo.style.height = (bgpHeight + xTop) + "px";
	}else{
		ibo.style.height = (minHeight + xTop) + "px";
	}
	ibo.style.overflowX = "hidden";
	ibo.style.overflowY = "auto";
	var mm=$("main-mid");
	if (ibo != mm && mm.style.height != 'auto') { mm.style.height = 'auto'; }
	if (ibo != mm && typeof ibo.observingLoad == "undefined") {
		ibo.observingLoad = true;
		Event.observe(ibo, 'load', scrollIf, false);
	}
}


/***
* Scroll down top of main Div
***/
function fScrollTomainRightDiv(){
	var xTop = $('mainDiv').offsetTop;
	window.scrollTo(0,xTop);
}

//////////////////// START betoffer stuff /////////////////////
var BET_OFFER_CONTEXT = "/betoffer";
var GRID_FOR_EVENTS = "/gridForEvents.do";
var GRID_FOR_SEARCH = "/gridForSearch.do";
var GRID_FOR_PATHS = "/gridForPaths.do";
var GRID_FOR_FILTERS = "/gridForFilters.do";
var GRID_DECORATED_DOCUMENT = "&gridViewName=decoratedGrid"

function grid_showBetOfferGridForPaths(pars) {
	startSearchProgress();

	var contextRoot = getContextRoot();
	if ( !endsWith(contextRoot, 'betting') ) {
		// Not in sportsbook so we can't just access iFrame, link directly into sportsbook
		document.location = '/betting/?' + pars;
	} else {
		// Within the sportsbook we can make use of the iFrame and skip reload of entire page
		var ifrmBetOffer = getOrCreateBetOfferIFrame();
		var url = BET_OFFER_CONTEXT + GRID_FOR_PATHS + "?" + pars + GRID_DECORATED_DOCUMENT;
		ifrmBetOffer.src = url;
	}
}

function grid_showBetOfferGridForEvents(pars) {
	startSearchProgress();

	var contextRoot = getContextRoot();
	if ( !endsWith(contextRoot, 'betting') ) {
		// Not in sportsbook so we can't just access iFrame, link directly into sportsbook
		document.location = '/betting/?' + pars;
	} else {
		// Within the sportsbook we can make use of the iFrame and skip reload of entire page
		var ifrmBetOffer = getOrCreateBetOfferIFrame();
		var url = BET_OFFER_CONTEXT + GRID_FOR_EVENTS + "?" + pars + GRID_DECORATED_DOCUMENT;
		ifrmBetOffer.src = url;
	}
}

/**
 * Returns the current context root.
 * Example: if the current context is: http://host:port/root/level1/level2
 * http://host:port/root will be returned.
 */
function getContextRoot() {
	var base = document.getElementsByTagName('base')[0];
	if (base && base.href && (base.href.length > 0)) {
		base = base.href;
	} else {
		base = document.URL;
	}
	return base.substr(0, base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1));
}

/**
 * Returns true if string ends with suffix, false o/w.
 */
function endsWith(string, suffix) {
	return (string.substring(string.length - suffix.length) == suffix);
}

function grid_showBetOfferGridForFilters(timeframe, criteriaGroup) {
	var url = BET_OFFER_CONTEXT + '/gridForFilters.do';
	var pars = 'gridSelectedTimeframe=' + timeframe + '&gridSelectedCriteriaGroup=' + criteriaGroup + GRID_DECORATED_DOCUMENT;
	var target = 'main-mid';
	startSearchProgress();
	var ifrmBetOffer = getBetofferIframe();

	ifrmBetOffer.src = url + "?" + pars;

}
function grid_printGrid(theForm, viewName) {
  	var pars = Form.serialize(theForm);
	var url = BET_OFFER_CONTEXT + grid_actionPath(theForm);
	url += "?gridViewName=" + viewName + "&" + pars;
	window.open(url, '_blank', 'width=800, height=600, resizable=yes, scrollbars=yes, menubar=yes');
}
function grid_showBetOffersPostForm(theForm) {
  	var pars = Form.serialize(theForm);
	startSearchProgress();
	var url = BET_OFFER_CONTEXT + grid_actionPath(theForm);
	url += "?" + pars + GRID_DECORATED_DOCUMENT
	// IMPORTANT! the getting or creating of the iframe needs to be
	// done after inspecting the form, otherwise ie scrambles the DOM-
	// model and the action switch (grid_actionPath) breaks
	var ifrmBetOffer = getOrCreateBetOfferIFrame();
	ifrmBetOffer.src = url;
}


function grid_actionPath(theForm) {
	var url = "";
	// Figure out what type of search we want to do
	// If we have a event ids, search by them
	if (grid_hasValue(theForm, 'gridEventIds')) {
		url += GRID_FOR_EVENTS;
	}
	// else if we have a search string, do a search
	else if (grid_hasValue(theForm, 'gridSearchString')) {
		url += GRID_FOR_SEARCH;
	}
	// else if we have a paths, search by them
	else if (grid_hasValue(theForm, 'gridPaths')) {
		url += GRID_FOR_PATHS;
	}
	// Default is no path, search keys or event ids. Just apply filters.
	// Typically when coming from "All Bets"-link
	else {
		url += GRID_FOR_FILTERS;
	}

	return url;
}
function grid_hasValue(theForm, fieldName) {
	var field = theForm.elements[fieldName];
	return (field != null && (isArray(field) || (field.value != null && field.value != "")));
}
function isArray(obj) {
	if (obj == null) return false;
	return obj.length != undefined;
}
function getOrCreateBetOfferIFrame(){
	var ifrmBetOffer = document.getElementById("ifrmBetOffer");

	if(!ifrmBetOffer){
		var mainMid = document.getElementById("main-mid");
		// Create new IFrame
		mainMid.innerHTML = BO_IFRM_HTML;
		ifrmBetOffer = document.getElementById("ifrmBetOffer");
	}

	return ifrmBetOffer;
}

//////////////////// END betoffer stuff /////////////////////


var bettingContext = "/betting";

function foldSystem(systemIndex) {
	var combIndex = 0;
	var combStake = $('coupon.betSystems-' + systemIndex + '-combinations-' + combIndex + '-stake');
	var prevStake = combStake;
	var systemStakeValue = combStake.value;
	while(combStake) {
		if(combStake.value != prevStake.value) {
			systemStakeValue = null;
			break;
		}
		prevStake = combStake;
		combStake = $('coupon.betSystems-' + systemIndex + '-combinations-' + ++combIndex + '-stake');
	}
	toogleSystem(systemIndex, true, systemStakeValue);
}
function unfoldSystem(systemIndex) {
	toogleSystem(systemIndex, false);
}
function getTargetDiv() {
	var targetDivId = 'main-right';
	var targetDiv = $(targetDivId);
	return targetDiv;
}
function toogleSystem(systemIndex, toogle, systemStake) {
  	var url = bettingContext + '/ajax/coupon.do';
  	var stakeParam = '';
  	if(systemStake != null) {
  		stakeParam = '&coupon.betSystems[' + systemIndex + '].systemStake=' + systemStake;
  	}
  	var pars = Form.serialize($('couponForm')) + '&coupon.betSystems[' + systemIndex + '].folded=' + toogle + stakeParam;
  	var target = getTargetDiv();
  	startProgress();
  	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
}
function refreshCoupon() {
  	var url = bettingContext + '/ajax/coupon.do';
  	var pars = Form.serialize($('couponForm'));
  	var target = getTargetDiv();
  	startProgress();
  	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
}
function restartCoupon() {
  	var url = bettingContext + '/ajax/restartCoupon.do';
  	var pars = 'keepCombinations=' + $('keepCombinations').checked;
  	var target = getTargetDiv();
  	startProgress();
  	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onComplete: stopProgress, evalScripts: true});
}
//just send the data to server, don't update anything
function saveCoupon() {
	var url = bettingContext + '/ajax/coupon.do';
  	var pars = Form.serialize($('couponForm'));
  	startProgress();
  	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
}
function placeBetConfirm() {
	//check that the 'place bet' button wasn't clicked multiple times
	if(!$('isSubmitted')) {
		var isSubmitted = document.createElement('div');
		isSubmitted.id = 'isSubmitted';
		var betslip = $('bettingslip');
		betslip.appendChild(isSubmitted);

		var pars = Form.serialize($('couponForm'));
		// first check if punter is logged in, and if not, run controller and reload page
		if (!isLoggedIn) {
			var myAjax = new Ajax.Request(bettingContext + '/ajax/placeBetWithNoCredentials.do', {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
			$('punterNotLoggedInDiv').style.display = "block";
			// DASY-6345 - function js $() will take anly first element with that ID, so it was needed to change ID to punterNotLoggedInDiv2
			$('punterNotLoggedInDiv2').style.display = "block";
			return;
		}
		// if logged in, continue with posting form through Ajax.Updater
	  	var url = bettingContext + '/ajax/placeBetConfirm.do';
	  	var target = getTargetDiv();
	  	startProgress();
	  	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
	}
}
function placeBet() {
	//check that the 'confirm' button wasn't clicked multiple times
	if(!$('isSubmitted')) {
		var isSubmitted = document.createElement('div');
		isSubmitted.id = 'isSubmitted';
		var betslip = $('bettingslip');
		betslip.appendChild(isSubmitted);

		var url = bettingContext + '/ajax/placeBet.do';
		var pars = '';
		if ($('pba1')) {
			pars = 'pbaAction=1';
			if ($('pba2').checked) {
				pars = 'pbaAction=2';
			}
			if ($('pba3').checked) {
				pars = 'pbaAction=3';
			}
		} else if($('pba2')) {
			pars = 'pbaAction=2';
		} else if($('pba3')) {
			pars = 'pbaAction=3';
		}
		pars = pars + '&CSRFToken='+ $('CSRFToken').value;
		var target = getTargetDiv();
		startProgress();
		var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
	}
}
function viewCoupon() {
  	var url = bettingContext + '/ajax/coupon.do';
  	var target = getTargetDiv();
  	startProgress();
  	var myAjax = new Ajax.Updater(target, url, {method: 'get', onComplete: stopProgress, evalScripts: true});
}


function addOutcome(outcomeId, odds) {
	var target = 'main-right';//getTargetDiv();
	var url = bettingContext + '/ajax/addOutcome.do';
	var pars = 'pendingOutcomeIds=' + outcomeId + '&pendingOdds=' + odds;
	// check to see if the form is visible, and if it is
	// serialize it
	if ($('couponForm')) {
		pars = Form.serialize($('couponForm')) + '&' + pars;
	}
	startProgress();
	if ($(target)) {
		var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
	} else {
		// when not in betting lobby
		var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function() {window.location = bettingContext;}});
	}
}
function removeOutcome(outcomeId) {
	var url = bettingContext + '/ajax/removeOutcome.do';
	var pars = Form.serialize($('couponForm')) + '&pendingOutcomeIds=' + outcomeId;
  	var target = getTargetDiv();
  	startProgress();
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
}
function setBanker(outcomeId, value) {
	var url = bettingContext + '/ajax/setBanker.do';
	var pars = '&outcomeId='+outcomeId+'&value='+ value;
	var target = getTargetDiv();
	startProgress();
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
}
function setInclude(outcomeId, elementIdx, value) {
	var bankerCbx = document.getElementById('banker'+elementIdx);
	bankerCbx.disabled = true;
	bankerCbx.checked = false;
	var url = bettingContext + '/ajax/setInclude.do';
	var pars = '&outcomeId='+outcomeId+'&value='+ value;
	var target = getTargetDiv();
	startProgress();
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: stopProgress, evalScripts: true});
}

function resetCoupon() {
	var url = bettingContext + '/ajax/resetCoupon.do';
  	var target = getTargetDiv();
  	startProgress();
  	var myAjax = new Ajax.Updater(target, url, {method: 'post', onComplete: stopProgress, evalScripts: true});
}
function MySlip() {
	this.showBankers = false;
	this.toogleBankers = function(oAnchor, flag) {
		this.showBankers = flag;
		var obj = $("bettingslip")
		if (this.showBankers) {
			obj.className = "showbankers";
			$(oAnchor).className = "shown";
		} else {
			obj.className = "hidebankers";
			$(oAnchor).className = "hidden";
		}
		for(var i = 0; i < 12; i++) {
			var bankersDiv = document.getElementById('bankersDiv'+i);
			if(!bankersDiv) break;
			bankersDiv.style.display = flag ? "inline":"none";
		}
		$('coupon.showBankers').value = this.showBankers;
	};
}

var myBettingSlip = new MySlip();

function Coupon() {
	this.rows = new Object();
	this.clear = function() {
		this.rows = new Object();
	};
	this.changeStake = function(key) {
		var newStake = $(key).value;
		if(newStake=="") {
			newStake='0';
		}

		this.rows[key].stake = formatFloat(newStake);
		this.updateHtml();
	};
	this.calcTotalStake = function() {
		var totalStake = 0.0;
		for (var key in this.rows) {
			totalStake += this.rows[key].stake * this.rows[key].nrCombs;
		}
		return new Number(totalStake).toFixed(2);;
	};
	this.calcPossiblePayout = function() {
		var totalPayout = 0.0;
		for (var key in this.rows) {
			totalPayout += this.rows[key].payout();
		}
		return new Number(totalPayout).toFixed(2);
	};
	this.addRow = function(key, odds, stake, nrCombs) {
		this.rows[key] = new Row(parseFloat(odds), parseFloat(stake), parseFloat(nrCombs));
	};
	this.updateHtml = function() {
		var stakeTag = $('totalStake');
		var payoutTag = $('totalPotentialPayout');
		var newTotalStake = this.calcTotalStake();
		var newPossiblePayout = "--.--";
		stakeTag.replaceChild(document.createTextNode(newTotalStake), stakeTag.firstChild);
		payoutTag.replaceChild(document.createTextNode(newPossiblePayout), payoutTag.firstChild);
	};
	this.writeMe = function() {
		var s = "";
		for (var key in this.rows) {
			s = s + "key: " + key
				+ ", odds: " + this.rows[key].odds
				+ ", stake: " + this.rows[key].stake + ", payout: " + this.rows[key].payout() + "\n";
		}
		s = s + "------------------\n";
		s = s + "Total stake: " + this.calcTotalStake() + "\n";
		s = s + "Total possible payout: " + this.calcPossiblePayout();
		return s;
	};
	function Row(odds, stake, nrCombs) {
		this.odds = odds;
		this.stake = stake;
		this.nrCombs = nrCombs;
		this.payout = function() {
			return this.odds * this.stake;
		};
	}
}
var coupon = new Coupon();


// TRIXIE & YANKEE stuff
function isTabOrEnter(eventKeyCode) {
	return (eventKeyCode == 9) || (eventKeyCode == 13);
}
function changeTrixieStake() {
	changeTrixieYankeeStake("trixie.stake");
}
function changeYankeeStake() {
	changeTrixieYankeeStake("yankee.stake");
}
function checkTrixieFieldEnabling() {
	checkTrixieYankeeFieldEnabling("trixie.stake");
}
function checkYankeeFieldEnabling() {
	checkTrixieYankeeFieldEnabling("yankee.stake");
}
function changeTrixieYankeeStake(fieldName) {
	var stake = $(fieldName).value;
	var names = resolveTrixieYankeeInvolvedFieldNames();
	for (var i = 0; i < names.length; i++) {
		$(names[i]).value = stake;
		coupon.changeStake(names[i]);
	}
	checkTrixieYankeeFieldEnabling(fieldName);
}
function checkTrixieYankeeFieldEnabling(fieldName) {
	var names = resolveTrixieYankeeInvolvedFieldNames();
	var isDisabled = $(fieldName).value != '' && $(fieldName).value != 0;
	for (var i = 0; i < names.length; i++) {
		$(names[i]).disabled = isDisabled;
	}
}
function resolveTrixieYankeeInvolvedFieldNames() {
	var names = new Array();
	// doubles
	if ($('coupon.betSystems-1-systemStake')) {
		names.push('coupon.betSystems-1-systemStake');
	} else {
		// if it is a yankee, no more than 6 doubles can appear
		for (var i = 0; i < 6; i++) {
			var fieldName = 'coupon.betSystems-1-combinations-' + i + '-stake';
			if ($(fieldName)) {
				names.push(fieldName);
			}
		}
	}
	// triples
	if ($('coupon.betSystems-2-systemStake')) {
		names.push('coupon.betSystems-2-systemStake');
	} else {
		// if it is a yankee, no more than 4 triples can appear
		for (var i = 0; i < 4; i++) {
			var fieldName = 'coupon.betSystems-2-combinations-' + i + '-stake';
			if ($(fieldName)) {
				names.push(fieldName);
			}
		}
	}
	// fourfold (only yankee)
	if ($('coupon.betSystems-3-systemStake')) {
		names.push('coupon.betSystems-3-systemStake');
	} else {
		var fieldName = 'coupon.betSystems-3-combinations-0-stake';
		if ($(fieldName)) {
			names.push(fieldName);
		}
	}
	return names;
}

// shows or hides bet information on the "confirm bet" slip
function toggleDisplay(field)
{
	var parTr = $('parent' + field);
	var tr = parTr.nextSibling;

	while (tr != null)
	{
		if (tr.tagName && tr.tagName.toLowerCase() == 'tr' && (tr.className == ('combination' + field)))
		{
			if (tr.style.display == 'none')
			{
				tr.style.display = '';
				$('imgHidden' + field).style.display = 'none';
				$('imgShown' + field).style.display = '';
				$('parent' + field).className = 'active';
			}
			else
			{
				tr.style.display = 'none';
				$('imgHidden' + field).style.display = '';
				$('imgShown' + field).style.display = 'none';
				$('parent' + field).className = '';
			}
		}
		tr = tr.nextSibling;
	}
}

// print coupon functinality
var receiptWindow = null;
function printTheCoupon(receiptHeader) {
	receiptWindow = window.open("/static/betting/receipt.html", "receiptWindow",
		"width=280, height=400, status=no, menubar=no, location=no");
	receiptWindow.blur();
	addEvent(receiptWindow, "load", function() {printTheCouponAction(receiptHeader)});
}
function printTheCouponAction(receiptHeader) {
	var slip = $("slipReceipt");
	var remoteSlip = receiptWindow.document.getElementById("slipReceipt");
	remoteSlip.innerHTML = slip.innerHTML;
	receiptWindow.document.getElementById("receiptHeader").innerHTML = receiptHeader;
	var a = receiptWindow.document.getElementsByTagName("A");
	var img = receiptWindow.document.getElementsByTagName("IMG");
	var div = receiptWindow.document.getElementsByTagName("DIV");
	var tr = receiptWindow.document.getElementsByTagName("TR");

	for(var i=0; i<a.length; i++) {
		a[i].style.display = "none";
	}

	for(var i=0; i<img.length; i++) {
		img[i].style.display = "none";
	}

	for(var i=0; i<div.length; i++) {
		if(div[i].className.indexOf("placebet") > -1) {
			div[i].style.display = "none";
		}
	}

	for(var i=0; i<tr.length; i++) {
		if (tr[i].className.indexOf("combination") != -1) {
			tr[i].style.display = "";
		}
	}

	receiptWindow.print();
	receiptWindow.self.close();
	receiptWindow = null;
}

/*
* Converts the input to be acceptable to parseFloat()
* and returns the result
*/
function formatFloat(str) {
	var decSymbol = $('decimalSeparator').value;

	str = str.replace(' ', '');

	if (/^((\d*\.{0,1}\d*))$/.test(str)){
		return Math.round(parseFloat(str)*100)/100;
	} else {
		return 0;
	}

}

/*
*
* Expand and collapse the combinations in the coupon_confirm view
*/
var expandedSystems = new Array();

function expandSystemType(type,placeHolder,target){
        var updater = new Ajax.Updater(placeHolder, '/betting/ajax/expand.do?action=expand&type='+type+'&target='+target, { method: 'get', evalScripts: true });
    }

    function toggleExpanded(type,placeHolder,target){
            if(expandedSystems[type] == 1){
                $(placeHolder).style.display = 'none';
                expandedSystems[type] = 0;
                displayParent(type);

            } else if(expandedSystems[type] == 0)  {
                $(placeHolder).style.display = '';
                expandedSystems[type] = 1;
                displayParent(type);
            } else {
                expandSystemType(type,placeHolder,target);
                expandedSystems[type] = 1;
                $(placeHolder).style.display = '';
                displayParent(type);
            }
    }

    function displayParent(field){
    	if($('parent' + field).className == 'active'){
    		$('imgHidden' + field).style.display = '';
		$('imgShown' + field).style.display = 'none';
		$('parent' + field).className = '';
    	}else {
    		$('imgHidden' + field).style.display = 'none';
		$('imgShown' + field).style.display = '';
		$('parent' + field).className = 'active';
    	}

    }

function setPlayerHeight(height) {
    setPromotionHeight("promotionplayer", height);
}

function setChooserHeight(height) {
    setPromotionHeight("promotionchooser", height);
}

function setPromotionHeight(elementId, height) {
	var obj = document.getElementById(elementId);
	obj.style.display = "block";
    obj.style.height = height + "px";
}

function getURL(url) {
    var lowerCaseUrl = url.toLowerCase();
    var popupUrl;
    var popup;
    
    if (lowerCaseUrl.indexOf('livebetting') == 0) {
        var eventId = url.substring(url.lastIndexOf(':') + 1, url.length);
        popupUrl = '/livebetting/flash.do?eventId=' + eventId + "&channelId=6";
        popup = window.open(popupUrl, 'liveWin_' + eventId, "toolbar=no,alwaysRaised=yes,dependent=yes,menubar=no,resizable=yes,scrollbars=yes,height=600,width=1009");
        popup.focus();
    } else if (lowerCaseUrl.indexOf('bingo') == 0) {
        launchGame();
    } else if (lowerCaseUrl.indexOf('openwin') == 0) {
        popupUrl = url.substring(url.lastIndexOf(':') + 1, url.length);
        popup = window.open(popupUrl);
        popup.focus();
    } else {
        window.location = url;
    }
}

function openLivebetting() {
    var popupUrl = '/livebetting/flash.do?channelId=6';
    var popup = window.open(popupUrl, '_blank', "toolbar=no,alwaysRaised=yes,dependent=yes,menubar=no,resizable=yes,scrollbars=yes,height=600,width=1009");
    popup.focus();
}

function selectLivebettingPromoEvent(eventId){
    var popupUrl = '/livebetting/flash.do?eventId=' + eventId + "&channelId=6";
    var popup = window.open(popupUrl, 'liveWin_' + eventId, "toolbar=no,alwaysRaised=yes,dependent=yes,menubar=no,resizable=yes,scrollbars=yes,height=600,width=1009");
    popup.focus();
}

function doFrameworkCallback(url, cookieNumber) {
	new Ajax.Request('/register/callback.do?uri=' + url, { method:'get' });
	document.cookie = 'unibetCallback' + cookieNumber + '=0;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT;';
}

function removeCallbackCountCookie() {
	document.cookie = 'unibetCallbackcallbackCount=0;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT;';
}
/* ========================================================================
   ===  flash8fixIE.js                                                  ===
   ========================================================================
   ===  created by: Robert Nordin, Danero (consultant)                  ===
   ========================================================================
   ===  Will essentially "disable" cashing for Internet Explorer with   ===
   ===  flashversion 8. Background problem is that IE does not read or  ===
   ===  start an already cached flash. This fix "forces" IE to look for ===
   ===  the flash again, thus "disabling" cashing. To reduce number of  ===
   ===  extra flash downloads checking for IE and Flash8 is made.       ===
   ========================================================================
 */

var IE     = false;
var Flash8 = false;
var fixstr = "";
var agent  = navigator.userAgent.toLowerCase();

if (agent.indexOf("msie") != -1)
{ 
  IE = true;
}

if (IE == true)
{
  var xobj = null;
  try
  {
    xobj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
    flashVersion = xobj.GetVariable("$version").split(",")[0].split(" ")[1];
    if (flashVersion == "8")
    {
      Flash8 = true;      
    }
    else
    {
      fixstr = "";
    }    
  }
  catch (e)
  { 
    fixstr = "";
  } 
}

function getIEFixStr()
{
  return (IE && Flash8) ? ("?" + Math.random() + new Date().getTime()) : "";
}


