
// script.aculo.us Resizables.js

// Copyright(c) 2007 - Orr Siloni, Comet Information Systems http://www.comet.co.il/en/
//
// Resizable.js is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Resizables = {
	instances: [],
	observers: [],
	
	register: function(resizable) {
		if(this.instances.length == 0) {
			this.eventMouseUp   = this.endResize.bindAsEventListener(this);
			this.eventMouseMove = this.updateResize.bindAsEventListener(this);
			
			Event.observe(document, "mouseup", this.eventMouseUp);
			Event.observe(document, "mousemove", this.eventMouseMove);
		}
		this.instances.push(resizable);
	},
	
	unregister: function(resizable) {
		this.instances = this.instances.reject(function(d) { return d==resizable });
		if(this.instances.length == 0) {
			Event.stopObserving(document, "mouseup", this.eventMouseUp);
			Event.stopObserving(document, "mousemove", this.eventMouseMove);
		}
	},
	
	activate: function(resizable) {
		if(resizable.options.delay) { 
			this._timeout = setTimeout(function() {
				Resizables._timeout = null; 
				Resizables.activeResizable = resizable; 
			}.bind(this), resizable.options.delay); 
		} else {
			this.activeResizable = resizable;
		}
	},
	
	deactivate: function() {
		this.activeResizable = null;
	},
	
	updateResize: function(event) {
		if(!this.activeResizable) return;
		var pointer = [Event.pointerX(event), Event.pointerY(event)];
		// Mozilla-based browsers fire successive mousemove events with
		// the same coordinates, prevent needless redrawing (moz bug?)
		if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
		this._lastPointer = pointer;
		
		this.activeResizable.updateResize(event, pointer);
	},
	
	endResize: function(event) {
		if(this._timeout) { 
		  clearTimeout(this._timeout); 
		  this._timeout = null; 
		}
		if(!this.activeResizable) return;
		this._lastPointer = null;
		this.activeResizable.endResize(event);
		this.activeResizable = null;
	},
	
	addObserver: function(observer) {
		this.observers.push(observer);
		this._cacheObserverCallbacks();
	},
  
	removeObserver: function(element) {  // element instead of observer fixes mem leaks
		this.observers = this.observers.reject( function(o) { return o.element==element });
		this._cacheObserverCallbacks();
	},
	
	notify: function(eventName, resizable, event) {  // 'onStart', 'onEnd', 'onResize'
		if(this[eventName+'Count'] > 0)
			this.observers.each( function(o) {
				if(o[eventName]) o[eventName](eventName, resizable, event);
			});
		if(resizable.options[eventName]) resizable.options[eventName](resizable, event);
	},
	
	_cacheObserverCallbacks: function() {
		['onStart','onEnd','onResize'].each( function(eventName) {
			Resizables[eventName+'Count'] = Resizables.observers.select(
				function(o) { return o[eventName]; }
			).length;
		});
	}
}

var Resizable = Class.create();
Resizable._resizing = {};

Resizable.prototype = {
	initialize: function(element){
		var defaults = {
			handle: false,
			snap: false,  // false, or xy or [x,y] or function(x,y){ return [x,y] }
			delay: 0,
			minHeight: false,
			minwidth: false,
			maxHeight: false,
			maxWidth: false
		}
		
		this.element = $(element);
		
		var options = Object.extend(defaults, arguments[1] || {});
		if(options.handle && typeof options.handle == 'string')
			this.handle = $(options.handle);
		else if(options.handle)
			this.handle = options.handle;
			
		if(!this.handle) this.handle = this.element;
		
		this.options  = options;
		this.dragging = false;
		
		this.eventMouseDown = this.initResize.bindAsEventListener(this);
		Event.observe(this.handle, "mousedown", this.eventMouseDown);
		
		Resizables.register(this);
	},
	
	destroy: function() {
		Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
	},
	
	currentDelta: function() {
		return([
			parseInt(Element.getStyle(this.element,'width') || '0'),
			parseInt(Element.getStyle(this.element,'height') || '0')]);
	},
	
	initResize: function(event) {
		if(typeof Resizable._resizing[this.element] != 'undefined' &&
			Resizable._resizing[this.element]) return;
		if(Event.isLeftClick(event)) {
			// abort on form elements, fixes a Firefox issue
			var src = Event.element(event);
			if((tag_name = src.tagName.toUpperCase()) && (
				tag_name=='INPUT' || tag_name=='SELECT' || tag_name=='OPTION' ||
				tag_name=='BUTTON' || tag_name=='TEXTAREA')) return;
			
			this.pointer = [Event.pointerX(event), Event.pointerY(event)];
			this.size = [parseInt(this.element.getStyle('width')) || 0, parseInt(this.element.getStyle('height')) || 0];
			
			Resizables.activate(this);
			Event.stop(event);
		}
	},
	
	startResize: function(event) {
		this.resizing = true;
		if(this.options.zindex) {
			this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
			this.element.style.zIndex = this.options.zindex;
		}
		Resizables.notify('onStart', this, event);
		Resizable._resizing[this.element] = true;
	},
	
	updateResize: function(event, pointer) {
		if(!this.resizing) this.startResize(event);
		
		Resizables.notify('onResize', this, event);
		
		this.draw(pointer);
		if(this.options.change) this.options.change(this);
		
		// fix AppleWebKit rendering
		if(Prototype.Browser.WebKit) window.scrollBy(0,0);
		Event.stop(event);
	},
	
	finishResize: function(event, success) {
		this.resizing = false;
		Resizables.notify('onEnd', this, event);
		if(this.options.zindex) this.element.style.zIndex = this.originalZ;
		Resizable._resizing[this.element] = false;
		Resizables.deactivate(this);
	},
	
	endResize: function(event) {
		if(!this.resizing) return;
		this.finishResize(event, true);
		Event.stop(event);
	},
	
	draw: function(point) {
		var p = [0,1].map(function(i){ 
			return (this.size[i] + point[i] - this.pointer[i]);
		}.bind(this));
		
		if(this.options.snap) {
			if(typeof this.options.snap == 'function') {
				p = this.options.snap(p[0],p[1],this);
			} else {
				if(this.options.snap instanceof Array) {
				p = p.map( function(v, i) {
				return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
			} else {
				p = p.map( function(v) {
				return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
			}
		}}
		
		var minWidth = (typeof(this.options.minWidth) == 'function') ? this.options.minWidth(this.element) : this.options.minWidth;
		var maxWidth = (typeof(this.options.maxWidth) == 'function') ? this.options.maxWidth(this.element) : this.options.maxWidth;
		var minHeight = (typeof(this.options.minHeight) == 'function') ? this.options.minHeight(this.element) : this.options.minHeight;
		var maxHeight = (typeof(this.options.maxHeight) == 'function') ? this.options.maxHeight(this.element) : this.options.maxHeight;

		if (minWidth && p[0] <= minWidth) p[0] = minWidth;
		if (maxWidth && p[0] >= maxWidth) p[0] = maxWidth;
		if (minHeight && p[1] <= minHeight) p[1] = minHeight;
		if (maxHeight && p[1] >= maxHeight) p[1] = maxHeight;
		
		var style = this.element.style;
		if((!this.options.constraint) || (this.options.constraint=='horizontal')){
			style.width = p[0] + "px";
		}
		if((!this.options.constraint) || (this.options.constraint=='vertical')){
			style.height = p[1] + "px";
		}
		
		if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
	}
};


/**
 * @author Ryan Johnson <http://syntacticx.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/core
 * @require prototype.js
 */

if(typeof(Control) == 'undefined')
    Control = {};
    
var $proc = function(proc){
    return typeof(proc) == 'function' ? proc : function(){return proc};
};

var $value = function(value){
    return typeof(value) == 'function' ? value() : value;
};

Object.Event = {
    extend: function(object){
        object._objectEventSetup = function(event_name){
            this._observers = this._observers || {};
            this._observers[event_name] = this._observers[event_name] || [];
        };
        object.observe = function(event_name,observer){
            if(typeof(event_name) == 'string' && typeof(observer) != 'undefined'){
                this._objectEventSetup(event_name);
                if(!this._observers[event_name].include(observer))
                    this._observers[event_name].push(observer);
            }else
                for(var e in event_name)
                    this.observe(e,event_name[e]);
        };
        object.stopObserving = function(event_name,observer){
            this._objectEventSetup(event_name);
            if(event_name && observer)
                this._observers[event_name] = this._observers[event_name].without(observer);
            else if(event_name)
                this._observers[event_name] = [];
            else
                this._observers = {};
        };
        object.observeOnce = function(event_name,outer_observer){
            var inner_observer = function(){
                outer_observer.apply(this,arguments);
                this.stopObserving(event_name,inner_observer);
            }.bind(this);
            this._objectEventSetup(event_name);
            this._observers[event_name].push(inner_observer);
        };
        object.notify = function(event_name){
            this._objectEventSetup(event_name);
            var collected_return_values = [];
            var args = $A(arguments).slice(1);
            try{
                for(var i = 0; i < this._observers[event_name].length; ++i)
                    collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args) || null);
            }catch(e){
                if(e == $break)
                    return false;
                else
                    throw e;
            }
            return collected_return_values;
        };
        if(object.prototype){
            object.prototype._objectEventSetup = object._objectEventSetup;
            object.prototype.observe = object.observe;
            object.prototype.stopObserving = object.stopObserving;
            object.prototype.observeOnce = object.observeOnce;
            object.prototype.notify = function(event_name){
                if(object.notify){
                    var args = $A(arguments).slice(1);
                    args.unshift(this);
                    args.unshift(event_name);
                    object.notify.apply(object,args);
                }
                this._objectEventSetup(event_name);
                var args = $A(arguments).slice(1);
                var collected_return_values = [];
                try{
                    if(this.options && this.options[event_name] && typeof(this.options[event_name]) == 'function')
                        collected_return_values.push(this.options[event_name].apply(this,args) || null);
                    for(var i = 0; i < this._observers[event_name].length; ++i)
                        collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args) || null);
                }catch(e){
                    if(e == $break)
                        return false;
                    else
                        throw e;
                }
                return collected_return_values;
            };
        }
    }
};

/* Begin Core Extensions */

//Element.observeOnce
Element.addMethods({
    observeOnce: function(element,event_name,outer_callback){
        var inner_callback = function(){
            outer_callback.apply(this,arguments);
            Element.stopObserving(element,event_name,inner_callback);
        };
        Element.observe(element,event_name,inner_callback);
    }
});

//mouse:wheel
(function(){
    function wheel(event){
        var delta, element, custom_event;
        // normalize the delta
        if (event.wheelDelta) { // IE & Opera
            delta = event.wheelDelta / 120;
        } else if (event.detail) { // W3C
            delta =- event.detail / 3;
        }
        if (!delta) { return; }
        element = Event.extend(event).target;
        element = Element.extend(element.nodeType === Node.TEXT_NODE ? element.parentNode : element);
        custom_event = element.fire('mouse:wheel',{ delta: delta });
        if (custom_event.stopped) {
            Event.stop(event);
            return false;
        }
    }
    document.observe('mousewheel',wheel);
    document.observe('DOMMouseScroll',wheel);
})();

/* End Core Extensions */

//from PrototypeUI
var IframeShim = Class.create({
    initialize: function() {
        this.element = new Element('iframe',{
            style: 'position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);display:none',
            src: 'javascript:void(0);',
            frameborder: 0 
        });
        $(document.body).insert(this.element);
    },
    hide: function() {
        this.element.hide();
        return this;
    },
    show: function() {
        this.element.show();
        return this;
    },
    positionUnder: function(element) {
        var element = $(element);
        var offset = element.cumulativeOffset();
        var dimensions = element.getDimensions();
        this.element.setStyle({
            left: offset[0] + 'px',
            top: offset[1] + 'px',
            width: dimensions.width + 'px',
            height: dimensions.height + 'px',
            zIndex: element.getStyle('zIndex') - 1
        }).show();
        return this;
    },
    setBounds: function(bounds) {
        for(prop in bounds)
            bounds[prop] += 'px';
        this.element.setStyle(bounds);
        return this;
    },
    destroy: function() {
        if(this.element)
            this.element.remove();
        return this;
    }
});


/**
 * @author Ryan Johnson <http://syntacticx.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/control/window
 * @require prototype.js, effects.js, draggable.js, resizable.js, livepipe.js
 */

//adds onDraw and constrainToViewport option to draggable
if(typeof(Draggable) != 'undefined'){
    //allows the point to be modified with an onDraw callback
    Draggable.prototype.draw = function(point) {
        var pos = Position.cumulativeOffset(this.element);
        if(this.options.ghosting) {
            var r = Position.realOffset(this.element);
            pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
        }
        
        var d = this.currentDelta();
        pos[0] -= d[0]; pos[1] -= d[1];
        
        if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
            pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
            pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
        }
        
        var p = [0,1].map(function(i){ 
            return (point[i]-pos[i]-this.offset[i]) 
        }.bind(this));
        
        if(this.options.snap) {
            if(typeof this.options.snap == 'function') {
                p = this.options.snap(p[0],p[1],this);
            } else {
                if(this.options.snap instanceof Array) {
                    p = p.map( function(v, i) {return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
                } else {
                    p = p.map( function(v) {return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
                  }
            }
        }
        
        if(this.options.onDraw)
            this.options.onDraw.bind(this)(p);
        else{
            var style = this.element.style;
            if(this.options.constrainToViewport){
                var viewport_dimensions = document.viewport.getDimensions();
                var container_dimensions = this.element.getDimensions();
                var margin_top = parseInt(this.element.getStyle('margin-top'));
                var margin_left = parseInt(this.element.getStyle('margin-left'));
                var boundary = [[
                    0 - margin_left,
                    0 - margin_top
                ],[
                    (viewport_dimensions.width - container_dimensions.width) - margin_left,
                    (viewport_dimensions.height - container_dimensions.height) - margin_top
                ]];
                if((!this.options.constraint) || (this.options.constraint=='horizontal')){ 
                    if((p[0] >= boundary[0][0]) && (p[0] <= boundary[1][0]))
                        this.element.style.left = p[0] + "px";
                    else
                        this.element.style.left = ((p[0] < boundary[0][0]) ? boundary[0][0] : boundary[1][0]) + "px";
                } 
                if((!this.options.constraint) || (this.options.constraint=='vertical')){ 
                    if((p[1] >= boundary[0][1] ) && (p[1] <= boundary[1][1]))
                        this.element.style.top = p[1] + "px";
                  else
                        this.element.style.top = ((p[1] <= boundary[0][1]) ? boundary[0][1] : boundary[1][1]) + "px";               
                }
            }else{
                if((!this.options.constraint) || (this.options.constraint=='horizontal'))
                  style.left = p[0] + "px";
                if((!this.options.constraint) || (this.options.constraint=='vertical'))
                  style.top     = p[1] + "px";
            }
            if(style.visibility=="hidden")
                style.visibility = ""; // fix gecko rendering
        }
    };
}

if(typeof(Prototype) == "undefined")
    throw "Control.Window requires Prototype to be loaded.";
if(typeof(IframeShim) == "undefined")
    throw "Control.Window requires IframeShim to be loaded.";
if(typeof(Object.Event) == "undefined")
    throw "Control.Window requires Object.Event to be loaded.";
/*
    known issues:
        - when iframe is clicked is does not gain focus
        - safari can't open multiple iframes properly
        - constrainToViewport: body must have no margin or padding for this to work properly
        - iframe will be mis positioned during fade in
        - document.viewport does not account for scrollbars (this will eventually be fixed in the prototype core)
    notes
        - setting constrainToViewport only works when the page is not scrollable
        - setting draggable: true will negate the effects of position: center
*/
Control.Window = Class.create({
    initialize: function(container,options){
        Control.Window.windows.push(this);
        
        //attribute initialization
        this.container = false;
        this.isOpen = false;
        this.href = false;
        this.sourceContainer = false; //this is optionally the container that will open the window
        this.ajaxRequest = false;
        this.remoteContentLoaded = false; //this is set when the code to load the remote content is run, onRemoteContentLoaded is fired when the connection is closed
        this.numberInSequence = Control.Window.windows.length + 1; //only useful for the effect scoping
        this.indicator = false;
        this.effects = {
            fade: false,
            appear: false
        };
        this.indicatorEffects = {
            fade: false,
            appear: false
        };
        
        //options
        this.options = Object.extend({
            //lifecycle
            beforeOpen: Prototype.emptyFunction,
            afterOpen: Prototype.emptyFunction,
            beforeClose: Prototype.emptyFunction,
            afterClose: Prototype.emptyFunction,
            //dimensions and modes
            height: null,
            width: null,
            className: false,
            position: 'center', //'center', 'relative', [x,y], [function(){return x;},function(){return y;}]
            offsetLeft: 0, //available only for anchors opening the window, or windows set to position: hover
            offsetTop: 0, //""
            iframe: false, //if the window has an href, this will display the href as an iframe instead of requesting the url as an an Ajax.Request
            hover: false, //element object to hover over, or if "true" only available for windows with sourceContainer (an anchor or any element already on the page with an href attribute)
            indicator: false, //element to show or hide when ajax requests, images and iframes are loading
            closeOnClick: false, //does not work with hover,can be: true (click anywhere), 'container' (will refer to this.container), or element (a specific element)
            iframeshim: true, //whether or not to position an iFrameShim underneath the window 
            //effects
            fade: false,
            fadeDuration: 0.75,
            //draggable
            draggable: false,
            onDrag: Prototype.emptyFunction,
            //resizable
            resizable: false,
            minHeight: false,
            minWidth: false,
            maxHeight: false,
            maxWidth: false,
            onResize: Prototype.emptyFunction,
            //draggable and resizable
            constrainToViewport: false,
            //ajax
            method: 'post',
            parameters: {},
            onComplete: Prototype.emptyFunction,
            onSuccess: Prototype.emptyFunction,
            onFailure: Prototype.emptyFunction,
            onException: Prototype.emptyFunction,
            //any element with an href (image,iframe,ajax) will call this after it is done loading
            onRemoteContentLoaded: Prototype.emptyFunction,
            insertRemoteContentAt: false //false will set this to this.container, can be string selector (first returned will be selected), or an Element that must be a child of this.container
        },options || {});
        
        //container setup
        this.indicator = this.options.indicator ? $(this.options.indicator) : false;
        if(container){
            if(typeof(container) == "string" && container.match(Control.Window.uriRegex))
                this.href = container;
            else{
                this.container = $(container);
                //need to create the container now for tooltips (or hover: element with no container already on the page)
                //second call made below will not create the container since the check is done inside createDefaultContainer()
                this.createDefaultContainer(container);
                //if an element with an href was passed in we use it to activate the window
                if(this.container && ((this.container.readAttribute('href') && this.container.readAttribute('href') != '') || (this.options.hover && this.options.hover !== true))){                        
                    if(this.options.hover && this.options.hover !== true)
                        this.sourceContainer = $(this.options.hover);
                    else{
                        this.sourceContainer = this.container;
                        this.href = this.container.readAttribute('href');
                        var rel = this.href.match(/^#(.+)$/);
                        if(rel && rel[1]){
                            this.container = $(rel[1]);
                            this.href = false;
                        }else
                            this.container = false;
                    }
                    //hover or click handling
                    this.sourceContainerOpenHandler = function(event){
                        this.open(event);
                        event.stop();
                        return false;
                    }.bindAsEventListener(this);
                    this.sourceContainerCloseHandler = function(event){
                        this.close(event);
                    }.bindAsEventListener(this);
                    this.sourceContainerMouseMoveHandler = function(event){
                        this.position(event);
                    }.bindAsEventListener(this);
                    if(this.options.hover){
                        this.sourceContainer.observe('mouseenter',this.sourceContainerOpenHandler);
                        this.sourceContainer.observe('mouseleave',this.sourceContainerCloseHandler);
                        if(this.options.position == 'mouse')
                            this.sourceContainer.observe('mousemove',this.sourceContainerMouseMoveHandler);
                    }else
                        this.sourceContainer.observe('click',this.sourceContainerOpenHandler);
                }
            }
        }
        this.createDefaultContainer(container);
        if(this.options.insertRemoteContentAt === false)
            this.options.insertRemoteContentAt = this.container;
        var styles = {
            margin: 0,
            position: 'absolute',
            zIndex: Control.Window.initialZIndexForWindow()
        };
        if(this.options.width)
            styles.width = $value(this.options.width) + 'px';
        if(this.options.height)
            styles.height = $value(this.options.height) + 'px';
        this.container.setStyle(styles);
        if(this.options.className)
            this.container.addClassName(this.options.className);
        this.positionHandler = this.position.bindAsEventListener(this);
        this.outOfBoundsPositionHandler = this.ensureInBounds.bindAsEventListener(this);
        this.bringToFrontHandler = this.bringToFront.bindAsEventListener(this);
        this.container.observe('mousedown',this.bringToFrontHandler);
        this.container.hide();
        this.closeHandler = this.close.bindAsEventListener(this);
        //iframeshim setup
        if(this.options.iframeshim){
            this.iFrameShim = new IframeShim();
            this.iFrameShim.hide();
        }
        //resizable support
        this.applyResizable();
        //draggable support
        this.applyDraggable();
        
        //makes sure the window can't go out of bounds
        Event.observe(window,'resize',this.outOfBoundsPositionHandler);
        
        this.notify('afterInitialize');
    },
    open: function(event){
        if(this.isOpen){
            this.bringToFront();
            return false;
        }
        if(this.notify('beforeOpen') === false)
            return false;
        //closeOnClick
        if(this.options.closeOnClick){
            if(this.options.closeOnClick === true)
                this.closeOnClickContainer = $(document.body);
            else if(this.options.closeOnClick == 'container')
                this.closeOnClickContainer = this.container;
            else if (this.options.closeOnClick == 'overlay'){
                Control.Overlay.load();
                this.closeOnClickContainer = Control.Overlay.container;
            }else
                this.closeOnClickContainer = $(this.options.closeOnClick);
            this.closeOnClickContainer.observe('click',this.closeHandler);
        }
        if(this.href && !this.options.iframe && !this.remoteContentLoaded){
            //link to image
            this.remoteContentLoaded = true;
            if(this.href.match(/\.(jpe?g|gif|png|tiff?)$/i)){
                var img = new Element('img');
                img.observe('load',function(img){
                    this.getRemoteContentInsertionTarget().insert(img);
                    this.position();
                    if(this.notify('onRemoteContentLoaded') !== false){
                        if(this.options.indicator)
                            this.hideIndicator();
                        this.finishOpen();
                    }
                }.bind(this,img));
                img.writeAttribute('src',this.href);
            }else{
                //if this is an ajax window it will only open if the request is successful
                if(!this.ajaxRequest){
                    if(this.options.indicator)
                        this.showIndicator();
                    this.ajaxRequest = new Ajax.Request(this.href,{
                        method: this.options.method,
                        parameters: this.options.parameters,
                        onComplete: function(request){
                            this.notify('onComplete',request);
                            this.ajaxRequest = false;
                        }.bind(this),
                        onSuccess: function(request){
                            this.getRemoteContentInsertionTarget().insert(request.responseText);
                            this.notify('onSuccess',request);
                            if(this.notify('onRemoteContentLoaded') !== false){
                                if(this.options.indicator)
                                    this.hideIndicator();
                                this.finishOpen();
                            }
                        }.bind(this),
                        onFailure: function(request){
                            this.notify('onFailure',request);
                            if(this.options.indicator)
                                this.hideIndicator();
                        }.bind(this),
                        onException: function(request,e){
                            this.notify('onException',request,e);
                            if(this.options.indicator)
                                this.hideIndicator();
                        }.bind(this)
                    });
                }
            }
            return true;
        }else if(this.options.iframe && !this.remoteContentLoaded){
            //iframe
            this.remoteContentLoaded = true;
            if(this.options.indicator)
                this.showIndicator();
            this.getRemoteContentInsertionTarget().insert(Control.Window.iframeTemplate.evaluate({
                href: this.href
            }));
            var iframe = this.container.down('iframe');
            iframe.onload = function(){
                this.notify('onRemoteContentLoaded');
                if(this.options.indicator)
                    this.hideIndicator();
                iframe.onload = null;
            }.bind(this);
        }
        this.finishOpen(event);
        return true
    },
    close: function(event){ //event may or may not be present
        if(!this.isOpen || this.notify('beforeClose',event) === false)
            return false;
        if(this.options.closeOnClick)
            this.closeOnClickContainer.stopObserving('click',this.closeHandler);
        if(this.options.fade){
            this.effects.fade = new Effect.Fade(this.container,{
                queue: {
                    position: 'front',
                    scope: 'Control.Window' + this.numberInSequence
                },
                from: 1,
                to: 0,
                duration: this.options.fadeDuration / 2,
                afterFinish: function(){
                    if(this.iFrameShim)
                        this.iFrameShim.hide();
                    this.isOpen = false;
                    this.notify('afterClose');
                }.bind(this)
            });
        }else{
            this.container.hide();
            if(this.iFrameShim)
                this.iFrameShim.hide();
        }
        if(this.ajaxRequest)
            this.ajaxRequest.transport.abort();
        if(!(this.options.draggable || this.options.resizable) && this.options.position == 'center')
            Event.stopObserving(window,'resize',this.positionHandler);
        if(!this.options.draggable && this.options.position == 'center')
            Event.stopObserving(window,'scroll',this.positionHandler);
        if(this.options.indicator)
            this.hideIndicator();
        if(!this.options.fade){
            this.isOpen = false;
            this.notify('afterClose');
        }
        return true;
    },
    position: function(event){
        //this is up top for performance reasons
        if(this.options.position == 'mouse'){
            var xy = [Event.pointerX(event),Event.pointerY(event)];
            this.container.setStyle({
                top: xy[1] + $value(this.options.offsetTop) + 'px',
                left: xy[0] + $value(this.options.offsetLeft) + 'px'
            });
            return;
        }
        var container_dimensions = this.container.getDimensions();
        var viewport_dimensions = document.viewport.getDimensions();
        Position.prepare();
        var offset_left = (Position.deltaX + Math.floor((viewport_dimensions.width - container_dimensions.width) / 2));
        var offset_top = (Position.deltaY + ((viewport_dimensions.height > container_dimensions.height) ? Math.floor((viewport_dimensions.height - container_dimensions.height) / 2) : 0));
        if(this.options.position == 'center'){
            this.container.setStyle({
                top: (container_dimensions.height <= viewport_dimensions.height) ? ((offset_top != null && offset_top > 0) ? offset_top : 0) + 'px' : 0,
                left: (container_dimensions.width <= viewport_dimensions.width) ? ((offset_left != null && offset_left > 0) ? offset_left : 0) + 'px' : 0
            });
        }else if(this.options.position == 'relative'){
            var xy = this.sourceContainer.cumulativeOffset();
            var top = xy[1] + $value(this.options.offsetTop);
            var left = xy[0] + $value(this.options.offsetLeft);
            this.container.setStyle({
                top: (container_dimensions.height <= viewport_dimensions.height) ? (this.options.constrainToViewport ? Math.max(0,Math.min(viewport_dimensions.height - (container_dimensions.height),top)) : top) + 'px' : 0,
                left: (container_dimensions.width <= viewport_dimensions.width) ? (this.options.constrainToViewport ? Math.max(0,Math.min(viewport_dimensions.width - (container_dimensions.width),left)) : left) + 'px' : 0
            });
        }else if(this.options.position.length){
            var top = $value(this.options.position[1]) + $value(this.options.offsetTop);
            var left = $value(this.options.position[0]) + $value(this.options.offsetLeft);
            this.container.setStyle({
                top: (container_dimensions.height <= viewport_dimensions.height) ? (this.options.constrainToViewport ? Math.max(0,Math.min(viewport_dimensions.height - (container_dimensions.height),top)) : top) + 'px' : 0,
                left: (container_dimensions.width <= viewport_dimensions.width) ? (this.options.constrainToViewport ? Math.max(0,Math.min(viewport_dimensions.width - (container_dimensions.width),left)) : left) + 'px' : 0
            });
        }
        if(this.iFrameShim)
            this.updateIFrameShimZIndex();
    },
    ensureInBounds: function(){
        if(!this.isOpen)
            return;
        var viewport_dimensions = document.viewport.getDimensions();
        var container_offset = this.container.cumulativeOffset();
        var container_dimensions = this.container.getDimensions();
        if(container_offset.left + container_dimensions.width > viewport_dimensions.width){
            this.container.setStyle({
                left: (Math.max(0,viewport_dimensions.width - container_dimensions.width)) + 'px'
            });
        }
        if(container_offset.top + container_dimensions.height > viewport_dimensions.height){
            this.container.setStyle({
                top: (Math.max(0,viewport_dimensions.height - container_dimensions.height)) + 'px'
            });
        }
    },
    bringToFront: function(){
        Control.Window.bringToFront(this);
        this.notify('bringToFront');
    },
    destroy: function(){
        this.container.stopObserving('mousedown',this.bringToFrontHandler);
        if(this.draggable){
            Draggables.removeObserver(this.container);
            this.draggable.handle.stopObserving('mousedown',this.bringToFrontHandler);
            this.draggable.destroy();
        }
        if(this.resizable){
            Resizables.removeObserver(this.container);
            this.resizable.handle.stopObserving('mousedown',this.bringToFrontHandler);
            this.resizable.destroy();
        }
        if(this.container && !this.sourceContainer)
            this.container.remove();
        if(this.sourceContainer){
            if(this.options.hover){
                this.sourceContainer.stopObserving('mouseenter',this.sourceContainerOpenHandler);
                this.sourceContainer.stopObserving('mouseleave',this.sourceContainerCloseHandler);
                if(this.options.position == 'mouse')
                    this.sourceContainer.stopObserving('mousemove',this.sourceContainerMouseMoveHandler);
            }else
                this.sourceContainer.stopObserving('click',this.sourceContainerOpenHandler);
        }
        if(this.iFrameShim)
            this.iFrameShim.destroy();
        Event.stopObserving(window,'resize',this.outOfBoundsPositionHandler);
        Control.Window.windows = Control.Window.windows.without(this);
        this.notify('afterDestroy');
    },
    //private
    applyResizable: function(){
        if(this.options.resizable){
            if(typeof(Resizable) == "undefined")
                throw "Control.Window requires resizable.js to be loaded.";
            var resizable_handle = null;
            if(this.options.resizable === true){
                resizable_handle = new Element('div',{
                    className: 'resizable_handle'
                });
                this.container.insert(resizable_handle);
            }else
                resizable_handle = $(this.options.resziable);
            this.resizable = new Resizable(this.container,{
                handle: resizable_handle,
                minHeight: this.options.minHeight,
                minWidth: this.options.minWidth,
                maxHeight: this.options.constrainToViewport ? function(element){
                    //viewport height - top - total border height
                    return (document.viewport.getDimensions().height - parseInt(element.style.top || 0)) - (element.getHeight() - parseInt(element.style.height || 0));
                } : this.options.maxHeight,
                maxWidth: this.options.constrainToViewport ? function(element){
                    //viewport width - left - total border width
                    return (document.viewport.getDimensions().width - parseInt(element.style.left || 0)) - (element.getWidth() - parseInt(element.style.width || 0));
                } : this.options.maxWidth
            });
            this.resizable.handle.observe('mousedown',this.bringToFrontHandler);
            Resizables.addObserver(new Control.Window.LayoutUpdateObserver(this,function(){
                if(this.iFrameShim)
                    this.updateIFrameShimZIndex();
                this.notify('onResize');
            }.bind(this)));
        }
    },
    applyDraggable: function(){
        if(this.options.draggable){
            if(typeof(Draggables) == "undefined")
                throw "Control.Window requires dragdrop.js to be loaded.";
            var draggable_handle = null;
            if(this.options.draggable === true){
                draggable_handle = new Element('div',{
                    className: 'draggable_handle'
                });
                this.container.insert(draggable_handle);
            }else
                draggable_handle = $(this.options.draggable);
            this.draggable = new Draggable(this.container,{
                handle: draggable_handle,
                constrainToViewport: this.options.constrainToViewport,
                zindex: this.container.getStyle('z-index'),
                starteffect: function(){
                    if(Prototype.Browser.IE){
                        this.old_onselectstart = document.onselectstart;
                        document.onselectstart = function(){
                            return false;
                        };
                    }
                }.bind(this),
                endeffect: function(){
                    document.onselectstart = this.old_onselectstart;
                }.bind(this)
            });
            this.draggable.handle.observe('mousedown',this.bringToFrontHandler);
            Draggables.addObserver(new Control.Window.LayoutUpdateObserver(this,function(){
                if(this.iFrameShim)
                    this.updateIFrameShimZIndex();
                this.notify('onDrag');
            }.bind(this)));
        }
    },
    createDefaultContainer: function(container){
        if(!this.container){
            //no container passed or found, create it
            this.container = new Element('div',{
                id: 'control_window_' + this.numberInSequence
            });
            $(document.body).insert(this.container);
            if(typeof(container) == "string" && $(container) == null && !container.match(/^#(.+)$/) && !container.match(Control.Window.uriRegex))
                this.container.update(container);
        }
    },
    finishOpen: function(event){
        this.bringToFront();
        if(this.options.fade){
            if(typeof(Effect) == "undefined")
                throw "Control.Window requires effects.js to be loaded."
            if(this.effects.fade)
                this.effects.fade.cancel();
            this.effects.appear = new Effect.Appear(this.container,{
                queue: {
                    position: 'end',
                    scope: 'Control.Window.' + this.numberInSequence
                },
                from: 0,
                to: 1,
                duration: this.options.fadeDuration / 2,
                afterFinish: function(){
                    if(this.iFrameShim)
                        this.updateIFrameShimZIndex();
                    this.isOpen = true;
                    this.notify('afterOpen');
                }.bind(this)
            });
        }else
            this.container.show();
        this.position(event);
        if(!(this.options.draggable || this.options.resizable) && this.options.position == 'center')
            Event.observe(window,'resize',this.positionHandler,false);
        if(!this.options.draggable && this.options.position == 'center')
            Event.observe(window,'scroll',this.positionHandler,false);
        if(!this.options.fade){
            this.isOpen = true;
            this.notify('afterOpen');
        }
        return true;
    },
    showIndicator: function(){
        this.showIndicatorTimeout = window.setTimeout(function(){
            if(this.options.fade){
                this.indicatorEffects.appear = new Effect.Appear(this.indicator,{
                    queue: {
                        position: 'front',
                        scope: 'Control.Window.indicator.' + this.numberInSequence
                    },
                    from: 0,
                    to: 1,
                    duration: this.options.fadeDuration / 2
                });
            }else
                this.indicator.show();
        }.bind(this),Control.Window.indicatorTimeout);
    },
    hideIndicator: function(){
        if(this.showIndicatorTimeout)
            window.clearTimeout(this.showIndicatorTimeout);
        this.indicator.hide();
    },
    getRemoteContentInsertionTarget: function(){
        return typeof(this.options.insertRemoteContentAt) == "string" ? this.container.down(this.options.insertRemoteContentAt) : $(this.options.insertRemoteContentAt);
    },
    updateIFrameShimZIndex: function(){
        if(this.iFrameShim)
            this.iFrameShim.positionUnder(this.container);
    }
});
//class methods
Object.extend(Control.Window,{
    windows: [],
    baseZIndex: 9999,
    indicatorTimeout: 250,
    iframeTemplate: new Template('<iframe src="#{href}" width="100%" height="100%" frameborder="0"></iframe>'),
    uriRegex: /^(\/|\#|https?\:\/\/|[\w]+\/)/,
    bringToFront: function(w){
        Control.Window.windows = Control.Window.windows.without(w);
        Control.Window.windows.push(w);
        Control.Window.windows.each(function(w,i){
            var z_index = Control.Window.baseZIndex + i;
            w.container.setStyle({
                zIndex: z_index
            });
            if(w.isOpen){
                if(w.iFrameShim)
                w.updateIFrameShimZIndex();
            }
            if(w.options.draggable)
                w.draggable.options.zindex = z_index;
        });
    },
    open: function(container,options){
        var w = new Control.Window(container,options);
        w.open();
        return w;
    },
    //protected
    initialZIndexForWindow: function(w){
        return Control.Window.baseZIndex + (Control.Window.windows.length - 1);
    }
});
Object.Event.extend(Control.Window);

//this is the observer for both Resizables and Draggables
Control.Window.LayoutUpdateObserver = Class.create({
    initialize: function(w,observer){
        this.w = w;
        this.element = $(w.container);
        this.observer = observer;
    },
    onStart: Prototype.emptyFunction,
    onEnd: function(event_name,instance){
        if(instance.element == this.element && this.iFrameShim)
            this.w.updateIFrameShimZIndex();
    },
    onResize: function(event_name,instance){
        if(instance.element == this.element)
            this.observer(this.element);
    },
    onDrag: function(event_name,instance){
        if(instance.element == this.element)
            this.observer(this.element);
    }
});

//overlay for Control.Modal
Control.Overlay = {
    id: 'control_overlay',
    loaded: false,
    container: false,
    lastOpacity: 0,
    styles: {
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: 9998
    },
    ieStyles: {
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 9998
    },
    effects: {
        fade: false,
        appear: false
    },
    load: function(){
        if(Control.Overlay.loaded)
            return false;
        Control.Overlay.loaded = true;
        Control.Overlay.container = new Element('div',{
            id: Control.Overlay.id
        });
        $(document.body).insert(Control.Overlay.container);
        if(Prototype.Browser.IE){
            Control.Overlay.container.setStyle(Control.Overlay.ieStyles);
            Event.observe(window,'scroll',Control.Overlay.positionOverlay);
            Event.observe(window,'resize',Control.Overlay.positionOverlay);
            Control.Overlay.observe('beforeShow',Control.Overlay.positionOverlay);
        }else
            Control.Overlay.container.setStyle(Control.Overlay.styles);
        Control.Overlay.iFrameShim = new IframeShim();
        Control.Overlay.iFrameShim.hide();
        Event.observe(window,'resize',Control.Overlay.positionIFrameShim);
        Control.Overlay.container.hide();
        return true;
    },
    unload: function(){
        if(!Control.Overlay.loaded)
            return false;
        Event.stopObserving(window,'resize',Control.Overlay.positionOverlay);
        Control.Overlay.stopObserving('beforeShow',Control.Overlay.positionOverlay);
        Event.stopObserving(window,'resize',Control.Overlay.positionIFrameShim);
        Control.Overlay.iFrameShim.destroy();
        Control.Overlay.container.remove();
        Control.Overlay.loaded = false;
        return true;
    },
    show: function(opacity,fade){
        if(Control.Overlay.notify('beforeShow') === false)
            return false;
        Control.Overlay.lastOpacity = opacity;
        Control.Overlay.positionIFrameShim();
        Control.Overlay.iFrameShim.show();
        if(fade){
            if(typeof(Effect) == "undefined")
                throw "Control.Window requires effects.js to be loaded."
            if(Control.Overlay.effects.fade)
                Control.Overlay.effects.fade.cancel();
            Control.Overlay.effects.appear = new Effect.Appear(Control.Overlay.container,{
                queue: {
                    position: 'end',
                    scope: 'Control.Overlay'
                },
                afterFinish: function(){
                    Control.Overlay.notify('afterShow');
                },
                from: 0,
                to: Control.Overlay.lastOpacity,
                duration: (fade === true ? 0.75 : fade) / 2
            });
        }else{
            Control.Overlay.container.setStyle({
                opacity: opacity || 1
            });
            Control.Overlay.container.show();
            Control.Overlay.notify('afterShow');
        }
        return true;
    },
    hide: function(fade){
        if(Control.Overlay.notify('beforeHide') === false)
            return false;
        if(Control.Overlay.effects.appear)
            Control.Overlay.effects.appear.cancel();
        Control.Overlay.iFrameShim.hide();
        if(fade){
            Control.Overlay.effects.fade = new Effect.Fade(Control.Overlay.container,{
                queue: {
                    position: 'front',
                    scope: 'Control.Overlay'
                },
                afterFinish: function(){
                    Control.Overlay.notify('afterHide');
                },
                from: Control.Overlay.lastOpacity,
                to: 0,
                duration: (fade === true ? 0.75 : fade) / 2
            });
        }else{
            Control.Overlay.container.hide();
            Control.Overlay.notify('afterHide');
        }
        return true;
    },
    positionIFrameShim: function(){
        if(Control.Overlay.container.visible())
            Control.Overlay.iFrameShim.positionUnder(Control.Overlay.container);
    },
    //IE only
    positionOverlay: function(){
        Control.Overlay.container.setStyle({
            width: document.body.clientWidth + 'px',
            height: document.body.clientHeight + 'px'
        });
    }
};
Object.Event.extend(Control.Overlay);

Control.ToolTip = Class.create(Control.Window,{
    initialize: function($super,container,tooltip,options){
        $super(tooltip,Object.extend(Object.extend(Object.clone(Control.ToolTip.defaultOptions),options || {}),{
            position: 'mouse',
            hover: container
        }));
    }
});
Object.extend(Control.ToolTip,{
    defaultOptions: {
        offsetLeft: 10
    }
});

Control.Modal = Class.create(Control.Window,{
    initialize: function($super,container,options){
        Control.Modal.InstanceMethods.beforeInitialize.bind(this)();
        $super(container,Object.extend(Object.clone(Control.Modal.defaultOptions),options || {}));
    }
});
Object.extend(Control.Modal,{
    defaultOptions: {
        overlayOpacity: 0.5,
        closeOnClick: 'overlay'
    },
    current: false,
    open: function(container,options){
        var modal = new Control.Modal(container,options);
        modal.open();
        return modal;
    },
    close: function(){
        if(Control.Modal.current)
            Control.Modal.current.close();
    },
    InstanceMethods: {
        beforeInitialize: function(){
            Control.Overlay.load();
            this.overlayFinishedOpening = false;
            this.observe('beforeOpen',Control.Modal.Observers.beforeOpen.bind(this));
            this.observe('afterOpen',Control.Modal.Observers.afterOpen.bind(this));
            this.observe('afterClose',Control.Modal.Observers.afterClose.bind(this));
        }
    },
    Observers: {
        beforeOpen: function(){
            if(!this.overlayFinishedOpening){
                Control.Overlay.observeOnce('afterShow',function(){
                    this.overlayFinishedOpening = true;
                    this.open();
                }.bind(this));
                Control.Overlay.show(this.options.overlayOpacity,this.options.fade ? this.options.fadeDuration : false);
                throw $break;
            }else
            Control.Window.windows.without(this).invoke('close');
        },
        afterOpen: function(){
            Control.Modal.current = this;
        },
        afterClose: function(){
            Control.Overlay.hide(this.options.fade ? this.options.fadeDuration : false);
            Control.Modal.current = false;
            this.overlayFinishedOpening = false;
        }
    }
});

Control.LightBox = Class.create(Control.Window,{
    initialize: function($super,container,options){
        this.allImagesLoaded = false;
        if(options.modal){
            var options = Object.extend(Object.clone(Control.LightBox.defaultOptions),options || {});
            options = Object.extend(Object.clone(Control.Modal.defaultOptions),options);
            options = Control.Modal.InstanceMethods.beforeInitialize.bind(this)(options);
            $super(container,options);
        }else
            $super(container,Object.extend(Object.clone(Control.LightBox.defaultOptions),options || {}));
        this.hasRemoteContent = this.href && !this.options.iframe;
        if(this.hasRemoteContent)
            this.observe('onRemoteContentLoaded',Control.LightBox.Observers.onRemoteContentLoaded.bind(this));
        else
            this.applyImageObservers();
        this.observe('beforeOpen',Control.LightBox.Observers.beforeOpen.bind(this));
    },
    applyImageObservers:function(){
        var images = this.getImages();
        this.numberImagesToLoad = images.length;
        this.numberofImagesLoaded = 0;
        images.each(function(image){
            image.observe('load',function(image){
                ++this.numberofImagesLoaded;
                if(this.numberImagesToLoad == this.numberofImagesLoaded){
                    this.allImagesLoaded = true;
                    this.onAllImagesLoaded();
                }
            }.bind(this,image));
            image.hide();
        }.bind(this));
    },
    onAllImagesLoaded: function(){
        this.getImages().each(function(image){
            this.showImage(image);
        }.bind(this));
        if(this.hasRemoteContent){
            if(this.options.indicator)
                this.hideIndicator();
            this.finishOpen();
        }else
            this.open();
    },
    getImages: function(){
        return this.container.select(Control.LightBox.imageSelector);
    },
    showImage: function(image){
        image.show();
    }
});
Object.extend(Control.LightBox,{
    imageSelector: 'img',
    defaultOptions: {},
    Observers: {
        beforeOpen: function(){
            if(!this.hasRemoteContent && !this.allImagesLoaded)
                throw $break;
        },
        onRemoteContentLoaded: function(){
            this.applyImageObservers();
            if(!this.allImagesLoaded)
                throw $break;
        }
    }
});


var TWIXController = Class.create();
TWIXController.prototype = {
	
	initialize : function(uname, gc, lang, guid, game_name, gameurl, swfversion, commonversion, player_advert_img, player_advert_time_cash, player_advert_time_training) 
	{
		try{
			this.version		 = 		commonversion;
			this.flashObject	 = 		null;
			this.delayId		 =		null;
			this.gamelist		 = 		null;
			this.userlist		 =		null;
			this.user			 = 		null;
			this.showGameTypes	 =		0;
			this.maxGameType	 =		0;
			this.gttParticipants =		[];
			this.isSinglePlayer	 =		false;
			this.hasScoring		 =		false;
			this.isGuest	 	 =		true;
			this.guestName		 =		'';
			this.guestIconM		 =		'';
			this.guestDelay		 =		null;
			this.guestDelayTime	 =		180;
			this.defaultIconS	 =		'';
			this.defaultIconM	 =		'';
			this.pubMsgCount	 =		0;
			this.windowCount	 =		0;
			this.openModals		 = 		[];
			this.firstLobbyCall	 =		true;
			this.playLock		 = 		false;
			this.game_name       =      game_name;
			this.buttonAbort	 =		null;
			this.buttonClicked	 =		null;
			this.isTrainingMP	 =		false;
			this.showPaymentDlg	 =		true;
			this.loadComplete	 =		false;
			this.loadBuffer		 =		null;
			this.isFF			 =		false;
			this.minFlashVersion =      '10.0.0';
			this.modalOpacity	 =		0.30;
			this.isConnected	 = 		false;
			this.scrollCH		 =		true;
			this.maxMsgLength	 =		100;
			this.isCashGame      =      false;
			this.player_advert_time_cash = player_advert_time_cash;
			this.player_advert_time_training = player_advert_time_training;
			this.COMMANDS		 =		[	{
				key: 'PUBLIC_MESSAGE',
				i: 0,
				f:this.onPublicMessage.bind(this)
			},
{
				key: 'LOBBY_DATA',
				i: 1,
				f:this.onLobbyData.bind(this)
			},
{
				key: 'EURO_UPDATE',
				i: 2,
				f:this.onEuroUpdate.bind(this)
			},
{
				key: 'PARTICIPANT_UPDATE',
				i: 3,
				f:this.onParticipantUpdate.bind(this)
			},
{
				key: 'WIN_MSG',
				i: 4,
				f:this.onWinMessage.bind(this)
			},
{
				key: 'USER_LEAVE_ROOM',
				i: 5,
				f:this.onUserLeaveRoom.bind(this)
			},
{
				key: 'USER_ENTER_ROOM',
				i: 6,
				f:this.onUserEnterRoom.bind(this)
			},
{
				key: 'PLAY_CLICK',
				i: 7
			},

			{
				key: 'JOIN_GAME_ERROR',
				i: 8,
				f:this.onJoinGameError.bind(this)
			},
{
				key: 'REQUEST_TICKET',
				i: 9,
				f:this.onRequestTicket.bind(this)
			},
{
				key: 'RELEASE_TICKET',
				i: 10
			},

			{
				key: 'BOOK_TICKET',
				i: 11
			},

			{
				key: 'START_GAME',
				i: 12,
				f:this.onStartGame.bind(this)
			},
{
				key: 'SHOW_MATCHING_DATA',
				i: 13,
				f:this.onShowMatchingData.bind(this)
			},
{
				key: 'REQUEST_LOBBY',
				i: 14
			},

			{
				key: 'USERVAR_UPDATE',
				i: 15,
				f:this.onUserVarUpdate.bind(this)
			},
{
				key: 'PRIVATE_MESSAGE',
				i: 16,
				f:this.onPrivateMessage.bind(this)
			},
{
				key: 'CONNECTION_FAILURE',
				i: 17,
				f:this.onConnectionFailure.bind(this)
			},
{
				key: 'CHAT_HISTORY',
				i: 18,
				f:this.onChatHistory.bind(this)
			},
{
				key: 'ADMIN_MESSAGE',
				i: 19,
				f:this.onAdminMessage.bind(this)
			},
{
				key: 'BLUEBOX',
				i: 20,
				f:this.onBlueBoxWarning.bind(this)
			},
{
				key: 'CONFIRM_ABORT',
				i: 21,
				f:this.onConfirmAbort.bind(this)
			},
{
				key: 'BUDDY_ACTION',
				i: 22,
				f:this.onBuddyAction.bind(this)
			},
{
				key: 'CHAT_ON_OFF',
				i: 23,
				f:this.onChatOnOff.bind(this)
			},
{
				key: 'SOUND_STATE',
				i: 24,
				f:this.onSoundState.bind(this)
			},
{
				key: 'LOAD_COMPLETE',
				i: 25,
				f: this.onLoadComplete.bind(this)
			},
{
				key: 'SHOW_TRANSACTION',
				i: 26,
				f: this.onShowTransaction.bind(this)
			},
{
				key: 'REQUEST_GAME',
				i: 27,
				f: this.onRequestGame.bind(this)
			},
{
				key: 'RELEASE_GAME',
				i: 28,
				f:this.onReleaseGame.bind(this)
			},
{
				key: 'JACKPOT_UPDATE',
				i: 29,
				f:this.onJackpotUpdate.bind(this)
				},

				{
				key: 'JACKPOT_INFO_CLICK',
				i: 30
			}];
			this.chatContLeft	= 		new Template(
				'<div class="user">' +
				'<div class="usericons"><img src="#{avatarUrl}"></div>' +
				'<div class="display">' +
				'<div class="top"><img src="/images/lobby/chat/bubble_top.gif"/></div>' +
				'<div class="left"><img src="/images/lobby/chat/bubble_left_with.gif"/></div>' +
				'<div class="text_right"><strong><span>#{time} #{name}:</span></strong> <br /> #{message}</div>' +
				'<div class="right"></div>' +
				'<div class="footer"><img src="/images/lobby/chat/bubble_footer.gif"/></div>' +
				'</div>' +
				'#{left}' +
				'</div>');
			this.chatContRight	= 		new Template(
				'<div class="user">' +
				'<div class="display">' +
				'<div class="top"><img src="/images/lobby/chat/bubble_top.gif"/></div>' +
				'<div class="left"></div>' +
				'<div class="text_left"><strong><span>#{time} #{name}:</span></strong> <br /> #{message}</div>' +
				'<div class="right"><img src="/images/lobby/chat/bubble_right_with.gif"/></div>' +
				'<div class="footer"><img src="/images/lobby/chat/bubble_footer.gif"/></div>' +
				'</div>' +
				'<div class="usericons"><img src="#{avatarUrl}"></div>' +
				'</div>');
			this.userCont		=		new Template(
				'<div class="user">' +
				'<span class="userimg"><img title="#{profilStr}" alt="#{profilStr}" src="#{avatar}"></span>' +
				'<div class="username"><strong>#{name}</strong>&nbsp;</div>' +
				'<div class="userforce"><img  title="" alt="" src="/images/lobby/stars#{skill}.png"> </div>' +
				'<div class="usericon"></div>' +
				'<div class="userlink"><a  href="/">#{detailStr}</a></div>' +
				'</div>'
				);
			this.infoPopup		=		new Template(
				'<div style="width:530px; height: 300px; text-align:left;" id="layer">' +
				'<div><img src="/images/layer/header.png" alt="" /></div>' +
				'<div class="main clearfix">' +
				'<div class="clearfix">' +
				'<div class="headline">#{headline}</div>' +
				'<div class="x"><a href="/"></a></div>' +
				'</div>' +
				'<div class="line"></div>' +
				'<div class="infos">#{infos}</div>' +
				'<div class="text">#{text}</div>' +
				'<div class="button2 clearfix">' +
				'<div class="buttonL button_big_grey"><a href="" id="btncancel"><span>#{cancel}</span></a></div>' +
				'<div class="buttonR button_big_green"><a href="" id="btnnext"><span>#{next}</span></a></div>' +
				'</div>' +
				'</div>' +
				'<div><img src="/images/layer/footer.png"  alt="" /></div>' +
				'</div>');
			this.infoOncePopup	=		new Template(
				'<div style="width:530px; height: 300px; text-align:left;" id="layer">' +
				'<div><img src="/images/layer/header.png" alt="" /></div>' +
				'<div class="main clearfix">' +
				'<div class="clearfix">' +
				'<div class="headline">#{headline}</div>' +
				'<div class="x"><a href="/"></a></div>' +
				'</div>' +
				'<div class="line"></div>' +
				'<div class="infos">#{infos}</div>' +
				'<div class="text">#{text}</div>' +
				'<div class="text show_once"><input type="checkbox" id="rt_show_once_id"><label style="display:inline;" for="rt_show_once_id">&nbsp;&nbsp;#{showOnce}</label></div>' +
				'<div class="button2 clearfix">' +
				'<div class="buttonL button_big_grey"><a href="" id="btncancel"><span>#{cancel}</span></a></div>' +
				'<div class="buttonR button_big_green"><a href="" id="btnnext"><span>#{next}</span></a></div>' +
				'</div>' +
				'</div>' +
				'<div><img src="/images/layer/footer.png"  alt="" /></div>' +
				'</div>');
			this.jackpotInfoPopup		=	new Template(
				'<div id="layer" style="width: 530px;  text-align:left;">' +
				'<div><img alt="" src="/images/layer/header.png"></div>' +
				'<div class="main clearfix">' +
				'<div class="clearfix">' +
				'<div class="headline">#{headline}</div>' +
				'<div class="x"><a href="/"></a></div>' +
				'</div>' +
				'<div class="line"></div>' +
				'<div class="infos">#{text}</div>' +
				'<div class="buttonC clearfix">' +
				'<div class="button_big_grey"><a href="" id="btncancel"><span>#{cancel}</span></a></div>' +
				'</div>' +
				'</div>' +
				'<div><img alt="" src="/images/layer/footer.png"></div>' +
				'</div>');
			this.warnPopup		=	new Template(
				'<div id="layer" style="width: 530px;  text-align:left;">' +
				'<div><img alt="" src="/images/layer/header.png"></div>' +
				'<div class="main clearfix">' +
				'<div class="clearfix">' +
				'<div class="headline_red">#{headline}</div>' +
				'<div class="x"><a href="/"></a></div>' +
				'</div>' +
				'<div class="line_red"></div>' +
				'<div class="infos">#{text}</div>' +
				'<div class="buttonC clearfix">' +
				'<div class="button_big_grey"><a href="" id="btnnext"><span>#{popupClose}</span></a></div>' +
				'</div>' +
				'</div>' +
				'<div><img alt="" src="/images/layer/footer.png"></div>' +
				'</div>');
			this.progressPopup	= 	new Template(
				'<div id="layer" style="width: 530px; text-align:left;">' +
				'<div><img alt="" src="/images/layer/header.png"></div>' +
				'<div class="main clearfix">' +
				'<div class="clearfix">' +
				'<div class="headline_c"><span>#{headline}</span></div>' +
				'</div>' +
				'<div class="line"></div>' +
				'<div class="text_c">#{text}</div>' +
				'<div class="infos">' +
				'<img alt="" src="/images/layer/timeline.gif">' +
				'</div>' +
				'</div>' +
				'<div><img alt="" src="/images/layer/footer.png"></div>' +
				'</div>');
			this.chatPopup		=	new Template(
				'<div style="width:203px; height: 300px; text-align:left;" id="layer" >' +
				'<div class="chat">' +
				'<div class="chat_header"><a href="/"></a></div>' +
				'<div class="dialoguser">' +
				'<div class="info">' +
				'<span class="userimg">' +
				'<img title="#{profile}" alt="#{profile}" src="#{avatarRecipiant}">' +
				'</span>' +
				'<strong>#{privateChatWith}<br />#{recipiant}</strong>' +
				'</div>' +
				'</div>' +
				'<div class="chat_areas">' +
				'</div>' +
				'<div class="chat_input">' +
				'<div class="display">' +
				'<textarea name="1" rows="3" class="input">#{chatInput}</textarea>' +
				'<span class="chat_left_characters">#{remainingChar}</span>' +
				'</div>' +
				'<div class="usericons"><img src="#{avatar}"></div>' +
				'<div class="button_s_green_chat"><a href=""><span>#{send}</span></a></div>' +
				'</div>' +
				'<div class="chat_footer"></div>' +
				'</div>' +
				'</div>');
			this.winMsg			= new Template(
				'<span class="userimg"><img title="#{profile}" alt="#{profile}" src="#{avatarUrl}"></span>' +
				'<a href="/profile/view/#{name}">#{name}</a> #{winMessage}');
			this.glentry		= new Template(
				'<div class="lobby_table_stake w_56 dotted_border_right">#{bet} &euro;</div>' +
				'<div class="lobby_table_price w_83 dotted_border_right">#{win} &euro;</div>' +
				'<div class="lobby_table_user w_63 dotted_border_right">#{maxPlayer}</div>' +
				'<div class="lobby_table_force w_72 dotted_border_right"><img  title="" alt="" src="/images/lobby/stars#{skill}.png"/></div>' +
				'<div class="lobby_table_id w_41 dotted_border_right">#{vid}</div>' +
				'<div class="lobby_table_button w_104"><div class="button_green_95x25_play"><a href="">#{buttonPlay}</a></div></div>' +
				'<div class="lobby_table_wait w_104">#{waitPlayer}<br/><a href="">#{buttonAbort}</a></div>');
			this.gljpentry		= new Template(
				'<div class="lobby_table_stake w_56 dotted_border_right">#{bet} &euro;</div>' +
				'<div class="lobby_table_price w_83 dotted_border_right">#{jp_win}</div>' +
				'<div class="lobby_table_user w_63 dotted_border_right">#{maxPlayer}</div>' +
				'<div class="lobby_table_force w_72 dotted_border_right"><img  title="" alt="" src="/images/lobby/stars#{skill}.png"/></div>' +
				'<div class="lobby_table_id w_41 dotted_border_right">#{vid}</div>' +
				'<div class="lobby_table_button w_104"><div class="button_green_95x25_play"><a href="">#{buttonPlay}</a></div></div>' +
				'<div class="lobby_table_wait w_104">#{waitPlayer}<br/><a href="">#{buttonAbort}</a></div>');
			this.matchingRow	= new Template(
				'<div class="#{className}">#{rank}</div>' +
				'<div class="table_portrait#{height}">' +
				'<img src="#{avatarUrl}" width="44" height="44" alt="#{strPlayername}" border="0"/>' +
				'</div>' +
				'<div class="table_information#{height} w_220">' +
				'<div class="row"><span class="font_15"><strong>#{name}</strong></span>  ' +
				'#{genderUrl}</div>' +
				'<div class="row">#{nrOfPlayedGames}</div>' +
				'<div class="row">' +
				'#{strSkill} <img src="/images/lobby/stars#{skill}.png" class="table_stars" width="53" height="17" alt="#{strSkill}#{skill}" boder="0"/>' +
				'</div>' +
				'</div>' +
				'<div class="table_score#{height}_#{kind}">' +
				'<strong>#{points}</strong><br/>' +
				'<span class="font_15">#{winAmount}</span>' +
				'</div>');
			if (Prototype.Browser.IE) {
				if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
					Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);
				}
			}
			if(navigator.userAgent.indexOf('Firefox') != -1) this.isFF = true;

			//		var sC = '{ "content": "lib/game_loader_view.jpg", "tint": 6974058, "fade": 500, "hold": 1000 }';
			var sC = '{ "content": "' + player_advert_img + '", "tint": 6974058, "fade": 500' +
			', "hold": ' + player_advert_time_training*1000 + ', "holdC": ' + player_advert_time_cash*1000 + 
			' }';
		
			var flashvars 		= {
				uname: uname,
				gc: gc,
				lang: lang,
				guid: guid,
				v: swfversion,
				cv: commonversion,
				startContent: escape(sC)
			};

			var params 			= {
				allowScriptAccess: "always",
				base: gameurl
			};
			if(Prototype.I)
				swfobject.switchOffAutoHideShow();
			swfobject.embedSWF(gameurl + '?v=' + swfversion, "gamecontainer", "768", "576", this.minFlashVersion, null, flashvars, params, null, this.onFlashLoaded.bind(this));
	
			document.observe('dom:loaded', this.onLoad.bind(this));
		
		}
		catch(e)
		{
			alert(e.name + ' : ' + e.message);			
		}
	},
    
	toString : function()
	{
		return 'TWIXController.instance (Ver: ' + this.version + ')';
	},
    
	onLoad : function(evt)
	{
		document.stopObserving('dom:loaded', this.onLoad);
		
		this.initTab('lobbyContainerTab');
		this.initTab('lobbySidebarTab');
		
		this.initSFX();
		
		$$('div.user_reload')[0].observe('click', (function(evt) {
			evt.stop();
			this.handleTabClick('players');
		}).bind(this));
		$('jackpot_tournament_info').observe('click', (function(evt){
			this.handleJackpotInfoClick(evt);
		}).bind(this));
	},
    
	onFlashLoaded : function(evt)
	{
		var lang = $('__lang');
		if(evt.success == false)
		{
			// no flash
			var playerVersion = swfobject.getFlashPlayerVersion();
			var fv = playerVersion.major + "." + playerVersion.minor + "." + playerVersion.release;
			var o = {
				headline: lang.down('#importantMsg').innerHTML,
				text: lang.down('#wrongFlashPlayerVersion').innerHTML.gsub('#{fpVersion}', fv).gsub('#{fpMinVersion}', this.minFlashVersion),
				popupClose: lang.down('#popupClose').innerHTML
			}
			var cancel = (function(e) {
				e.stop();
			});
			this.showModal(o, 'warn', cancel , cancel);
			return;
		}
		this.flashObject = $(evt.ref.id);
		this.delayId = (function() {
			this.showModal({
				headline: lang.down('#connectionProgress').innerHTML,
				text: lang.down('#connectionPatience').innerHTML
				}, 'progress');
		}).bind(this).delay(12);
			
		if(this.isFF)	this.flashObject.setStyle( {
			visibility: 'hidden'
		});
		
	},
	
	onLoadComplete : function()
	{
		this.loadComplete = true;
		// copy the legend underneath the advertisement area
		$('advertcontainer').up(1).insert('<div id="game_details">' + $('gamecontainer').up().next().innerHTML + '</div');

		if(this.loadBuffer != null)
		{
			var lang = $('__lang');
			this.removeModal();
			if(this.loadBuffer[1] != null)
			{
				this.showModal({
					headline: lang.down('#startingGame').innerHTML,
					text: lang.down('#paymentProgress').innerHTML
					}, 'progress');
			}
			this.sendMessage(this.loadBuffer[0]);
			this.loadBuffer = null;
		}
	},
    
	handleMessage : function(params)
	{
		var json = $H(params.evalJSON());
		var token = json.get('cmd');
		if(token == undefined) 
			this.log('TC.handleMessage: cmd token not found.');
		else 
		{
			var cmd = this.getCmd(token);
			
			try
			{
				cmd.f(json);
			}
			catch(e)
			{
				alert(e.name + ' : ' + e.message);			
			}
		}
	},
	
	handleReloadCheck : function()
	{		
		// set page reload check
		// will be called from flash 
		var ref = $('__ref');
		if(ref.value == "0") ref.value = "1";
		else {
			ref.value = "0";
			location.reload();
		}
	},
	
	sendMessage : function(params)
	{
		var result = this.flashObject.handleMessage(params);
		
		if(result != '0')
		{
			this.log('TC.sendMessage: error. ' + result);
		}
	},
	
	onLobbyData : function(json)
	{
		if (this.delayId != null) {
			window.clearTimeout(this.delayId);
			this.delayId = null;
		}
		if(Control.Modal.current != false)
		{
			if(Control.Modal.current.container.retrieve('type') == 'progress')
			{
				this.removeModal();				
			}
		}
		$('lobbycontent').setStyle({
			left: '-20px'
		});

		this.playLock		= false;
		this.gamelist		= json.get('gamelist');
		var _gl				= this.gamelist.sort( function(a, b){
			if(a.skill == b.skill)
			{
				if(a.bet == b.bet)
				{
					return a.maxPlayer == b.maxPlayer ? 0 : (a.maxPlayer < b.maxPlayer ? -1 : 1);
				}
				else
					return (a.bet < b.bet ? -1 : 1);
			}
			else
				return (a.skill < b.skill ? -1 : 1);
		});
		this.gamelist		= _gl;
		var c = 1;
		this.gamelist.each( function (ge)
		{
			ge.vid = c;
			c++;
		});
		
		this.user			= $H(json.get('user'));
		if (this.user.get('skill') != null) 
		{
			this.onEuroUpdate(this.user.get('euro'));
			this.isGuest = false;
			this.guestDelay = null;
		}
		else
		{
			this.user.set('skill', 1);
			this.guestDelay = (function() {
				window.location.href = '/account/new'
			}).bind(this).delay(this.guestDelayTime);
		}
		this.user.set('avatar', this.getSmallAvatar(this.user.get('avatar')));
		
		this.userlist		= json.get('userlist');
		this.orderUserList();
		this.userlist.each( (function(e) {
			e.avatar = this.getSmallAvatar(e.avatar);
		}).bind(this));
		
		this.initChatInput();
		this.pubMsgCount = 0;

		if (this.firstLobbyCall) {
			this.isConnected = true;
			this.firstLobbyCall = false 
			var ct = $$('li.tab_chat')[0];
			new Effect.Move(ct, {
				x: 0,
				y: -24,
				duration: 0.5
			});
			var pt = $$('li.tab_spieler')[0];
			new Effect.Move(pt, {
				x: 0,
				y: -24,
				duration: 0.5
			});
			//show sfx
			$$('div.lobby_header_button_ton')[0].setStyle({
				visibility: 'visible'
			});
			$$('div.lobby_header_button_ton')[1].setStyle({
				visibility: 'visible'
			});

			// set variables for game lobby
			var glVars = $('__glvars');
			this.isSinglePlayer = glVars.down('#single_player').innerHTML == 'true' ? true : false;
			this.hasScoring = glVars.down('#has_scoring').innerHTML == 'true' ? true : false;
			this.showGameTypes = parseInt(glVars.down('#show_game_types').innerHTML);
			this.maxGameType = parseInt(glVars.down('#max_game_type').innerHTML);
			this.gttParticipants = glVars.down('#gtt_participants').innerHTML.split('|');
			this.maxMsgLength = glVars.down('#max_chat_msg_length').innerHTML;
			this.guestName = glVars.down('#user_guest_name').innerHTML;
			this.guestIconM = glVars.down('#user_guest_icon').innerHTML;
			this.defaultIconS = glVars.down('#default_icon_small').innerHTML;
			this.defaultIconM = glVars.down('#default_icon_medium').innerHTML;
			this.player_advert_type = glVars.down('#player_advert_type').innerHTML;
		}
		this.updateUserCount(json.get('lobby'), json.get('limbo'));

		this.updateGameTables(false);
	},
	
	onParticipantUpdate : function(json)
	{
		var id = json.get('gameId');
		var entry = this.gamelist.find( function(e) {
			return e.id == id;
		} );
		entry.player = json.get('userCount');
		var tr = $('gtt' + id);
		if(tr != undefined)
		{
			tr.down('.lobby_table_user').update(entry.player + ' / ' + entry.maxPlayer);
		}
	},

	onJackpotUpdate : function(json)
	{
		var id = json.get('gameId');
		var entry = this.gamelist.find( function(e) {
			return e.id == id;
		} );
		entry.endTime = json.get('endTime');
		entry.jackpotAmount = json.get('jackpotAmount');
		var tr = $('gtt' + id);
		if(tr != undefined)
		{
			tr.down('.lobby_table_info').down('a').observe('click', (function(evt){
				this.handleJackpotTournamentClick(evt);
			}).bind(this));
			now = new Date();
			if(entry.endTime*1000 >= now.getTime())
			{
				tr.down('.lobby_table_user').update(formatTime(entry.endTime*1000));
			}
			else
			{
				duration = '<span class="lobby_table_time">'+$('duration_game_table_type_id_'+entry.id).innerHTML+'</span>'
				tr.down('.lobby_table_user').update(duration)
			}
			win = this.updateJackpotAmount(entry, true);
			tr.down('.lobby_table_price').update(win);
		}
	},

	onEuroUpdate : function(euro)
	{
		var currCurrency = $('__lang').down('#currentCurrency').innerHTML;
		if(typeof(euro) == 'object') euro = euro.get('amount');
		this.user.set('euro', euro);
		if ($('cents'))
		{
			var centSpan = $('cents').down();
			if(euro < 0)
			{
				if(!centSpan.hasClassName('red_font'))
					centSpan.addClassName('red_font');
				
				centSpan.update('- ' + this.currency(euro * -1 / 100) + currCurrency);
			}
			else
			{
				if(centSpan.hasClassName('red_font'))
					centSpan.removeClassName('red_font');
				
				centSpan.update('+ ' + this.currency(euro / 100) + currCurrency);
			}
		}
	},
	
	onUserVarUpdate : function (json)
	{
		try {
			json.each( function(e) {
				if (e.key != 'cmd') {
					if(e.key == 'nog')
					{
						this.user.set(e.key, e.value);
						var pos = e.value == 1 ? 0 : 1;
						$('nrofplayedgames').update($('__lang').down('#l_nrofplayedgames').innerHTML.split('|')[pos].gsub('#{nog}', e.value));
					}
					else if(e.key == 's')
					{
						this.user.set('skill', e.value);
						$("changeableskillimg").src = '/images/lobby/stars' + e.value + '.png';
						this.updateGameTables(true);
					}
				}
			}, this);
			var str = "";
			this.user.each( function(e) 
			{
				str += '\t' + e.key + ' : ' + e.value + ' \n ';
			});
		}
		catch(e)
		{
			alert(e.name + ' : ' + e.message);			
		}
	},
	
	onPublicMessage : function(json)
	{
		var chat = $('chat_areas');
		var l = chat.immediateDescendants().length;
		if(l > 20)
		{
			chat.firstDescendant().remove();
		}
		this.pubMsgCount++;
		var side =  (this.pubMsgCount % 2 == 0) ? this.chatContRight : this.chatContLeft;
		var scroll = ((chat.scrollTop == (chat.scrollHeight - 320)) || (chat.scrollHeight <= 320));
		json.set('avatarUrl', this.getSmallAvatar(json.get('avatarUrl')));
		chat.insert(side.evaluate(json));
		var user = this.userlist.find( function(u) {
			return u.name == json.get('name')
			});
		if((user != null) && (user.isModerator))
		{
			var modmsg = chat.childElements().last().down('div.usericons');
			modmsg.removeClassName('usericons');
			modmsg.addClassName('mod_usericon');
			chat.childElements().last().down('span').addClassName('moderator_name');
		}
		if(scroll) chat.scrollTop = chat.scrollHeight;
	},
	
	onChatHistory : function(json)
	{
		var chatentrys = json.get('chatentrys');
		chatentrys.each( (function(e) {
			e.message = e.message.gsub('&apos;','\'').gsub('&amp;','&');
			;
			this.onPublicMessage($H(e));
		}).bind(this));
		this.scrollCH = true;
	},
	
	onChatOnOff : function(json)
	{
		var setChatOn = json.get('setChatOn');
		var offText = json.get('offText');
		var chat = $('chat_areas');

		while (chat.immediateDescendants().length > 0)
		{
			chat.firstDescendant().remove();
		}
		if (setChatOn != 0)
		{
			$('chat_input_box').show();
		}
		else
		{
			chat.insert('<div class="text_left"><strong>' + offText + '</strong></div>');
			$('chat_input_box').hide();
		}
	},
	
	onBuddyAction : function(json)
	{
		
	},
	
	onSoundState : function(json)
	{
		var isMuted = json.get('isMuted');
		var img = $$('div.lobby_header_button_ton')[0].down('img');
		var imgMatch = $$('div.lobby_header_button_ton')[1].down('img');
		if(isMuted)
		{
			img.src = '/images/lobby/header/tonaus.png';
			imgMatch.src = '/images/lobby/header/tonaus.png';
		}
		else
		{
			img.src = '/images/lobby/header/tonan.png';
			imgMatch.src = '/images/lobby/header/tonan.png';
		}
	},
	
	onPrivateMessage : function(json)
	{
		var chatWindow = $('__chatBox' + this.getEscName(json.get('sender')));
		if (!Object.isElement(chatWindow)) 
		{
			this.openPrivateChat(json.get('sender'));
		}
		var chatWindow = $('__chatBox' + this.getEscName(json.get('sender')));
		var ci = chatWindow.down('textarea.input');
		var count = ci.retrieve('count');
		count = count + 1;
		ci.store('count', count);
		this.addPrivChatEntry(chatWindow.down('div.chat_areas'), count, json);
	},
	
	onUserEnterRoom : function(json)
	{
		var user = json;
		if (json.get != undefined) {			
			this.updateUserCount(json.get('lobby'), json.get('limbo'));
			user = json.get('user');
			if(user == undefined) return;
		}
		// update list		
		user.avatar = this.getSmallAvatar(user.avatar);
		this.userlist.push(user);
		this.orderUserList();
		
		this.updateUserOpacity();
		
		// find open chat
		this.addPrivateSysMsg(user.name, $('__lang').down('#chatUserEnterRoom').innerHTML);

		// find an open user profile
		if (Control.Modal.current) {
			var content = Control.Modal.current.container;
			if (content.retrieve('type') == 'profil') {
				if (content.down('#userprofile_name')) {
					if (content.down('#userprofile_name').down('h2').innerHTML == user.name) {
						content.down('div.button_s150_green').setStyle( {
							opacity: 1.0
						} );
					}
				}
			}
		}
	},
	
	onUserLeaveRoom : function(json)
	{
		// find open chat
		this.addPrivateSysMsg(json.get('name'), $('__lang').down('#chatUserLeftRoom').innerHTML);
		this.updateUserCount(json.get('lobby'), json.get('limbo'));
		this.userlist = this.userlist.findAll( function(u) {
			return (u.name != json.get('name'));
		});
		this.orderUserList();
		
		this.updateUserOpacity();
		
		// find an open user profile
		if (Control.Modal.current) {
			var content = Control.Modal.current.container;
			if (content.retrieve('type') == 'profil') {
				if (content.down('#userprofile_name')) {
					if (content.down('#userprofile_name').down('h2').innerHTML == json.get('name')) {
						content.down('div.button_s150_green').setStyle( {
							opacity: this.modalOpacity
						} );
					}
				}
			}
		}
	},
	
	onWinMessage : function(json)
	{
		var lang = $('__lang');
		var winMessage = lang.down('#moneyWinMessage').innerHTML.gsub('#{amount}', this.currency(json.get('amount') / 100));
		json.set('avatarUrl', this.getSmallAvatar(json.get('avatarUrl')));
		json.set('winMessage', winMessage);
		json.set('profile', lang.down('#profileString').innerHTML);
		var wmsg = this.winMsg.evaluate(json);
		var cont = new Element('div', {
			'class' : 'clear'
		});
		cont.setStyle({
			paddingBottom: '10px'
		});
		cont.update(wmsg);
		
		var windiv = $('winmessage');
		var lastmsg = windiv.firstDescendant();
		windiv.insert(cont);
		if(lastmsg)
		{
			new Effect.Move(lastmsg, {
				x: 0,
				y: -40,
				mode: 'relative',
				duration: 0.5,
				fps: 31
			} );
			new Effect.Move(cont, {
				x: 0,
				y: -40,
				mode: 'relative',
				duration: 0.5,
				fps: 31,
				afterFinish: function(e) {
					e.element.setStyle({
						position: 'static',
						top: 0
					});
					e.element.previous().remove()
					}
				});
	}
},
	
onAdminMessage : function (json)
{
	var lang = $('__lang');
	var o = {
		headline: lang.down('#importantMsg').innerHTML,
		popupClose: lang.down('#popupClose').innerHTML
	}
	o.text = json.get('message');
	var cancel = (function(e) {
		e.stop();
		this.removeModal();
		this.playLock = false;
	}).bind(this);
	this.showModal(o, 'warn', cancel , cancel);
},
	
onBlueBoxWarning : function (json)
{
	var lang = $('__lang');
	var o = {
		headline: lang.down('#importantMsg').innerHTML,
		text: lang.down('#connectionWarning').innerHTML,
		popupClose: lang.down('#popupClose').innerHTML
	};
	var cancel = (function(e){
		e.stop();
		this.removeModal();
		this.playLock = false;
	}).bind(this);
	this.showModal(o, 'warn', cancel, cancel);
},
	
onConfirmAbort : function(json)
{
	var lang = $('__lang');
	var o = {};
		
	o.headline = lang.down('#importantMsg').innerHTML;
	if(this.isSinglePlayer)
		o.text = lang.down('#confirmAbort').innerHTML.gsub('#{gameMode}', ((json.get('gameMode') == 'Match') ? lang.down('#match').innerHTML : lang.down('#turnier').innerHTML));
	else
		o.text = lang.down('#confirmAbortMP').innerHTML;
	o.cancel = lang.down('#noString').innerHTML;
	o.next = lang.down('#yesString').innerHTML;
	var cancel = (function(e){
		e.stop();
		this.removeModal();
		this.sendMessage(Object.toJSON({
			cmd: this.getCmd('CONFIRM_ABORT'),
			action: false
		}));
	}).bind(this);
	var next = (function(e){
		e.stop();
		this.removeModal();
		this.sendMessage(Object.toJSON({
			cmd: this.getCmd('CONFIRM_ABORT'),
			action: true
		}));
	}).bind(this);
	this.showModal(o, 'info', cancel , next);
},
	
onJoinGameError : function (json)
{
	var errorCode = json.get('error');
	this.playLock = false;
	this.isTrainingMP = false;
	var lang = $('__lang');
	var o = {
		headline: lang.down('#importantMsg').innerHTML
	}
	if(errorCode == 52)
	{
		o.text = lang.down('#repeatTournament').innerHTML;
	}
	else if(errorCode == 8)
	{
		o.text = lang.down('#notEnoughMoney').innerHTML;
	}
	else
	{
		o.text = lang.down('#joinError').innerHTML;
	}
	o.popupClose = lang.down('#popupClose').innerHTML;
	var cancel = (function(e) {
		e.stop();
		this.removeModal();
		this.playLock = false;
		if (this.buttonAbort != null)
		{
			this.buttonAbort.update(lang.down('#buttonPlay').innerHTML);
			this.showSkillSelector(this.buttonAbort, true);
			this.markRowToPlay(this.buttonAbort, false);
			this.buttonAbort = null;
		}
		if (this.buttonClicked != null)
		{
			this.buttonClicked.update(lang.down('#buttonPlay').innerHTML);
			this.markRowToPlay(this.buttonClicked, false);
			this.buttonClicked = null;
		}
	}).bind(this);
	this.showModal(o, 'warn', cancel , cancel);
},
	
onRequestTicket : function (json)
{
	var partState = json.get('partState');
	var gameId = json.get('gameId');

	var lang = $('__lang');
	var entry = this.gamelist.find( function(e) {
		return e.id == gameId;
	} );
	var o = Object.clone(entry);

	o.bet = this.currency(o.bet / 100)
	o.win = this.currency(o.win / 100)
	if(entry.mode == 4)
	{
		o.win = this.updateJackpotAmount(o);
		o.headline = lang.down('#doplayTurnier').innerHTML;
		var gei = new Template(lang.down('#gameDetails').innerHTML);
		o.maxPlayer = o.player;
		o.infos = gei.evaluate(o);
		o.text = lang.down('#confirmPayment').innerHTML.sub('#{euro}', o.bet);
		o.cancel = lang.down('#abortString').innerHTML;
		o.next = lang.down('#continueString').innerHTML;
	}
	else
	{
		o.headline = lang.down('#doplayTurnier').innerHTML;
		var gei = new Template(lang.down('#gameDetails').innerHTML);
		o.infos = gei.evaluate(o);
		o.text = lang.down('#confirmPayment').innerHTML.sub('#{euro}', o.bet);
		o.cancel = lang.down('#abortString').innerHTML;
		o.next = lang.down('#continueString').innerHTML;
	}
	var cancel = (function(e){
		e.stop();
		this.removeModal();
		this.sendMessage(Object.toJSON({
			cmd: this.getCmd('RELEASE_TICKET')
		}));
		this.playLock = false;
	}).bind(this);
	var next = (function(e){
		e.stop();
		this.removeModal();
		this.playLock = true;
		var so = Object.toJSON({
			cmd: this.getCmd('BOOK_TICKET')
		});
		if (this.loadComplete == false) {
			this.loadBuffer = [so, true];
			this.showModal({
				headline: lang.down('#loadingProgress').innerHTML,
				text: lang.down('#connectionPatience').innerHTML
				}, 'progress');
		}
		else {
			this.showModal({
				headline: lang.down('#startingGame').innerHTML,
				text: lang.down('#paymentProgress').innerHTML
				}, 'progress');
			this.sendMessage(so);
		}
	}).bind(this);
	this.showModal(o, 'info', cancel , next);
},

onRequestGame : function()
{
	this.playLock = false;
},

onShowTransaction : function(json)
{
	var lang = $('__lang');
	if (this.isTrainingMP)
		this.showModal({
			headline: lang.down('#startingGame').innerHTML,
			text: lang.down('#connectionPatience').innerHTML
			}, 'progress');
	else
		this.showModal({
			headline: lang.down('#startingGame').innerHTML,
			text: lang.down('#paymentProgress').innerHTML
			}, 'progress');
	this.isTrainingMP = false;
	if (this.buttonAbort != null)
	{
		this.buttonAbort.update(lang.down('#buttonPlay').innerHTML);
		this.showSkillSelector(this.buttonAbort, true);
		this.markRowToPlay(this.buttonAbort, false);
		this.buttonAbort = null;
	}
	if (this.buttonClicked != null)
	{
		this.buttonClicked.update(lang.down('#buttonPlay').innerHTML);
		this.markRowToPlay(this.buttonClicked, false);
		this.buttonClicked = null;
	}
	this.playLock = false;
},

onReleaseGame : function()
{
	this.isTrainingMP = false;
	this.buttonAbort = null;
	if (this.buttonClicked != null)
	{
		this.buttonAbort = this.buttonClicked;
		this.buttonClicked = null;
		this.functionPlayClick(this.buttonAbort);
	}
	else
	{
		this.playLock = false;
	}
},

onStartGame : function()
{
	this.removeAllWindows();

	if (this.player_advert_type == 'img') {
		$('lobbycontent').setStyle({
			left: '-812px'
		});
		this.flashObject.setStyle({
			visibility: 'visible'
		});
	} else {
		$('lobbycontent').setStyle({
			left: '-2423px'
		});
		this.flashObject.setStyle({
			visibility: 'hidden'
		});
	
		var a = (function() {
			$('lobbycontent').setStyle({
				left: '-812px'
			});
			this.flashObject.setStyle({
				visibility: 'visible'
			});
		}).bind(this).delay(this.isCashGame?parseInt(this.player_advert_time_cash)+1:parseInt(this.player_advert_time_training)+1);
	}

	Element.scrollTo($('content'));
},
	
onShowMatchingData : function(json)
{
	if(this.isFF)
		this.flashObject.setStyle( {
			visibility: 'hidden'
		});
			
	this.removeAllWindows();
	$('lobbycontent').setStyle({
		left: '-1632px'
	});

	if ($$('div.lobby_header_button_merken')[0].visible())
		$$('div.lobby_header_button_merken')[1].show();
	else
		$$('div.lobby_header_button_merken')[1].hide();

	// evaluate global data
	var lang = $('__lang');
	var mData = json.get('matchingData');
	var thisUser = parseInt(mData.thisUser);
	var gameNo = parseInt(mData.game_table_id);
	var remainPlayers = parseInt(mData.remainingPlayers);
	var stakeAmount = this.currency(parseInt(mData.amount) / 100);
	var players = mData.player.toArray();

	// result header
	var finished = true;
	var type = '';
	var msg = '';
	var arrSize = players.size();
	if (arrSize < players[thisUser].rank) {
		arrSize = players[thisUser].rank;
		var order = [arrSize];
		order[(players[thisUser].rank - 1)] = thisUser;
	}
	else
		var order = [arrSize];
	var winIdx = 0;
	for (var idx = 0; idx < players.size(); ++idx) {
		if (players[idx].rank == 1) winIdx = idx;
		order[(players[idx].rank - 1)] = idx;
	}
	var gt = parseInt(mData.gameType);
	if (gt ==1) {
		if (players[thisUser].rank == 1) {
			if (this.isSinglePlayer)
				msg = lang.down('#trainingWon').innerHTML.split('|');
			else
				msg = lang.down('#trainingWonMP').innerHTML.split('|');
		}
		else {
			msg = lang.down('#trainingLost').innerHTML.split('|');
			if (players[winIdx].isGuest)
				msg[0] = msg[0].gsub('#{name}', this.guestName);
			else
				msg[0] = msg[0].gsub('#{name}', players[winIdx].name);
		}
		type = lang.down('#training').innerHTML;
	}
	else if (gt == 2) {
		if (remainPlayers > 0)
			finished = false;
		if (players[thisUser].rank == 1) {
			if (finished)
				msg = lang.down('#matchWon').innerHTML.split('|');
			else {
				msg = lang.down('#matchNotFinished').innerHTML.split('|');
			}
		}
		else {
			msg = lang.down('#matchLost').innerHTML.split('|');
			if (players[winIdx].isGuest)
				msg[0] = msg[0].gsub('#{name}', this.guestName);
			else
				msg[0] = msg[0].gsub('#{name}', players[winIdx].name);
		}
		type = lang.down('#match').innerHTML;
	}
	else if (gt == 3) {
		if (remainPlayers > 0)
			finished = false;
		if (players[thisUser].rank == 1) {
			if (finished)
				msg = lang.down('#tournamentWon').innerHTML.split('|');
			else {
				msg = lang.down('#tournamentNotFinished').innerHTML.split('|');
				if (remainPlayers > 1)
					msg[1] = msg[1].gsub('#{count}', remainPlayers);
				else
					msg[1] = msg[2];
			}
		}
		else {
			if (this.isSinglePlayer)
				msg = lang.down('#tournamentLost').innerHTML.split('|');
			else {
				msg = lang.down('#trainingLost').innerHTML.split('|');
				msg[0] = msg[0].gsub('#{name}', players[winIdx].name);
			}
		}
		if (this.isSinglePlayer)
			type = lang.down('#turnier').innerHTML;
		else
			type = lang.down('#cashMP').innerHTML;
	}

	else if (gt == 4) {
		if (remainPlayers > 0)
			finished = false;
		if (players[thisUser].rank == 1) {
			if (finished)
				msg = lang.down('#tournamentWon').innerHTML.split('|');
			else {
				msg = lang.down('#jackpotNotFinished').innerHTML.split('|');
			}
		}
		else {
			if (this.isSinglePlayer)
				msg = lang.down('#tournamentLost').innerHTML.split('|');
			else {
				msg = lang.down('#trainingLost').innerHTML.split('|');
				msg[0] = msg[0].gsub('#{name}', players[winIdx].name);
			}
		}
		if (this.isSinglePlayer)
			type = lang.down('#turnier').innerHTML;
		else
			type = lang.down('#cashMP').innerHTML;
	}
		
	$('win_lost_msg').update('<strong>' + msg[0] + '</strong><br/>' + msg[1]);

	// headline of result table
	var stake = ' ';
	if (gt != 1)
		stake = lang.down('#strStake').innerHTML + ': ' + stakeAmount + ' &euro;';
	$('headline_info').update('<strong> ' + type + ' ' + stake + '</strong>');
	$('headline_game_no').update('<span class="font_13">' + lang.down('#gameNumber').innerHTML + gameNo + '</span>');

	// result table
	var o = {
		strPlayername : lang.down('#strPlayername').innerHTML,
		strSkill : lang.down('#strSkill').innerHTML
	};
	var showRow = false;
	var rowColor = '';
	var rowClass = '';
	$('rank_table').update('');
	for (var idx = 0; idx < arrSize; ++idx) {
		//			if ((gt < 3) || ((gt == 3) && (order[idx] == thisUser)))
		showRow = false;
		if (this.isSinglePlayer) {
			if ((gt < 3) || ((gt == 3 || gt == 4) && (order[idx] == thisUser))) {
				showRow = true;
			}
		}
		else {
			showRow = true;
		}
		if (showRow)
		{
			var user = players[order[idx]];
			var gender = ' ';
			if (user.isGuest) {
				o.name = this.guestName;
				o.avatarUrl = this.guestIconM;
			}
			else {
				o.name = user.name;
				if (user.avatar_url != undefined)
					o.avatarUrl = user.avatar_url;
				else
					o.avatarUrl = this.defaultIconM;
				if(user.gender == 1)
					gender = '/images/lobby/m.png';
				else if(user.gender == 2)
					gender = '/images/lobby/w.png';
			}
			if (gender.length > 1)
				o.genderUrl = '<img src="' + gender + '" width="15" height="15" alt=""/>';
			else
				o.genderUrl = gender;
			o.skill = String(user.skill);
			if (this.hasScoring)
				o.points = lang.down('#strPoints').innerHTML + ': ' + this.formatNumber(user.score);
			else {
				if(user.rank == 1)
					o.points = lang.down('#won').innerHTML;
				else
					o.points = lang.down('#lost').innerHTML;
			}
			var pos = user.totalGames == 1 ? 0 : 1;
			o.nrOfPlayedGames = lang.down('#l_nrofplayedgames').innerHTML.split('|')[pos].gsub('#{nog}', '<strong>' + this.formatNumber(user.totalGames)) + '</strong>';
			if (finished)
				o.rank = user.rank;
			else
				o.rank = '?';
			if ((user.rank == 1) && (finished)) {
				o.kind = 'win';
				o.winAmount = lang.down('#strWinning').innerHTML + ': ' + this.currency(parseInt(mData.winAmount) / 100) + ' ' + lang.down('#currencyShort').innerHTML;
			}
			else {
				if((finished != 1) && (user.rank == 1))
					o.kind = 'unsure';
				else
					o.kind = 'loose';
				if (gt < 3) {
					if ((gt == 2) && (arrSize == 1))
						o.winAmount = '&nbsp;';
					else
						o.winAmount = lang.down('#strWinning').innerHTML + ': ' + this.currency(0) + ' ' + lang.down('#currencyShort').innerHTML;
				}
				else
					o.winAmount = '&nbsp;';
			}
			rowColor = (idx % 2 == 0) ? 'sand' : 'light_sand';
			if (order[idx] == thisUser) {
				o.height = '100';
				o.className = 'table_placement_self h_100';
			}
			else {
				o.height = '100';
				o.className = 'table_placement' + o.height;
			}
			var row = new Element('div', {
				'class' : 'row ' + rowColor + ' h_' + o.height
			});
			row.insert(this.matchingRow.evaluate(o));
			$('rank_table').insert( {
				bottom: row
			});
		}
	}

	var a = $('matchingdata').down('a');
	a.stopObserving('click');
	a.store('done', false);
	a.observe('click', (function(e) {
		e.stop();
		var a = e.findElement('a');
		if(a.retrieve('done') == true) return;
		a.store('done', true);
		this.sendMessage( Object.toJSON( {
			cmd: this.getCmd('REQUEST_LOBBY')
		}) );
	}).bind(this));
	Element.scrollTo($('games'));
},
	
onConnectionFailure : function(json)
{
	var lang = $('__lang');
	var o = {
		headline: lang.down('#importantMsg').innerHTML,
		popupClose: lang.down('#continueString').innerHTML
	};
		
	if(this.isConnected == false)
		o.text = lang.down('#connectionFailed').innerHTML;
	else
		o.text = lang.down('#connectionLost').innerHTML;
	var cancel = (function(e) {
		e.stop();
		window.location.reload(true);
	});
	this.showModal(o, 'warn', cancel , cancel);
},
handleJackpotInfoClick: function (event)
{
	event.stop();
	var clickedBtn = event.findElement('a');
	this.functionJackpotInfoClick(clickedBtn);
},
functionJackpotInfoClick: function(clickedBtn)
{
	var lang = $('__lang');
	var cancel = (function(e){
		e.stop();
		this.removeModal();
		this.playLock = false;
	}).bind(this);
	this.showModal({
		headline: lang.down('#jackpotTournamentInfo').innerHTML,
		text: lang.down('#jackpotTournamentText').innerHTML,
		cancel: lang.down('#jackpotInfoClose').innerHTML
		}, 'jackpot_info', cancel);
},
handleJackpotTournamentClick: function (event)
{
	event.stop();
	if(this.playLock)
	{
		return;
	}
	var clickedBtn = event.findElement('a');
	this.functionJackpotTournamentClick(clickedBtn);
},
functionJackpotTournamentClick: function(clickedBtn)
{
	var lang = $('__lang');
	var gameId = clickedBtn.id.sub("gtt_link_","");
	var entry = this.gamelist.find( function(e) {
		return e.id == gameId
	} );
	var o = Object.clone(entry);

	o.bet = this.currency(o.bet / 100)
	o.win = this.currency(o.win / 100)
	if(entry.mode == 4)
	{
		var url = "/games/jackpot_info?game_table_id="+gameId;
		this.showModal({
			headline: lang.down('#loadingProgress').innerHTML,
			text: lang.down('#connectionPatience').innerHTML
			}, 'progress');
		var t = this;
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport){
				t.removeModal();
				o.headline = lang.down('#currentJackpotInfo').innerHTML;
				o.infos = transport.responseText;
				o.text = "";
				o.cancel = lang.down('#abortString').innerHTML;
				o.next = lang.down('#buttonPlay').innerHTML;
				var cancel = (function(e){
					e.stop();
					t.removeModal();
					this.playLock = false;
				}).bind(t);
				var next = (function(e){
					this.playLock = true;
					e.stop();
					t.removeModal();
					this.functionPlayClick($$('#gtt'+o.id+' .lobby_table_button a')[0]);
				}).bind(t);
				t.showModal(o, 'info', cancel , next);
			}
		});
		return;
	}
},
	
handlePlayClick: function (event)
{
	event.stop();
	if(this.playLock)
	{
		return;
	}
	var clickedBtn = event.findElement('a');
	if (!this.isSinglePlayer)
	{
		if (this.buttonAbort != null)
		{
			var gameId = this.buttonAbort.retrieve('gameId');
			this.buttonAbort.update($('__lang').down('#buttonPlay').innerHTML);
			this.showSkillSelector(this.buttonAbort, true);
			this.markRowToPlay(this.buttonAbort, false);
			if (gameId != clickedBtn.retrieve('gameId'))
			{
				this.buttonClicked = clickedBtn;
			}
			this.playLock = true;
			var so = Object.toJSON({
				cmd: this.getCmd('RELEASE_GAME'),
				gameId: gameId
			});
			this.sendMessage(so);
			return;
		}
		else
		{
			this.buttonAbort = clickedBtn;
			this.buttonClicked = null;
		}
	}
	this.functionPlayClick(clickedBtn);
},

functionPlayClick: function (clickedBtn)
{
	var lang = $('__lang');
	var entry = this.gamelist.find( function(e) {
		return e.id == clickedBtn.retrieve('gameId');
	} );
	var o = Object.clone(entry);
	o.bet = this.currency(o.bet / 100);
	o.win = this.currency(o.win / 100);
	var gei = new Template(lang.down('#gameDetails').innerHTML);
	try
	{
		if(this.isGuest == true && entry.bet > 0)
			throw {
				name: 'NeedRegistration',
				message: ' guest trys to play cash'
			}
		if(entry.skill < this.user.get('skill'))
			throw {
				name: 'Skillerror',
				message: 'selected game\'s skill to large'
			};
		if(entry.bet > 0 && this.user.get('memberLevel') == 'limited')
			throw {
				name: 'LimitedError',
				message: ' limited try s cash'
			};
		if(entry.bet > 0 && this.user.get('euro') == 0)
			throw {
				name: 'NoMoney',
				message: ' no money to play game'
			};
		if(entry.bet > 0 && this.user.get('euro') < entry.bet)
			throw {
				name: 'EuroError',
				message: ' not enought money to play game'
			};
			
		this.isCashGame = (entry.mode != 1);
		if (this.isSinglePlayer)
		{
			if (entry.mode == 2)
			{
				o.headline = lang.down('#doplayMatch').innerHTML;
				o.infos = gei.evaluate(o);
				o.text = lang.down('#confirmPayment').innerHTML.sub('#{euro}', o.bet);
				o.cancel = lang.down('#abortString').innerHTML;
				o.next = lang.down('#continueString').innerHTML;
				var cancel = (function(e){
					e.stop();
					this.removeModal();
					this.playLock = false;
				}).bind(this);
				var next = (function(e){
					e.stop();
					this.removeModal();
					this.playLock = true;
					var so = Object.toJSON({
						cmd: this.getCmd('PLAY_CLICK'),
						gameId: entry.id
					});
					if (this.loadComplete == false) {
						this.loadBuffer = [so, true];
						this.showModal({
							headline: lang.down('#loadingProgress').innerHTML,
							text: lang.down('#connectionPatience').innerHTML
							}, 'progress');
					}
					else {
						this.showModal({
							headline: lang.down('#startingGame').innerHTML,
							text: lang.down('#paymentProgress').innerHTML
							}, 'progress');
						this.sendMessage(so);
					}
				}).bind(this);
				this.showModal(o, 'info', cancel , next);
				return;
			}
			this.playLock = true;
			var so = Object.toJSON({
				cmd: this.getCmd('PLAY_CLICK'),
				gameId: entry.id
			});
			if (this.loadComplete == false) {
				this.loadBuffer = [so, null];
				this.showModal({
					headline: lang.down('#loadingProgress').innerHTML,
					text: lang.down('#connectionPatience').innerHTML
					}, 'progress');
			}
			else {
				this.sendMessage(so);
			}
			return;
		}
		else
		{
			// multi player game
			var waitForPlayer = lang.down('#waitForPlayer').innerHTML;
			if (entry.mode == 1)
			{
				this.playLock = true;
				this.isTrainingMP = true;
				var so = Object.toJSON({
					cmd: this.getCmd('PLAY_CLICK'),
					gameId: entry.id
				});
				this.buttonAbort.update(lang.down('#buttonAbort').innerHTML);
				this.markRowToPlay(this.buttonAbort, true);
				if (this.loadComplete == false) {
					this.loadBuffer = [so, null];
					this.showModal({
						headline: lang.down('#loadingProgress').innerHTML,
						text: lang.down('#connectionPatience').innerHTML
						}, 'progress');
				}
				else {
					this.sendMessage(so);
				}
			}

			else
			{
				if (this.showPaymentDlg)
				{
					// jackpot
					if (entry.mode == 4)
					{
						o.headline = lang.down('#doplayJackpot').innerHTML;
						o.infos = gei.evaluate(o);
						o.text = lang.down('#confirmPaymentMP').innerHTML.sub('#{euro}', o.bet);
						o.showOnce = lang.down('#rememberDecision').innerHTML;
						o.cancel = lang.down('#abortString').innerHTML;
						o.next = lang.down('#continueString').innerHTML;

					}
					else
					{
						o.headline = lang.down('#doplayMultiPlayer').innerHTML;
						o.infos = gei.evaluate(o);
						o.text = lang.down('#confirmPaymentMP').innerHTML.sub('#{euro}', o.bet);
						o.showOnce = lang.down('#rememberDecision').innerHTML;
						o.cancel = lang.down('#abortString').innerHTML;
						o.next = lang.down('#continueString').innerHTML;

					}
					var cancel = (function(e){
						e.stop();
						this.removeModal();
						this.playLock = false;
						this.showSkillSelector(this.buttonAbort, true);
						this.buttonAbort = null;
					}).bind(this);
					var next = (function(e){
						e.stop();
						var element = e.findElement('div.button_big_green');
						var showDlg = element.up('div.main').down('input').checked;
						if (showDlg)
							this.showPaymentDlg = false;
						else
							this.showPaymentDlg = true;
						this.removeModal();
						this.playLock = true;
						var so = Object.toJSON({
							cmd: this.getCmd('PLAY_CLICK'),
							gameId: entry.id
						});
						this.showSkillSelector(this.buttonAbort, false);
						this.buttonAbort.update(lang.down('#buttonAbort').innerHTML);
						this.markRowToPlay(this.buttonAbort, true);
						if (this.loadComplete == false) {
							this.loadBuffer = [so, null];
							this.showModal({
								headline: lang.down('#loadingProgress').innerHTML,
								text: lang.down('#connectionPatience').innerHTML
								}, 'progress');
						}
						else {
							this.sendMessage(so);
						}
					}).bind(this);
					this.showModal(o, 'info_once', cancel , next);
				}
				else
				{
					this.playLock = true;
					var so = Object.toJSON({
						cmd: this.getCmd('PLAY_CLICK'),
						gameId: entry.id
					});
					this.showSkillSelector(this.buttonAbort, false);
					this.buttonAbort.update(lang.down('#buttonAbort').innerHTML);
					this.markRowToPlay(this.buttonAbort, true);
					if (this.loadComplete == false) {
						this.loadBuffer = [so, null];
						this.showModal({
							headline: lang.down('#loadingProgress').innerHTML,
							text: lang.down('#connectionPatience').innerHTML
							}, 'progress');
					}
					else {
						this.sendMessage(so);
					}
				}
			}
		}
	}
	catch(e)
	{
		if(e.name == 'EuroError' || e.name == 'NoMoney')
		{
			if (entry.mode == 2)
				o.headline = lang.down('#doplayMatch').innerHTML;
			else if (entry.mode == 3 || entry.mode == 4) {
				if (this.isSinglePlayer)
					o.headline = lang.down('#doplayTurnier').innerHTML;
				else
					o.headline = lang.down('#doplayMultiPlayer').innerHTML;
			}
			if(entry.mode == 4)
			{
				o.win = this.updateJackpotAmount(o);
				o.maxPlayer = o.player;
			}
			o.infos = gei.evaluate(o);
			if(e.name == 'NoMoney') o.text = lang.down('#noMoney').innerHTML;
			else if(e.name == 'EuroError') o.text = lang.down('#notEnoughMoney').innerHTML;
			o.cancel = lang.down('#abortString').innerHTML;
			o.next = lang.down('#continueString').innerHTML;

			var cancel = (function(e){
				e.stop();
				this.removeModal();
				this.playLock = false;
				this.buttonAbort = null;
			}).bind(this);
			var next = (function(e){
				e.stop();
				window.location.href = '/payment_in/new';
			}).bind(this);
			this.showModal(o, 'info', cancel , next);
		}
		else if(e.name == 'NeedRegistration')
		{
			o = {};
				
			o.headline = lang.down('#importantMsg').innerHTML;
			o.text = lang.down('#registrationNote').innerHTML;
			o.cancel = lang.down('#abortString').innerHTML;
			o.next = lang.down('#continueString').innerHTML;
			var cancel = (function(e){
				e.stop();
				this.removeModal();
				this.playLock = false;
				this.buttonAbort = null;
			}).bind(this);
			var next = (function(e){
				e.stop();
				window.location.href = '/account/new';
			}).bind(this);
			this.showModal(o, 'info', cancel , next);
		}
		else if(e.name == 'LimitedError')
		{
			o = {};
				
			o.headline = lang.down('#importantMsg').innerHTML;
			o.text = lang.down('#limitedCash').innerHTML;
			o.cancel = lang.down('#abortString').innerHTML;
			o.next = lang.down('#continueString').innerHTML;
			var cancel = (function(e){
				e.stop();
				this.removeModal();
				this.playLock = false;
				this.buttonAbort = null;
			}).bind(this);
			var next = (function(e){
				e.stop();
				window.location.href = '/account/become_topgamer';
			}).bind(this);
			this.showModal(o, 'info', cancel , next);
		}
		else
			alert(e.name + ' : ' + e.message);
	}
},

handleAddBuddy : function(uid, type, add)
{
	var pbuddy = this.userlist.find( function(u) {
		return u.dbid == uid
		});
	if(Object.isUndefined(pbuddy) == false)
	{
		if (add) {
			pbuddy.buddy = (type == 1) ? 'Friend' : 'Enemy';
		} else {
			pbuddy.buddy ='Unknown';
		}
		this.handleTabClick('players') ;
	}
	var o = {
		cmd: this.getCmd('BUDDY_ACTION'),
		id: uid,
		type: type,
		add: (add == true ? 'true' : 'false')
		};
	this.sendMessage(Object.toJSON(o));
},
	
handleSendPubMessage : function(event)
{
	var cif = $('chat_input');
	var txt = cif.value;
	
	if((event.type == 'keydown') || (event.type == 'keyup'))
	{
		if (cif.value.length > this.maxMsgLength) {
			cif.value = cif.value.substring(0, this.maxMsgLength);
			cif.scrollTop = cif.scrollHeight;
		}
		else
			cif.next('span').update((this.maxMsgLength - txt.length) + ' ' + $('__lang').down('#remainingChar').innerHTML);
			
		if(!(event.keyCode == Event.KEY_RETURN && event.type == 'keydown'))
			return;
	}
	event.stop();
	if(this.user == null) return;
	cif.value = '';
	cif.next('span').update(this.maxMsgLength + ' ' + $('__lang').down('#remainingChar').innerHTML);
	if(this.isGuest == true)
	{
		this.showRegPopup('pubChat');
	}
	//else if(this.user.get('memberLevel') == 'limited')
	//{
	//this.showLimitedPopup();
	//}
	else if(txt.length > 0 && txt != $('__lang').down('#chatInput').innerHTML)
	{
		txt = txt.truncate(this.maxMsgLength,'');
		var o = {
			cmd: this.getCmd('PUBLIC_MESSAGE'),
			msg: txt.escapeHTML().gsub(/"/,'&quot;')
		};
		this.sendMessage(Object.toJSON(o));
	}
},
	
handleSendPrivatMessage : function(event)
{
	var cb = event.findElement('.chat');
	var ci = cb.down('textarea.input');
	var txt = ci.value;

	if((event.type == 'keydown') || (event.type == 'keyup'))
	{
		if (ci.value.length > this.maxMsgLength) {
			ci.value = ci.value.substring(0, this.maxMsgLength);
			ci.scrollTop = ci.scrollHeight;
		}
		else
			ci.next('span').update((this.maxMsgLength - txt.length) + ' ' + $('__lang').down('#remainingChar').innerHTML);
			
		if(!(event.keyCode == Event.KEY_RETURN && event.type == 'keydown'))
			return;
	}
	event.stop();
	var ca = cb.down('div.chat_areas');
		
	if(this.userlist.find( function(u) {
		return u.name == ci.retrieve('chatpartner')
		}) == null)

		{
		this.addPrivateSysMsg(ci.retrieve('chatpartner'), $('__lang').down('#chatUserHasGone').innerHTML);
		ci.value = '';
		return;
	}
		
	ci.value = '';
	ci.next('span').update(this.maxMsgLength + ' ' + $('__lang').down('#remainingChar').innerHTML);
	var count = parseInt(ci.retrieve('count'));
	count = count + 1;
	ci.store('count', count);
	if(txt.length > 0 && txt != $('__lang').down('#chatInput').innerHTML)
	{
		txt = txt.truncate(this.maxMsgLength,'').escapeHTML().gsub(/"/,'&quot;');
		var o = {
			cmd: this.getCmd('PRIVATE_MESSAGE'),
			msg: txt,
			user: ci.retrieve('chatpartner')
		};
		this.sendMessage(Object.toJSON(o));
		var o = {
			name: this.user.get('name'),
			time: this.getMsgTime(),
			avatarUrl:cb.down('.chat_input').down('.usericons').down('img').src,
			message: txt
		};
		this.addPrivChatEntry(ca, count, $H(o));
	}
},
	
handleAllSkillClick : function(event)
{
	event.stop();
	if(this.playLock)
	{
		return;
	}
	var a = event.findElement('a');
	var skill = a.retrieve('skill');
	var lang = $('__lang');
	if (skill.length == 1)
	{
		skill = [1, 2, 3];
		a.store('skill', skill);
		a.update(lang.down('#showOwnSkill').innerHTML);
	}
	else
	{
		skill = [this.user.get('skill')];
		a.store('skill', skill);
		a.update(lang.down('#showAllSkills').innerHTML);
	}
	var table = a.up('div', 1).next('.lobby_table');
	var gtt = parseInt(table.down('.gtt').innerHTML);
	var nop = parseInt(table.down('.nop').innerHTML);
	this.createRowEntry(table, gtt, skill, nop);
},
	
handleTabClick : function(name)
{
	if (name == 'players') {
		var lang = $('__lang');
		var d = new Date();
		var h = d.getHours();
		var m = d.getMinutes();
		var s = d.getSeconds();
		var updateTime = lang.down('#updateTime').innerHTML;
		updateTime = updateTime.gsub('#{time}', ((h < 10) ? '0' + h : h) + ':' + ((m < 10) ? '0' + m : m) + ':' + ((s < 10) ? '0' + s : s));
		$('players_areas').previous().update(updateTime);

		$('players_areas').update('');
		this.userlist.each(function(u){
			this.createUserListEntry(u);
		}, this);
		$('recommendations').hide();
		$('boximportant').hide();
		$('__gamelist').down('#cs').hide();
	}
	else if(name == 'info')
	{
		$('recommendations').show();
		$('boximportant').show();
		$('__gamelist').down('#cs').hide();
	}
	else if(name == 'chat')
	{
		$('recommendations').hide();
		$('boximportant').hide();
		$('__gamelist').down('#cs').show();
		if (this.scrollCH) {
			(function(){
				$('chat_areas').scrollTop = $('chat_areas').scrollHeight;
				this.scrollCH = false;
			}).delay(.1);
		}
	}
	else if (name == 'champions') {
		new Ajax.Updater('game_details_content', '/games/subpage/' + this.game_name, {
			evalScripts: true,
			parameters: {
				tab: 'dailychampions'
			}
		});
		$('game_legend').hide();
	}
	else if(name == 'game_selection')
	{
		$('game_legend').show();
	}
	else if(name == 'guide')
	{
		$('game_legend').hide();
	}
		
},
	
handleSFXClick : function(event)
{
	event.stop();
	var o = {
		cmd: this.getCmd('SOUND_STATE')
	};
	this.sendMessage(Object.toJSON(o));
},
	
// elment init
initTab : function(tabContainer)
{
	var divcont = [];
	var tabs = $(tabContainer).select('a').each( function(e)
	{
		var aname = e.href.match(/#(\w.+)/)[1];
		divcont.push(aname);
		e.observe('click', (function(event)
		{
			event.stop();
			var a = event.findElement('a');
			var n = a.href.match(/#(\w.+)/)[1];
			this.handleTabClick(n);
			$(n).show();
			$(n + '_link').addClassName('active');
			a.retrieve('tabs').without(n).each( function(n) {
				$(n).hide();
				$(n + '_link').removeClassName('active');
			});
		}).bind(this));
	}, this);
	tabs.each(function(tab) {
		tab.store('tabs', divcont);
	})
},
	
initChatInput : function()
{
	$('chat_areas').update('');
		
	var cif = $('chat_input');
	var cib = $('chat_input_send');
		
	cif.stopObserving('focus');
	cif.stopObserving('keydown');
	cif.stopObserving('keyup');
	cib.stopObserving('click');
		
	cif.observe('focus', function(e) {
		var t = e.findElement('textarea');
		t.value = '', t.stopObserving('focus')
		});
	cif.observe('keydown', this.handleSendPubMessage.bind(this));
	cif.observe('keyup', this.handleSendPubMessage.bind(this));
	cib.observe('click', this.handleSendPubMessage.bind(this));
		
	cif.value = $('__lang').down('#chatInput').innerHTML
},
	
initSkillSelector : function(elementId)
{
	var e = $(elementId);
	var userSkill = this.user.get('skill');
	e.store('skill', [userSkill]);
	e.stopObserving('click');
	e.observe('click', this.handleAllSkillClick.bind(this));
	if (userSkill != 3) {
		e.up('div').show();
		var lang = $('__lang');
		e.update(lang.down('#showAllSkills').innerHTML);
	}
	else
		e.up('div').hide();
},
	
initSFX : function()
{
	var sfxbtn = $$('div.lobby_header_button_ton')[0];
	var matchbtn = $$('div.lobby_header_button_ton')[1];
	sfxbtn.observe('click', this.handleSFXClick.bind(this));
	matchbtn.observe('click', this.handleSFXClick.bind(this));
},
	
initUserPopup : function(evt, user)
{
	Control.Modal.current.position(evt);
	var lang = $('__lang');
	var content = Control.Modal.current.container;
	var cancelFunc = (function(e){
		e.stop();
		this.removeModal();
		this.playLock = false;
	}).bind(this);
	content.down('div.x').observe('click', cancelFunc);
	content.down('div.button_s150_grey').observe('click', cancelFunc);
		
	content.down('div.button_s150_green').observe('click', (function(evt){
		evt.stop();
		if (content.down('div.button_s150_green').getStyle('opacity') == this.modalOpacity) return;
		//if (this.user.get('memberLevel') == 'limited') {
		//this.showLimitedPopup();
		//return;
		//}
		this.removeModal();
		this.playLock = false;
		var chatWindow = $('__chatBox' + this.getEscName(user.name));
		if (!Object.isElement(chatWindow)) {
			this.openPrivateChat(user.name);
		}
		else
			Control.Window.windows.find( function(w) {
				return (w.chatpartner == user.name);
			}).bringToFront();
	}).bind(this));

	try {
		content.down('li#profile_enemy').down('a').observe('click', (function(evt){
			evt.stop();
			try {
				var li = evt.findElement('li');
				var a = evt.findElement('a')
				if (a.hasClassName('addUser')) {
					this.handleAddBuddy(user.dbid, 2, true);
					a.removeClassName('addUser');
					a.update(lang.down('#delEnemy').innerHTML);
					li.up('ul#profile_actions').down('li#profile_friend').hide();
					li.insert({
						before: '<li title="" id="profile_empty" style = "background-image: url()"></li>'
					});
				}
				else {
					this.handleAddBuddy(user.dbid, 2, false);
					a.addClassName('addUser');
					a.update(lang.down('#addEnemy').innerHTML);
					li.up('ul#profile_actions').down('li#profile_empty').remove();
					li.up('ul#profile_actions').down('li#profile_friend').show();
				}
			}
			catch (e) {
			}
		}).bind(this));
	}
	catch (e) {
	}
		
	try {
		content.down('li#profile_friend').down('a').observe('click', (function(evt){
			evt.stop();
			try {
				var li = evt.findElement('li');
				var a = evt.findElement('a');
				if (a.hasClassName('addUser')) {
					this.handleAddBuddy(user.dbid, 1, true);
					a.removeClassName('addUser');
					a.update(lang.down('#delBuddy').innerHTML);
					li.up('ul#profile_actions').down('li#profile_enemy').hide();
				}
				else {
					this.handleAddBuddy(user.dbid, 1, false);
					a.addClassName('addUser');
					a.update(lang.down('#addBuddy').innerHTML);
					li.up('ul#profile_actions').down('li#profile_enemy').show();
				}
			}
			catch (e) {
			}
		}).bind(this));
	}
	catch (e) {
	}
},
	
openPrivateChat : function(name)
{
	$(document.body).insert('<div id="__chatBox' + this.getEscName(name) + '"></div>');
	var pcb = $('__chatBox' + this.getEscName(name));
	var recipiantUser = this.userlist.find( function(u) {
		return u.name == name
		});
	var avatarRecipiant = recipiantUser.avatar;
	if ((avatarRecipiant == null) || (avatarRecipiant == ''))
		avatarRecipiant = this.defaultIconS;
	var lang = $('__lang');
	var o = {
		recipiant: name,
		avatarRecipiant: avatarRecipiant,
		profile: lang.down('#profileString').innerHTML,
		privateChatWith: lang.down('#privateChatWith').innerHTML,
		chatInput: lang.down('#chatInput').innerHTML,
		send: lang.down('#chatSend').innerHTML,
		remainingChar: this.maxMsgLength + ' ' + lang.down('#remainingChar').innerHTML
	};
	pcb.insert(this.chatPopup.evaluate(o));
	var pcw = new Control.Window(pcb, {
		className: 'chat_window',
		draggable: pcb.select('.chat_header')[0],
		position: [this.getRandom(100, 300), this.getRandom(100, 300)],
		beforeClose: (function(){
			this.container.store('_top', this.container.getStyle('top'));
			this.container.store('_left', this.container.getStyle('left'));
		})
	});
	pcw.chatpartner = name;
	pcb.down('.chat_input').down('.usericons').down('img').src = $('chat').down('.chat_input').down('img').src;
	var cif = pcb.down('textarea.input');
	cif.store('count', 0);
	cif.store('chatpartner', name);
	var cib = pcb.down('.button_s_green_chat').down('a');
	
	cif.observe('focus', function(e) {
		var t = e.findElement('textarea');
		t.value = '', t.stopObserving('focus')
		});
	cif.observe('keydown', this.handleSendPrivatMessage.bind(this));
	cif.observe('keyup', this.handleSendPrivatMessage.bind(this));
	cib.observe('click', this.handleSendPrivatMessage.bind(this));
		
	pcb.down('div.chat_header').down('a').observe('click', function(evt) {
		evt.stop();
		pcw.destroy();
	});
		
	if(Control.Modal.current == false)
		pcw.open();
},
	
addPrivChatEntry : function(chat, count, o)
{
	var l = chat.immediateDescendants().length;
	if(l > 20)
	{
		chat.firstDescendant().remove();
	}
	var side = (count % 2 == 0) ? this.chatContRight : this.chatContLeft;
	var scroll = ((chat.scrollTop == (chat.scrollHeight - 186)) || (chat.scrollHeight <= 186));
	o.set('avatarUrl', this.getSmallAvatar(o.get('avatarUrl')));
	chat.insert(side.evaluate(o));
		
	var user = this.userlist.find( function(u) {
		return u.name == o.get('name')
		});
	if(user != null && user.isModerator)
	{
		chat.childElements().last().down('span').addClassName('moderator_name');
	}
	if(scroll) chat.scrollTop = chat.scrollHeight;
},
	
addPrivateSysMsg : function(name, msg)
{
	// find open chat
	var chatWindow = $('__chatBox' + this.getEscName(name));
	if (Object.isElement(chatWindow)) {
		var ci = chatWindow.down('textarea.input');
		var count = parseInt(ci.retrieve('count'));
		count = count + 1;
		ci.store('count', count);
		var o = {
			avatarUrl: '/images/usericons/small/24G_Icon.jpg',
			name: 'SYSTEM',
			message: msg
		};
		this.addPrivChatEntry(chatWindow.down('div.chat_areas'), count, $H(o));
	}
},

showRegPopup : function(clickArea)
{
	var lang = $('__lang');
	var o = {};
	o.headline = lang.down('#importantMsg').innerHTML;
	o.cancel = lang.down('#abortString').innerHTML;
	o.next = lang.down('#continueString').innerHTML;
	if (clickArea == 'pubChat')
		o.text = lang.down('#chatRegOnly').innerHTML;
	else if (clickArea == 'playerList')
		o.text = lang.down('#detailsRegOnly').innerHTML;
	else
		return;
	var cancel = (function(e){
		e.stop();
		this.removeModal();
		this.playLock = false;
	}).bind(this);
	var next = (function(e){
		e.stop();
		window.location.href = '/account/new';
	}).bind(this);
	this.showModal(o, 'info', cancel , next);
},
	
showLimitedPopup : function()
{
	this.showModal(null, 'profil', null , null);
	new Ajax.Updater(Control.Modal.current.container, '/games/subpage/' + this.game_name, {
		evalScripts: false,
		parameters: {
			tab: 'chatuser_not_qualified'
		},
		onComplete: (function(evt){
			Control.Modal.current.position(evt);
			var content = Control.Modal.current.container;
			var cancelFunc = (function(e){
				e.stop();
				this.removeModal();
				this.playLock = false;
			}).bind(this);
			content.down('div.button_big_grey').observe('click', cancelFunc);
		}).bind(this)
	});
},
	
showModal : function(content, type, cancelFunc, nextFunc)
{
	try {
		if(Control.Modal.current)
		{
			this.openModals.push(Control.Modal.current);
		}
		var modal	= new Control.Modal(null,{
			overlayOpacity: this.modalOpacity,
			fade: false
		});
				
		if (type == 'info') {
			modal.container.update(this.infoPopup.evaluate(content));
			modal.container.down('div.x').observe('click', cancelFunc);
			modal.options.closeOnClick = false;
			modal.options.afterOpen = function(){
				if (Prototype.Browser.IE == false)
					Control.Overlay.positionIFrameShim();
			};
				
			modal.container.down('#btncancel').observe('click', cancelFunc);
			modal.container.down('#btnnext').observe('click', nextFunc);
		}
		if (type == 'info_once') {
			modal.container.update(this.infoOncePopup.evaluate(content));
			modal.container.down('div.x').observe('click', cancelFunc);
			modal.options.closeOnClick = false;
			modal.options.afterOpen = function(){
				if (Prototype.Browser.IE == false)
					Control.Overlay.positionIFrameShim();
			};
			modal.container.down('#btncancel').observe('click', cancelFunc);
			modal.container.down('#btnnext').observe('click', nextFunc);
		}
		else if(type == 'jackpot_info') {
			modal.container.update(this.jackpotInfoPopup.evaluate(content));
			modal.container.down('div.x').observe('click', cancelFunc);
			modal.options.closeOnClick = false;
			modal.options.afterOpen = function(){
				if (Prototype.Browser.IE == false)
					Control.Overlay.positionIFrameShim();
			};

			modal.container.down('#btncancel').observe('click', cancelFunc);
		}
		else if(type == 'warn')
		{
			modal.container.update(this.warnPopup.evaluate(content));
			modal.container.down('div.x').observe('click', nextFunc);
			modal.options.closeOnClick = false;
			modal.options.afterOpen = function(){
				if (Prototype.Browser.IE == false)
					Control.Overlay.positionIFrameShim();
			};
				
			modal.container.down('#btnnext').observe('click', nextFunc);
		}
		else if(type == 'progress')
		{
			modal.container.update(this.progressPopup.evaluate(content));
			modal.options.closeOnClick = false;
			modal.options.afterOpen = function(){
				if (Prototype.Browser.IE == false)
					Control.Overlay.positionIFrameShim();
			};
		}
		else if(type == 'profil')
		{
			modal.options.closeOnClick = false;
		}
		modal.container.store('type', type);
		modal.open();
		Control.Overlay.show(this.modalOpacity);
			
		if(this.isFF)	if($('lobbycontent').getStyle('left') == '-812px') this.flashObject.setStyle( {
			visibility: 'hidden'
		});
	}
	catch(e)
	{
		alert(e.name + ' : ' + e.message);
	}
},
	
removeModal : function()
{
	// are there stored modals ?
	var current = Control.Modal.current;
	Control.Modal.close();
	Control.Modal.current = false;
	current.destroy();
	if(this.openModals.length > 0)
	{
		Control.Modal.current = this.openModals.last();
		this.openModals.pop();// = this.openModals.without(current);
		if(Control.Modal.current.container.retrieve('type') == 'progress')
		{
			this.removeModal();
			return;
		}
		Control.Modal.current.open();
		Control.Modal.current.container.show();
		Control.Overlay.show(this.modalOpacity);
	}
	else
	{
		this.refreshWindows();
		if(this.isFF)	if($('lobbycontent').getStyle('left') == '-812px') this.flashObject.setStyle( {
			visibility: 'visible'
		});
	}
},
	
refreshWindows : function()
{
	Control.Window.windows.each( function(w) {
		w.open();
		if(w.container.retrieve('_top'))
		{
			w.container.setStyle({
				top: w.container.retrieve('_top'),
				left: w.container.retrieve('_left')
			});
		}
	});
},
	
removeAllWindows : function()
{
	Control.Modal.close();
	try {
		Control.Window.windows.each(function(w){
			w.destroy()
		});
	}
	catch(e)
	{
		alert(e.name + ' : ' + e.message);
	}
	this.openModals = [];
	if(Object.isUndefined(Control.Overlay.iFrameShim) == false)
		Control.Overlay.hide();
},
	
createUserListEntry : function(user)
{
	var lang = $('__lang');

	user.profilStr = lang.down('#profileString').innerHTML;
	user.detailStr = lang.down('#detailsString').innerHTML;
	var e = new Element('div', {
		'class' : 'infoareas'
	});
	if ((user.avatar == 'null') || (user.avatar == ''))
		user.avatar = this.defaultIconS;
	e.insert(this.userCont.evaluate(user));
	if(user.buddy == 'Friend')
		e.down('div.usericon').update('<img title="' + lang.down('#buddy').innerHTML + '" alt="' + lang.down('#buddy').innerHTML + '" src="/images/icons/friend.gif">');
	else if(user.buddy == 'Enemy')
		e.down('div.usericon').update('<img title="' + lang.down('#enemy').innerHTML + '" alt="' + lang.down('#enemy').innerHTML + '" src="/images/icons/enemy.gif">');
			
	if(user.sex == 'Male')
		e.down('div.username').insert({
			bottom: new Element('img', {
				src: '/images/lobby/m.png',
				width: 13,
				height: 15
			})
			});
	else if(user.sex == 'Female')
		e.down('div.username').insert({
			bottom: new Element('img', {
				src: '/images/lobby/w.png',
				width: 13,
				height: 15
			})
			});
			
	if (user.name == this.user.get('name')) {
		e.down('div.userlink a').hide();
	}
	else {
		if (user.isModerator)
			e.down('div.userlink a').update(lang.down('#talkToModerator').innerHTML);
				
		e.down('div.userlink a').observe('click', (function(evt){
			evt.stop();
			if (this.userNotInLobby(user.name)) {
				return;
			}
			if (this.isGuest) {
				this.showRegPopup('playerList');
				return;
			}
			if (user.isModerator) {
				var chatWindow = $('__chatBox' + this.getEscName(user.name));
				if (Object.isElement(chatWindow)) {
					// bring to front
					Control.Window.windows.find(function(w){
						return (w.chatpartner == user.name);
					}).bringToFront();
				}
				else
					this.openPrivateChat(user.name);
				return;
			}
			this.showModal(null, 'profil', null, null);
			new Ajax.Updater(Control.Modal.current.container, '/games/subpage/' + this.game_name, {
				evalScripts: true,
				parameters: {
					tab: 'userprofile',
					user_name: user.name
				},
				onComplete: (function(evt){
					this.initUserPopup(evt, user);
				}).bind(this)
			});
		}).bind(this));
	}
	$('players_areas').insert( {
		bottom: e
	});
},

updateGameTables : function(fullUpdate)
{
	var tables = $('game_selection').select('.lobby_table');
	try {
		tables.each( function(e)
		{
			var gtt = parseInt(e.down('.gtt').innerHTML);
			var nop = parseInt(e.down('.nop').innerHTML);
			if (gtt == 1)
			{
				this.createRowEntry(e, gtt, [3], nop);
			}
			else
			{
				if(!fullUpdate)
					tSkill = e.retrieve('skill');
				else
					tSkill = nop;
						
				if (tSkill)
				{
					this.createRowEntry(e, gtt, tSkill, nop);
				}
				else
				{
					this.createRowEntry(e, gtt, [this.user.get('skill')], nop);
					entrys_total = this.gamelist.filter( function(e) {
								return e.mode == gtt && e.skill >= this.user.get('skill');
							}, this).size();
					entrys_same = this.gamelist.filter( function(e) {
								return e.mode == gtt && e.skill == this.user.get('skill');
							}, this).size();
					if(entrys_total > entrys_same){
						var elementId = e.up('div').down('.lobby_headline_link').down('a');
						this.initSkillSelector(elementId);
					}
				}
			}
		}, this);
	} catch(e) {}
},

createRowEntry : function(table, mode, skill, nop)
{
	var lang = $('__lang');
	var rows = table.select('div.light_sand', 'div.sand', 'div.orange');
	rows.each( function(e) {
		e.remove();
	});
	var entrys;
	if (this.isSinglePlayer)
		entrys = this.gamelist.filter( function(e) {
			return e.mode == mode && (skill.indexOf(e.skill) != -1 && e.skill >= this.user.get('skill'));
		}, this);
	else
		entrys = this.gamelist.filter( function(e) {
			return e.mode == mode && ((mode == 1) || (skill.indexOf(e.skill) != -1 && e.skill >= this.user.get('skill') && e.maxPlayer == nop));
		}, this);

	var c = 0;
	var lastRow = table.down('.lobby_table_headline_bg');
	entrys.each( function(_e)
	{
		var e = Object.clone(_e);
		if (mode == 1)
		{
			e.skill = 0;
			if (this.isSinglePlayer)
			{
				e.maxPlayer = 2;
			}
			else
			{
				e.maxPlayer = e.player + ' / ' + e.maxPlayer;
			}
		}
		if (mode == 3)
		{
			e.maxPlayer = e.player + ' / ' + e.maxPlayer;
		}
		if (mode == 4)
		{
			e.maxPlayer = 0;
			time = new Date();
			if(e.endTime != 0 && time.getTime() <= e.endTime*1000)
			{
				e.maxPlayer = formatTime(e.endTime*1000);
			}
			else
			{
				e.maxPlayer = '<span class="lobby_table_time">'+$('duration_game_table_type_id_'+e.id).innerHTML+'</span>';
			}
		}
		//e.order = (c % 2 == 0) ? 'light_sand' : 'sand';
		e.bet = this.currency(e.bet / 100);
		var info = null;
		if (mode == 4)
		{
			e.win = this.updateJackpotAmount(e);
			e.jp_win = this.updateJackpotAmount(e, true);
			info = new Element('div', {
				'class': 'lobby_table_info dotted_border_right'
			});
			link = new Element('a', {
				'href' :'#',
				'id' : 'gtt_link_'+ e.id
				});
			info.insert(link);
		}
		else
		{
			e.win = this.currency(e.win / 100);
		}
		e.buttonPlay = lang.down('#buttonPlay').innerHTML;
		e.waitPlayer = lang.down('#waitForPlayer').innerHTML;
		e.buttonAbort = lang.down('#buttonAbort').innerHTML;

		var color = (c % 2 == 0) ? 'light_sand' : 'sand';
		var row = new Element('div', {
			'class': 'row ' + color,
			id: 'gtt' + e.id
			});
		if(mode == 4)
			row.insert(this.gljpentry.evaluate(e));
		else
			row.insert(this.glentry.evaluate(e));
		row.store('defaultColor', color);

		row.down('div.lobby_table_button').show();
		var btn = row.down('.button_green_95x25_play').down('a');
		btn.store('gameId', e.id);
		btn.observe('click', this.handlePlayClick.bind(this));

		row.down('div.lobby_table_wait').hide();
		var link = row.down('div.lobby_table_wait').down('a');
		link.store('gameId', e.id);
		link.observe('click', this.handlePlayClick.bind(this));

		Element.insert(lastRow, {
			after: row
		});
		if(info != null)
		{
			var el = $(row).select("div.lobby_table_price")[0];
			el.removeClassName("dotted_border_right");
			el.removeClassName("w_83");
			el.addClassName("w_60");
			Element.insert(el, {
				after: info
			})
			$('gtt_link_'+ e.id).observe('click', (function(evt){
				this.handleJackpotTournamentClick(evt);
			}).bind(this));
		}

		lastRow = row;
		c++;
	}, this);
},
	
updateUserCount : function(lobby, limbo)
{
	if(Object.isUndefined(this.usersingame))
	{
		this.usersingame = $('__lang').down('#nrofusersingame').innerHTML;
	}
	var m = this.usersingame.gsub('#{lobby}', this.formatNumber(lobby)).gsub('#{limbo}', this.formatNumber(limbo));
		
	$$('div.boxuserinfo').each( function(e){
		if(Object.isElement(e.down('div.text')))
		{
			e.down('div.text').update(m);
		}
		else
		{
			e.update(m);
		}
	});
},
	
// helper
log: function(message)
{
	/*		if (this.isFF) {
			if(typeof(message) == 'string')
				console.log('TC.log: %s', message);
			//$('log').insert(message + '<br>');
		}*/

	},
	
	getCmd : function(cmd)
	{
		if(typeof(cmd) == 'string')
			return this.COMMANDS.find(function(e) {
				return (e.key == cmd);
			}, this).i;
		else
			return this.COMMANDS.find(function(e) {
				return (e.i == cmd);
			}, this);
	},
	
	currency : function(val) 
	{
		var aDigits = val.toFixed(2).split(".");
		aDigits[0] = aDigits[0].split("").reverse().join("").replace(/(\d{3})(?=\d)/g, "$1.").split("").reverse().join("");
		return aDigits.join(",");
	},
	
	getSmallAvatar : function(mediumAvatar)
	{
		if ((mediumAvatar == null) || (mediumAvatar == 'null') ||
			(mediumAvatar == '') || (mediumAvatar == undefined))
			return this.defaultIconS;
		
		var thumb = mediumAvatar;
		if(mediumAvatar.indexOf('/files/avatars/') != -1)
		{
			// custom icon
			thumb = mediumAvatar.gsub('medium', 'thumb');
		}
		else			
			thumb = mediumAvatar.gsub('medium', 'small');
		return thumb;
	},
	
	getMsgTime : function()
	{
		var d = new Date();
		var h = d.getHours();
		var m = d.getMinutes();
		return '[' + ((h < 10) ? "0" + h : h) + ':' + ((m < 10) ? "0" + m : m) + ']';
	},
	
	getRandom : function( min, max )
	{
		if( min > max ) {
			return( -1 );
		}
		if( min == max ) {
			return( min );
		} 
		return( min + parseInt( Math.random() * ( max-min+1 ) ) );
	},
	
	getEscName : function( name )
	{
		var _ret = name.replace(/Q/g, "QQQ");
		return( _ret.replace(/\*/g, "Q") );
	},
	
	orderUserList : function()
	{
		// moderators at the top
		var _modlist = this.userlist.filter( function(e) {
			return e.isModerator;
		}, this);
		var _ml	= _modlist.sort( function(a, b){
			return (a.name < b.name ? -1 : 1);
		});
		// other users beneath
		var _usrlist = this.userlist.filter( function(e) {
			return !e.isModerator;
		}, this);
		var _ul	= _usrlist.sort(function(a, b){
			return (a.name < b.name ? -1 : 1);
		});
		this.userlist = _ml.concat(_ul);
	},

	userNotInLobby : function(username)
	{
		var srcUser = this.userlist.filter( function(u) {
			return (u.name == username);
		} );
		if (srcUser.size() > 0) return false;
		return true;
	},
	
	updateUserOpacity : function()
	{
		if(!$('players').visible()) return;
		var usersname;
		$('players_areas').childElements().each( (function(user) {
			if(this.userNotInLobby(user.down('strong').innerHTML))
				user.setStyle({
					opacity: this.modalOpacity
					});
			else
				user.setStyle({
					opacity: 1.0
				});
			
		}).bind(this));
	},

	showSkillSelector : function(clickedBtn, show)
	{
		var skillSelector = clickedBtn.up('div.lobby_table_group').down('a');
		if ((show) && (parseInt(this.user.get('skill')) != 3))
			skillSelector.show()
		else
			skillSelector.hide()
	},

	markRowToPlay : function(button, wait)
	{
		var color;
		var row = button.up('div.row');
		if (wait)
		{
			if (row.hasClassName('light_sand'))
				color = 'light_sand';
			else
				color = 'sand';
			row.removeClassName(color);
			row.addClassName('orange');
			row.down('div.lobby_table_button').hide();
			row.down('div.lobby_table_wait').show();
		}
		else
		{
			color = row.retrieve('defaultColor')
			row.removeClassName('orange')
			row.addClassName(color)
			row.down('div.lobby_table_button').show();
			row.down('div.lobby_table_wait').hide();
		}
	},

	formatNumber : function(val) 
	{
		var aDigits = String(val);
		return aDigits.split("").reverse().join("").replace(/(\d{3})(?=\d)/g, "$1.").split("").reverse().join("");
	},
	updateJackpotAmount : function(obj, with_span){
		if(with_span == null)
			with_span = true;
		time = new Date();
		if(obj.endTime != 0 && time.getTime() <= obj.endTime*1000)
		{
			obj.win = this.currency(obj.jackpotAmount / 100);
		}
		else
		{
			obj.win = $('min_win_game_table_type_id_'+obj.id).innerHTML;

		}
		if(with_span){
			length = obj.win.match("[0-9\.]+")[0].length;
			switch(length) {
				case 3:
					obj.win = '<span class="font_15">'+obj.win+'&nbsp;&euro;</span>';
					break;
				case 5:
					obj.win = '<span class="font_12">'+obj.win+'&nbsp;&euro;</span>';
					break;

				case 6:
					obj.win = '<span class="font_11">'+obj.win+'&nbsp;&euro;</span>';
					break;
				default:
					return obj.win + '&nbsp;&euro;';
					break;
			}

		}
		return obj.win;
	}
};


function showGame(){};

function formatTime(time){
	var t = new Date(time);
	var minutes = t.getMinutes();
	if (minutes < 10)
		minutes = "0" + minutes;
	var month = t.getMonth() +1 ;
	if (month < 10)
		month = "0" + month;
	var day = t.getDate();
	if (day < 10)
		day = "0" + day;
	var hours = t.getHours();
	if (hours < 10)
		hours = "0" + hours;
	var year = t.getFullYear();
	var time_str = day + "." + month + "." + year + " " + hours + ":" + minutes + " Uhr"
	return '<span class="lobby_table_time">'+time_str+'</span>';
};



// =========
// = UTILS =
// =========
function getDocHeight() {
  var D = document;
  return Math.max(
    Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
    Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
    Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function blur_(value_, object_) {
  if(object_.value=="") {
    object_.value=value_;
  }
}

function focus_(value_, object_) {
  if(object_.value==value_) {
    object_.value="";
  }
}

function textCounter(field, id, limit) {
  limit = typeof(limit) != 'undefined' ? limit : 180;
  if (field.value.length > limit) {
    field.value = field.value.substring(0, limit);
  } else {
    document.getElementById(id).innerHTML = limit - field.value.length;
  }
}


// ==========
// = POPUPS =
// ==========

function optinPopup() {
  var win = null;
  var width = 658;
  var height = 532;
  var winleft = (screen.width-width)/2;
  var wintop = (screen.height-height)/2;
  
  var settings = 'height=' + height + ',width=' + width + ',top=' + wintop + ',left=' + winleft + 'scrollbars=no,resizeable=no';
  
  win=window.open('/profile/optin_popup','Newsletter',settings);
  if(parseInt(navigator.appVersion, 10) >= 4) {
    win.window.focus();
  }
  
  return false;
}

function recommendationPopup(popup_url) {
  var win = null;
  var width = 665;
  var height = 533;
  var winleft = (screen.width-width)/2;
  var wintop = (screen.height-height)/2;
  var settings  ='height='+height+',';
  settings +='width='+width+',';
  settings +='top='+wintop+',';
  settings +='left='+winleft+',';
  settings +='scrollbars=yes,';
  settings +='resizable=no';
  win=window.open(popup_url,'weiterempfehlen',settings);
  if(parseInt(navigator.appVersion, 10) >= 4){
    win.window.focus();
  }
	
  return false;
}


// ===========
// = SPINNER =
// ===========

function insertSpinner(element, pos) {
  var spinner = new Element('img', {
    'src': '/images/icons/loading.gif',
    'alt': 'Lädt…'
  }).addClassName('default_spinner');
  element.insert({
    'bottom': spinner
  });
  return spinner;
}

function removeSpinner(spinner) {
  spinner.remove();
}


// ===========
// = TOGGLES =
// ===========

function toggleService() {
  var content = $('sidebar_service_content');
  var close = $('sidebar_service_close');
  var open = $('sidebar_service_open');
  
  if (!content.visible()) {
    content.blindDown({
      duration: 0.3
    });
    open.hide();
    close.show();
  } else {
    if (content.visible()) {
      content.blindUp({
        duration: 0.3
      });
      open.show();
      close.hide();
    };
  }
  
  return false;
}

function toggleHighlightClass(element) {
  element.toggleClassName('highlight');
}

function toggleGenreGame(genrePos, gamePos) {
  var posArray = ['top_game','game_2','game_3'];
  for (var posIdx in posArray) {
    var pos = posArray[posIdx];
    if (typeof(pos) == 'string') {
      if($('genre_' + genrePos + '_' + pos + '_big') != null){
        $('genre_' + genrePos + '_' + pos + '_big').style.display = (pos == gamePos ? 'block' : 'none');
      }
      if($('genre_' + genrePos + '_' + pos + '_small') != null) {
        $('genre_' + genrePos + '_' + pos + '_small').style.display =  (pos == gamePos ? 'none' : 'block');
      }
    }
  }
}


// ============
// = SWITCHES =
// ============

function switchLobbyNaviTab(divName) {
  var tabArray = ['game_selection','guide','champions','game'];
  for (var tabIdx in tabArray) {
    var tab = tabArray[tabIdx];
    if (typeof(tab) == 'string') {
      $(tab).style.display = (tab == divName ? 'block' : 'none');
      if ($(tab + '_link'))
        if (tab == divName)
          $(tab + '_link').addClassName('active');
        else
          $(tab + '_link').removeClassName('active');
    }
  }
  return false;
}

function switchLobbySidebarNaviTab(divName) {
  var tabArray = ['info','chat','players'];
  for (var tabIdx in tabArray) {
    var tab = tabArray[tabIdx];
    if (typeof(tab) == 'string') {
      $(tab).style.display = (tab == divName ? 'block' : 'none');
      if ($(tab + '_link'))
        if (tab == divName)
          $(tab + '_link').addClassName('active');
        else
          $(tab + '_link').removeClassName('active');
    }
  }
  return false;
}

function switchSkilllevel(skilllevel, area) {
  var img_count;
  switch (area) {
  case 'training':
    img_count = 1;
    break;
  case 'match':
    img_count = 5;
    break;
  case 'tournament':
    img_count = 8;
    break;
  }

  var img_num = 1;
  for (img_num = 1; img_num <= img_count; img_num++) {
    $(area + '_' + img_num.toString() + '_img').src = '/images/lobby/stars' + skilllevel.toString() + '.png';
  }

  $('skilllevel_submenu_' + area).toggle();
}

function switchGamesPlayTab(game_shortname, tab) {
  new Ajax.Updater('game_details_content', '/games/subpage/' + game_shortname, {
    evalScripts: true,
    parameters: {
      tab: tab
    },
    onComplete: function(transport) {
      $('story_link').removeClassName('active');
      if ($('extras_link'))
        $('extras_link').removeClassName('active');
      $('champions_link').removeClassName('active');
      $('screenshots_link').removeClassName('active');
      $(transport.request.parameters['tab'] + '_link').addClassName('active');
    }
  });
  return false;
}


// ============
// = OVERLAYS =
// ============

function openDefaultOverlay(content, options) {
  var class_for_overlay;
  var overflow_for_overlay;
  var options = options || {};
  
  try{
    // If the content is a html element
    content.hide();
    var content = content.cloneNode(true);
    content.show();
  }catch(e){
    // if its just a string
    var content = content;
  };
  
  // specific class for the overlay
  if (!options.id) {
    try{
      class_for_overlay = content.id;
      content.id = "";
    }catch(e){
      class_for_overlay = '';
    };
  } else {
    class_for_overlay = options.id;
  };
  
  if(options.css_class) {
    class_for_overlay += " " + options.css_class;
  }
  
  // dynamically create overlay structure
  var overlay = new Element('div', {
    'id': 'overlay'
  });
  var container = new Element('div', {
    'id': 'overlay_container'
  });
  var content_wrapper = new Element('div', {
    'id': 'overlay_content'
  }).addClassName(class_for_overlay + ' overlay_container');
  content_wrapper.insert({
    top: content
  });
  
  // create Close button
  if (options.close_button) {
    var close_button = new Element('a', {
      'id': 'default_close_overlay',
      'href': '#'
    });
    var close_image = new Element('img', {
      'src': '/images/popups/default_close_overlay.png',
      'alt': 'Schließen'
    });
    close_button.update(close_image);
    container.insert({
      top: close_button
    });
    close_button.observe('click', function(e) {
      Event.stop(e);
      closeDefaultOverlay();
    });
  };
  
  // append elements
  $$('body').first().insert({
    top: overlay
  });
  overlay.insert({
    top: container
  });
  container.insert({
    top: content_wrapper
  });
  
  // styling stuff, positioning and height
  var height = getDocHeight();
  
  overlay.setStyle({
    width: '100%',
    height: height + 'px'
  });
  
  if (container.getHeight() > document.viewport.getHeight()) {
    container.setStyle({
      width: ((container.getWidth() + 15) + 'px'),
      height: ((document.viewport.getHeight() - 50) + 'px'),
      overflow: 'auto'
    });
  };
  
  container.setStyle({
    top: (document.viewport.getScrollOffsets().top + (document.viewport.getHeight() / 2) - container.getHeight() / 2) + 'px',
    left: (document.viewport.getWidth() / 2 - container.getWidth() / 2) + 'px'
  });
  return false;
}
function closeDefaultOverlay() {
  var overlay = $('overlay').remove();
  var container = $('overlay_container');
  if (container) container.remove();
  return false;
}

var games_overlay_loaded = false;
function showGamesOverlay() {
  document.observe("mousedown", function(event) {
    closeGamesOverlay(event);
  });
  
  var overlay = $('sidebar_games_overlay');
  new Effect.Appear(overlay, {
    duration: 0.3
  });
  
  if (games_overlay_loaded) {
  } else {
    new Ajax.Request('/games/get_games_list', {
      onLoading: function(request) {
        $('sidebar_games_overlay_spinner').show();
      },
      onSuccess: function(request) {
        $('sidebar_games_overlay_list').update(request.responseText);
        games_overlay_loaded = true;
      },
      onFailure: function(request) {

      },
      onComplete: function(request) {
        $('sidebar_games_overlay_spinner').hide();
      }
    });
  }
  
  return false;
}
function closeGamesOverlay(event) {
  overlay = $('sidebar_games_overlay');
  event_element = Event.element(event);
  
  if (event_element != overlay && !event_element.descendantOf(overlay)) {
    overlay.fade({
      duration: 0.3
    });
    document.stopObserving("mousedown");
  };
}

function showCouponOverlay(div_id) {
  if(Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6){
    showCouponOverlayIE(div_id);
    return;
  }

  if (div_id == null){
    div_id = 'overlay_content';
  }
  var overlay = new Element('div', {
    'id': 'overlay'
  });
  var container = new Element('div', {
    'id': 'overlay_container'
  });
  var content = $(div_id).cloneNode(true);
  $(div_id).remove();
  var height = getDocHeight();

  container.addClassName(div_id);
  $$('body').first().insert({
    top: overlay
  });
  overlay.insert({
    top: container
  });
  container.insert({
    top: content
  });
  
  content.show();
  overlay.setStyle({
    width: '100%',
    height: height + 'px'
    });
  container.setStyle({
    top: (document.viewport.getScrollOffsets().top + (document.viewport.getHeight() / 2) - container.getHeight() / 2) + 'px',
    left: (document.viewport.getWidth() / 2 - container.getWidth() / 2) + 'px'
  });
}
function showCouponOverlayIE(div_id) {

  if (div_id == null){
    div_id = 'overlay_content';
  }
  var container = new Element('div', {
    'id': 'overlay_container'
  });
  var content = $(div_id).cloneNode(true);
  $(div_id).remove();
  var height = getDocHeight();

  container.addClassName(div_id);
  $$('body').first().insert({
    top: container
  });
  container.insert({
    top: content
  });

  content.show();
  container.setStyle({
    top: (document.viewport.getScrollOffsets().top + (document.viewport.getHeight() / 2) - container.getHeight() / 2) + 'px',
    left: (document.viewport.getWidth() / 2 - container.getWidth() / 2) + 'px'
  });
}
function closeCouponOverlay() {
  if(Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6){
    closeCouponOverlayIE();
    return;
  }

  if($('overlay').style.display != "none") {
    $('overlay').fade({
      duration: 0.5,
      afterFinish: function() {
        $('overlay').remove();
      }
    });
  }
}
function closeCouponOverlayIE() {
  if($('overlay_container').style.display != "none") {
    $('overlay_container').fade({
      duration: 0.5,
      afterFinish: function() {
        $('overlay_container').remove();
      }
    });
  }
}

function openLeagueResultOverlay(link, game) {
  var spinner;
  new Ajax.Request('/league/get_results', {
    parameters: {
      game_id: game
    },
    onCreate: function() {
      spinner = insertSpinner(link);
    },
    onSuccess: function(response) {
      removeSpinner(spinner);
      $('content').scrollTo();
      $('result_overlay_container').update(response.responseText);
    },
    onComplete: function(response) {
      var content_height = $('content').getHeight();
      var overlay_height = $('result_overlay_container').down(0).getHeight();
      if (overlay_height > content_height) {
        $('content').setStyle({
          'height': overlay_height+'px'
          });
      };
    }
  });
  return false;
}
function closeLeagueResultOverlay() {
  $('result_overlay_container').update('');
  $('content').setStyle({
    'height': 'auto'
  });
  return false;
}

function openGameDetailsOverlay(link, genre_game_id) {
  var spinner;
  new Ajax.Request('/start/game_details/' + genre_game_id, {
    onCreate: function() {
      spinner = insertSpinner(link);
    },
    onSuccess: function(response) {
      removeSpinner(spinner);
      //$('content').scrollTo();
      $('game_details_overlay_container').update(response.responseText);
    },
    onComplete: function(response) {
      var content_height = $('content').getHeight();
      var overlay_height = $('game_details_overlay_container').down(0).getHeight();
      if (overlay_height > content_height) {
        $('content').setStyle({
          'height': overlay_height+'px'
          });
      };
    },
    onFailure: function(response) {
      removeSpinner(spinner);
    }
  });
  return false;
}
function closeGameDetailsOverlay() {
  $('game_details_overlay_container').update('');
  // $('content').setStyle({'height': 'auto'});
  return false;
}


function openNotificationOverlay(content, options) {
  var options = options || {};
  
  try {
    // If the content is a html element
    content.hide();
    var content = content.cloneNode(true);
    content.show();
  } catch(e) {
    // if its just a string
    var content = content;
  };

  // dynamically create overlay structure
  var overlay = new Element('div', {
    'id': 'overlay'
  });
  var container = new Element('div', {
    'id': 'overlay_container'
  });
  var content_wrapper = new Element('div', {
    'id': 'overlay_content'
  });
  content_wrapper.addClassName(content.id);
  content_wrapper.insert({
    top: content
  });
  
  // create close button for corner
  var close_button_corner = new Element('a', {
    'href': '#'
  });
  close_button_corner.addClassName("close");
  close_button_corner.observe('click', function(e) {
    Event.stop(e);
    closeNotificationOverlay();
  });
  content_wrapper.insert({
    top: close_button_corner
  });
  
  var close_button = new Element('a', {
    href: '#'
  }).update("Schließen");
  close_button.addClassName("button_close");
  close_button.observe('click', function(e) {
    Event.stop(e);
    closeNotificationOverlay();
  });
  content.insert(close_button);
  
  var footer = new Element('div');
  footer.addClassName("overlay_bottom w_474");
  content_wrapper.insert(footer);
  
  // append elements
  $$('body').first().insert({ top: overlay });
  overlay.insert({ top: container });
  container.insert({ top: content_wrapper });
  
  // styling stuff, positioning and height
  var height = getDocHeight();
  
  overlay.setStyle({
    width: '100%',
    height: height + 'px'
  });
  
  if (container.getHeight() > document.viewport.getHeight()) {
    container.setStyle({
      height: ((document.viewport.getHeight() - 50) + 'px'),
      overflow: 'auto'
    });
  };
  
  container.setStyle({
    top: (document.viewport.getScrollOffsets().top + (document.viewport.getHeight() / 2) - container.getHeight() / 2) + 'px',
    left: (document.viewport.getWidth() / 2 - container.getWidth() / 2) + 'px'
  });
  return false;
}
function closeNotificationOverlay() {
  closeDefaultOverlay();
}


// ===============
// = OTHER STUFF =
// ===============

function depotDetail(id, round_id, name, cents, date, game_active) {
  if ($('details_for_' + id).empty()) {
    new Ajax.Updater('details_for_' + id, '/profile/gamedepot_detail', {
      asynchronous:true,
      evalScripts:true,
      parameters:{
        game_round_id: round_id,
        game_shortname: name,
        euro_cents: cents,
        date: date,
        game_active: game_active
      }
    });
  }

  if ($('details_for_' + id).style.display == 'none')
  {
    $('details_for_' + id).style.display = '';
  }
  else
  {
    $('details_for_' + id).style.display = 'none';
  }
	
  if ($('row_for_' + id).hasClassName('active'))
  {
    $('row_for_' + id).removeClassName('active');
  }
  else
  {
    $('row_for_' + id).addClassName('active');
  }	
}

function doOptIn(source) {
  new Ajax.Request('/profile/opt_in?yes&' + source, {
    onSuccess: function(transport) {
      $('status_bar_container').innerHTML = transport.responseText;
      if ($('optin_header_div')) $('optin_header_div').toggle();
      if ($('optin_container_div')) $('optin_container_div').toggle();
    }
  });

  return false;
}

function redeemCoupon(couponcode) {
  showCouponOverlay('coupon_overlay');
  if ($('code_error_bar')) {
  //new Effect.Fade($('code_error_bar'), {duration: 0.3});
  }
  new Ajax.Request('/coupons/redeem?couponcode=' + couponcode, {
    onSuccess: function(transport) {
      if(transport.responseText == 'OK'){
        if ($('code_error_bar')) {
          new Effect.Fade($('code_error_bar'), {
            duration: 0.3
          });
        }
        closeCouponOverlay();
        self.location.href='/coupons/success';
      }
      else {
        if ($('code_error_bar')) {
          $('code_error_text').innerHTML = transport.responseText;
          new Effect.Appear($('code_error_bar'), {
            duration: 0.3
          });
        }
        closeCouponOverlay();
      }
    }
  });

  return false;
}

function login(form) {
  if(Prototype.Browser.WebKit == true){
    form.submit();
    return false;
  }
  var form = form;
  var error_box = form.previous('p');
  error_box.hide();
  
  new Ajax.Request(form.action, {
    parameters: {
      username : username,
      password : password,
      serviceprovider : serviceprovider,
      partner : partner,
      Tipp24GamesReturnUrl : Tipp24GamesReturnUrl
    },
    crossSite: true,
    method: 'GET',
    onSuccess: function(request) {
      window.location.reload();
    },
    onFailure: function(request) {
      error_box.show();
      error_box.down('span').innerHTML = request.responseText;
    }
  });
  
  return false;
}

// Opens Overlay for league Conditions
function leagueConditions(link) {
  var spinner;
  new Ajax.Request('/league/get_conditions', {
    onCreate: function() {
      spinner = insertSpinner(link);
    },
    onSuccess: function(response) {
      removeSpinner(spinner);
      openDefaultOverlay(response.responseText, {
        'close_button': true,
        'id': 'league_conditions'
      });
    },
    onComplete: function(response) {
    }
  });
  return false;
}

function turnBlogPage(page_num) {
  new Ajax.Updater('news_box', '/start/blog/' + page_num.toString(), {
    evalScripts: false
  });
  return false;
}


function fusionTeaserHover(element) {
  link = $(element).down("div");
  alink = $(element).down("a");
  element.observe("mouseover", function() { this.className = this.className.replace("button_green_188x42", "button_green_188x42_hover") }.bind(link));
  element.observe("mouseout",  function() { this.className = this.className.replace("button_green_188x42_hover", "button_green_188x42") }.bind(link));
  element.observe("click",     function() { location.href = this.href }.bind(alink));
}


$(document).observe("dom:loaded", function() {
  if (login_overlayer = $("login_overlay"))
    openDefaultOverlay(login_overlayer);

  if (notification_overlayer = $("notification_overlay"))
    openNotificationOverlay(notification_overlayer);

  if (customer_info_overlayer = $("customer_info")) {
      openDefaultOverlay(customer_info_overlayer, {id: 'customer_info_overlay'});

      Element.observe('close', 'click', function(e) {
	      Event.stop(e);
	      closeDefaultOverlay();
              return false;
	  });

      Element.observe('btnnext', 'click', function(e) {
	      Event.stop(e);
	      closeDefaultOverlay();
              return false;
	  });
  }

  if (teasers = $$(".fusion_game_teaser, .fusion_game_topgamer_box_180x530"))
    teasers.each(function(teaser) {
      fusionTeaserHover(teaser);
    });
});


var _sessionTimeout = 0;
var _SRT_ID = 0;

function formatCurrency(num) {
    num = parseFloat(num.replace(/\$|\,/g,''));
    if(isNaN(num))
        num = 0;
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    var numCents = num % 100;
    num = Math.floor(num/100).toString();
    if(numCents<10)
        numCents = "0" + numCents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.toString().substring(0,num.length-(4*i+3))+'.'+
            num.toString().substring(num.length-(4*i+3));

    return (((sign) ? '+ ' : '- ') + num) + ',' + numCents;
}



function updateCoins(euro_cent) {
    var euro = parseFloat(euro_cent/100).toFixed(2);
	var neg = (euro < 0);
    euro = String(euro);
    var str =  formatCurrency(euro) + ' EUR';
    if (document.getElementById('cents')) {
		if (neg) {
			document.getElementById('cents').innerHTML = '<span class="red_font">' + str + '</span>';
		}
		else {
			document.getElementById('cents').innerHTML = '<span>' + str + '</span>';
		}
    }
}



function refreshSession() {
    currentTime = new Date;
    if (_sessionTimeout <= currentTime.getTime()) {
        new Ajax.Request('/session/refresh', {
                onSuccess: function(transport) {
                    if (!transport.responseText.match(/SESSION_EXPIRED/)) {
                        var balancePattern = new RegExp("balance=(-?[0-9]+)");
                        var matches = balancePattern.exec(transport.responseText);
                        if (matches.length > 1) {
                            updateCoins(matches[1]);
                        }

                        var timeoutPattern = new RegExp("timeout=([0-9]+)");
                        var matches = timeoutPattern.exec(transport.responseText);
                        if (matches.length > 1) {
                            _sessionTimeout = currentTime.getTime() + parseInt(matches[1], 10);
                        }

                    }
                    else {
                        clearInterval(_SRT_ID);
                    }
                }
        });
    }
}


function startSessionRefreshTimer(timeout) {
    currentTime = new Date;
    _sessionTimeout = currentTime.getTime() + timeout;
    _SRT_ID = setInterval("refreshSession()", 30000);
}