// -----------------------------------------------------------------------------
//  Copyright 2009 Red Planet Marketing GmbH. All rights reserved.
// -----------------------------------------------------------------------------

//===========================
//   EVENT
//===========================
var CustomEvent = function() {
	//name of the event
	this.eventName = arguments[0];
	var mEventName = this.eventName;

	//function to call on event fire
	var eventAction = null;

	//subscribe a function to the event
	this.subscribe = function(fn) {
		eventAction = fn;
	};

	//fire the event
	this.fire = function(sender, eventArgs) {
		if(eventAction != null) {
			eventAction(sender, eventArgs);
		}
	};
};

var changeResolutionEvent = new CustomEvent("changeResolution");
var initializedEvent = new CustomEvent("InitializedEvent");
var playbackFinishedEvent = new CustomEvent("PlaybackFinishedEvent");
//============================

var isTableResizable = true;
var isLobbyResizable = true;

//constants defined for calling timeline events
    var HOLDEM_FLOP = 1;
		var HOLDEM_TURN = 2;
		var HOLDEM_RIVER = 3;
		var SEVENCARDSTUD_DOWN = 11;
		var SEVENCARDSTUD_4STREET = 4;
		var SEVENCARDSTUD_5STREET = 5;
		var SEVENCARDSTUD_6STREET = 6;
		var SEVENCARDSTUD_RIVER = 7;
		var SEVENCARDSTUD_COMMUNITY = 8;
		var SEVENCARDSTUD_ALLIN = 12;
		var SHOWDOWN = 9;		
		var START = 10;

var _RPXExternal = function()
{	            	            
    this._tableWindows = {};
    this._openWindows = {};
    this.MIN_LOBBY_WIDTH = 580;
	this.MIN_LOBBY_HEIGHT = 425;
};

	function _RPXExternal$_initTableScreen(width, height, rightSpaceWidth, bottomSpaceHeight)
    {
    	RPXExternal.initApplicationScreen(width, height, rightSpaceWidth, bottomSpaceHeight);
    	
    	//history will be initialized later
    	this._gameHistoryInitialized = false;
    	
    	//lobby has got information (global function) about table beeing resized
    	if (window.opener && !window.opener.closed)
			isTableResizable = window.opener.isTableResizable;
    	else 
			isTableResizable = false;
	 }
	 
	 function _RPXExternal$_initLobbyScreen(width, height, rightSpaceWidth, bottomSpaceHeight)
	 {
	     RPXExternal.initApplicationScreen(width, height, rightSpaceWidth, bottomSpaceHeight);
	}
   
	function _RPXExternal$_initApplicationScreen(width, height, rightSpaceWidth, bottomSpaceHeight)
	{
		this.APP_DEFAULT_HEIGHT = height;
		this.APP_DEFAULT_WIDTH = width;
		
		this.RIGHT_SPACE_WIDTH = rightSpaceWidth;
		this.BOTTOM_SPACE_HEIGHT = bottomSpaceHeight;
		
		this.APP_ASPECT_RATIO = this.APP_DEFAULT_WIDTH / this.APP_DEFAULT_HEIGHT;
		this.APP_MIN_HEIGHT = 350;
		this.APP_MIN_WIDTH = this.APP_MIN_HEIGHT * this.APP_ASPECT_RATIO;
		this.SCREEN_ASPECT_RATIO = window.screen.width / window.screen.height;
		
		this._windowOffsetHeight = -1;
		this._windowOffsetWidth = -1;    	
		this._windowCurrentHeight = this.APP_DEFAULT_WIDTH;
		this._windowCurrentWidth = this.APP_DEFAULT_HEIGHT;
	}
	

    function _RPXExternal$_calculateWindowOffset()
    {    
    	if (window.outerHeight && window.outerWidth){
    		this._windowOffsetHeight = window.outerHeight - window.innerHeight;
            this._windowOffsetWidth = window.outerWidth - window.innerWidth;
    	}
    	else if (window.resizeTo)
        {
            window.resizeTo(this.APP_DEFAULT_WIDTH, this.APP_DEFAULT_HEIGHT);

            this._windowOffsetHeight = this.APP_DEFAULT_HEIGHT - window.document.documentElement.clientHeight;
            this._windowOffsetWidth = this.APP_DEFAULT_WIDTH - window.document.documentElement.clientWidth;
        }
    }
	
	function _RPXExternal$checkExit()
	{
		if (window.opener == null || window.opener.overrideTableCloseDialog)
			return null;
		else
		{
			try
			{
				return window.document.getElementById("tableApplication").checkClose()
			}
			catch (error)
			{
				return null;
			}			
		}	
	}
	
	function _RPXExternal$refreshPage()
    {		
		location.reload(true);
    } 

    function _RPXExternal$closeAllTableWindows()
    {
        for (var i in this._tableWindows)
        {
            this._tableWindows[i].close();            
            this._tableWindows[i] = null;            
            delete this._tableWindows[i];
        }
    }        
    
    function _RPXExternal$closeTableWindow(tableID)
    {
    	if (this._tableWindows[tableID] != undefined)
    	{    	
    		this._tableWindows[tableID].close();            
    		this._tableWindows[tableID] = null;           
    		delete this._tableWindows[tableID];
    	}	
    }
    
    function _RPXExternal$closeWindowID(windowID)
    {
    	if (this._openWindows[windowID] != undefined)
    	{
    		this._openWindows[windowID].close();
    		this._openWindows[windowID] = null;
    		delete this._openWindows[windowID];
    	}	
    }
    
    /**
     * Tables needs to be closed manualy before closing lobby
     */    
    function _RPXExternal$closeLobby()
    {    
    	try
    	{
    		window.document.getElementById("lobbyApplication").closeLobby();
    	}
    	catch (error)
    	{
    	}	
    }

    function _RPXExternal$closeWindow()
    {
        window.close();
    }

	//deprecated - not supported in FF 4
    function _RPXExternal$focusOpenerWindow()
    {
        window.opener.focus();
    }

    function _RPXExternal$focusWindow()
    {
        window.focus();
    }
    
    function _RPXExternal$focusTableWindow(tableID)
    {
    	if (this._tableWindows[tableID] != null)
    	{     	     		     		     
	    	this._tableWindows[tableID].focus();	    	
	    	if (this._tableWindows[tableID].document.getElementById('tableApplication') != null)	    		    		    	
	    		this._tableWindows[tableID].document.getElementById('tableApplication').focus();
	    }	
    	
    	/*
    	var callFromLobby = true;
    	if (arguments.length > 1)
    	{
    		if (fromTable == true)
    		{
    			//its called from table
    			window.opener.RPXExternal.focusTableWindow(tableID, false);
    			callFromLobby = false;
    		}
    	}
    
    	if (callFromLobby == true)
    	{
	     	if (this._tableWindows[tableID] != null)     	     		     		     
	    		this._tableWindows[tableID].focus();
    	}
    	*/
    }
    
    function _RPXExternal$isTableWindowFocused()
    {
    	return hasFocus; 
    }
    
    function _RPXExternal$historyInitialized()
    {
    	this._gameHistoryInitialized = true;
    	initializedEvent.fire(null, { message: 'initialization completed!'});
    }
    
    function _RPXExternal$historyPlaybackFinished()
    {
    	playbackFinishedEvent.fire(null, { message: 'history playback finished!'});
    }
    
    function _RPXExternal$isHistoryInitialized()
    {
    	return this._gameHistoryInitialized;
    }
    
    function _RPXExternal$getTableOpenStatus(tableID)
    {
     	for (var i in this._tableWindows)
        {
        	if (i == tableID)
        	{
        		// opera can't determine if the popup window is closed or not
        		if (window.opera)
        			return "unknown";
        		
        		if (!this._tableWindows[i].closed)
            		return "open";
            }	                                              
        }
        
        return "closed";
    }
    
    function _RPXExternal$loginWeb(sessionid)
	{
	  //this is currently not working because using "id=%SESSION%" in webchat makes the web lose its session with user (will be done later by Peter) 
		var bannerObject = document.getElementById("flashBanner");
		
		if (bannerObject != null)
		{
			var str = bannerObject.src.replace("%SESSION%", sessionid);
			bannerObject.contentWindow.location = str;
		}
		
	}

    function _RPXExternal$processTableClose(tableID)
    {
        this._tableWindows[tableID] = null;

        delete this._tableWindows[tableID];
    }
    
    function _RPXExternal$setHistoryPlay()
    {
      if (RPXExternal.isHistoryInitialized())
      {
      	document.getElementById("tableApplication").gamePlayButton();
      }
    }
    
    function _RPXExternal$setHistorySound()
    {
      if (RPXExternal.isHistoryInitialized())
      {
          document.getElementById("tableApplication").gameSoundButton();
      }
    }
    
    function _RPXExternal$setHistoryTimeline(option)
    {
    	if (RPXExternal.isHistoryInitialized())
      	{
      		document.getElementById("tableApplication").gameHistoryTimeline(option);
      	}
    }
    
    function _RPXExternal$setHistoryTimelineByIndex(position)
    {
      	if (RPXExternal.isHistoryInitialized())
      	{
      		document.getElementById("tableApplication").gameHistoryTimelineByIndex(position);
      	}
    }

    function _RPXExternal$onTableWindowClose(tableID)
    {
    	if (window.opener != null)
        	if (window.opener.document.getElementById("lobbyApplication") != null)
        		window.opener.document.getElementById("lobbyApplication").closeTable(tableID);
    }
    
    function _RPXExternal$onLobbyWindowResize()
    {
        window.clearTimeout(this._resizeTimer);

        this._resizeTimer = window.setTimeout(function() { RPXExternal.restoreAppWindowAspectRatio(isLobbyResizable); }, 300);
    }
    
    function _RPXExternal$onTableWindowResize()
    {
        window.clearTimeout(this._resizeTimer);

        this._resizeTimer = window.setTimeout(function() { RPXExternal.restoreAppWindowAspectRatio(isTableResizable); }, 300);
    }

    function _RPXExternal$openTableWindow(tableID, resizable)
    {
        isTableResizable = resizable;
        
        var tableWindow = this.openWindow("cardroom.php?tableID=" + tableID, "rpxTable" + tableID,
            "height=548,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,width=790", true, 0, tableID);

        if (tableWindow)
        {
            tableWindow.focus();
            
            this._tableWindows[tableID] = tableWindow;
        }
        else
            swfobject.getObjectById("lobbyApplication").closeTable(tableID); 
    }
        
    function _RPXExternal$openWindow(url, name, features, reportBlocker, windowID, tableID)
    {
        var win = window.open(url, name, features);
        
        if (windowID != 0)
          this._openWindows[windowID] = win;
		
		if (arguments.length != 6)
			tableID = -1;		
        
        if (reportBlocker)
        {
			if (!win)					             		        	        	        	
		    	this._reportPopupBlocker(url, name, features, tableID);	        			        	        	        		        			
			else
				if (navigator && (navigator.userAgent.toLowerCase()).indexOf("chrome") > -1)
					setTimeout(function(){checkChromePopUpBlocker(win, url, name, features, tableID);}, 1000)
		}				        	 	               

		if (tableID != -1)
        	return win;
    }
    
    function checkChromePopUpBlocker(win, url, name, features, tableID)
    {
		if (!win.closed && win.innerHeight < 10)
		{
			_RPXExternal$_reportPopupBlocker(url, name, features, tableID);
			win.close();
		}	
	}
    
    function _RPXExternal$_reportPopupBlocker(url, name, features, tableID)
    {    	
    	if (window.document.getElementById("lobbyApplication") != null)    	    	
    		window.document.getElementById("lobbyApplication").reportPopupBlocker(url, name, features, tableID);    		
    	else if (window.document.getElementById("tableApplication") != null)
    		window.document.getElementById("tableApplication").reportPopupBlocker(url, name, features);    
    }

    function _RPXExternal$minimizeTableWindow()
    {
        var actHeight = window.innerHeight || window.document.documentElement.clientHeight;
        var actWidth = window.innerWidth || window.document.documentElement.clientWidth;
        this.resizeWindow(576.642 - actWidth, 400 - actHeight);
    }

    function _RPXExternal$resizeWindow(width, height, target)
    {                                       
        target = target || window.self;
    
        if (window.resizeBy)
        {
           // if (this._windowOffsetWidth == -1)
            //    this._calculateWindowOffset();
            
            window.clearInterval(this._ieTimer);
            
            try
            {
                target.resizeBy(width, height);
            }
            catch (e)
            {
                this._ieTimer = window.setInterval(function () { RPXExternal.resizeWindow(width, height, target); }, 100);
            }
        }
        else
        {
            target.innerHeight = height;
            target.innerWidth = width;
        }
    }
    
    function _RPXExternal$restoreAppWindowAspectRatio(resize)
    {
        if (resize == false)
        {
            //if its not allowed to resize window, we force to get back to original window size
            
            var actHeight = window.innerHeight || window.document.documentElement.clientHeight;
            var actWidth = window.innerWidth || window.document.documentElement.clientWidth;
  
            this.resizeWindow(this.APP_DEFAULT_WIDTH + this.RIGHT_SPACE_WIDTH - actWidth, this.APP_DEFAULT_HEIGHT + this.BOTTOM_SPACE_HEIGHT - actHeight);
        }
        else
        {
	 	  var oldHeight = window.innerHeight || window.document.documentElement.clientHeight;
          var oldWidth = window.innerWidth || window.document.documentElement.clientWidth;

          var newHeight = window.innerHeight || window.document.documentElement.clientHeight;
          var newWidth = window.innerWidth || window.document.documentElement.clientWidth;
          
          //change width/height according to banners (space)
          newWidth -= this.RIGHT_SPACE_WIDTH;
          newHeight -= this.BOTTOM_SPACE_HEIGHT;
  
          if (Math.abs(this._windowCurrentHeight - newHeight) > Math.abs(this._windowCurrentWidth - newWidth))
              newWidth = Math.round(newHeight * this.APP_ASPECT_RATIO);
          else
              newHeight = Math.round(newWidth / this.APP_ASPECT_RATIO);
          
          if (this.SCREEN_ASPECT_RATIO > this.APP_ASPECT_RATIO && (newHeight > window.screen.height || newWidth > window.screen.width))
          {
              newHeight = window.screen.height;
              newWidth = Math.round(newHeight * this.APP_ASPECT_RATIO);
          }
  
          if (this.SCREEN_ASPECT_RATIO < this.APP_ASPECT_RATIO && (newHeight > window.screen.height || newWidth > window.screen.width))
          {
              newWidth = window.screen.width;
              newHeight = Math.round(newWidth / this.APP_ASPECT_RATIO);
          }
          
      	  newHeight = Math.max(newHeight, this.APP_MIN_HEIGHT);
      	  newWidth = Math.max(newWidth, this.APP_MIN_WIDTH);
          
          this._windowCurrentHeight = newHeight;
          this._windowCurrentWidth = newWidth;
          
          changeResolutionEvent.fire(null, { width: newWidth , height: newHeight});
          
          //change width/height back
          newWidth += this.RIGHT_SPACE_WIDTH;
          newHeight += this.BOTTOM_SPACE_HEIGHT;
          
          this.resizeWindow(newWidth - oldWidth , newHeight - oldHeight );
        }
    }

    function _RPXExternal$restoreTableWindow()
    {
        //this is here temporaly (old TableApplication.swf calls this method)
        
        var actHeight = window.innerHeight || window.document.documentElement.clientHeight;
        var actWidth = window.innerWidth || window.document.documentElement.clientWidth;
  
        this.resizeWindow(this.APP_DEFAULT_WIDTH + this.RIGHT_SPACE_WIDTH - actWidth, this.APP_DEFAULT_HEIGHT + this.BOTTOM_SPACE_HEIGHT - actHeight);
    }
    
    function _RPXExternal$restoreAppWindow()
    {
        var actHeight = window.innerHeight || window.document.documentElement.clientHeight;
        var actWidth = window.innerWidth || window.document.documentElement.clientWidth;
  
        this.resizeWindow(this.APP_DEFAULT_WIDTH + this.RIGHT_SPACE_WIDTH - actWidth, this.APP_DEFAULT_HEIGHT + this.BOTTOM_SPACE_HEIGHT - actHeight);
    }

    function _RPXExternal$setWindowTitle(value)
    {
        window.document.title = value;
    }

    function _RPXExternal$tileTableWindows()
    {
        var index = 0;
        var windowCount = 0;
        
        for (var i in this._tableWindows)
            windowCount++;
        
        var columnCount = (this.SCREEN_ASPECT_RATIO > 1 ? Math.ceil : Math.floor)(Math.sqrt(windowCount));


		var windowHeight = Math.round(window.screen.height / 2) - 40;
		var windowWidth = Math.round(windowHeight * this.APP_ASPECT_RATIO);

		if (windowWidth * columnCount > window.screen.width)
		{
			windowWidth = Math.round(window.screen.width / columnCount);
 	      	windowHeight = Math.round(windowWidth / this.APP_ASPECT_RATIO);
		}

        for (var i in this._tableWindows)
        {
	     	var oldHeight = this._tableWindows[i].innerHeight || this._tableWindows[i].document.documentElement.clientHeight;
	     	var oldWidth = this._tableWindows[i].innerWidth|| this._tableWindows[i].document.documentElement.clientWidth;
		
     	    this.resizeWindow(windowWidth - oldWidth, windowHeight - oldHeight , this._tableWindows[i]);
            
			this._tableWindows[i].moveTo((index % columnCount != 0 ? windowWidth : 0) * (index % columnCount), Math.floor(index / columnCount) *  ( window.screen.height / Math.ceil(windowCount / columnCount) ) );

            index++;
        }
    }
    
    
    function _RPXExternal$cascadeTableWindows()
    {
	    var defaultTableWidth = 790;			
		var defaultTableHeight = 548;    
	
	    var index = 0;
	    var windowCount = 0;
	    for (var i in this._tableWindows)
	        windowCount++;
	    
	    var lineX;
	    var lineY;
	    var lineXd;
	    var lineYd;
        
        //count diagonal line
        lineX = window.screen.width - defaultTableWidth;
        lineY = window.screen.height - defaultTableHeight;
      
        lineXd = lineX / (windowCount - 1);
        lineYd = lineY / (windowCount - 1);
      
        for (var i in this._tableWindows)
        {
            var oldHeight = this._tableWindows[i].innerHeight || this._tableWindows[i].document.documentElement.clientHeight;
            var oldWidth = this._tableWindows[i].innerWidth|| this._tableWindows[i].document.documentElement.clientWidth;
           
            this.resizeWindow(defaultTableWidth - oldWidth, defaultTableHeight - oldHeight , this._tableWindows[i]);
            this.focusTableWindow(i);
            this._tableWindows[i].moveTo(index * lineXd, index * lineYd);
            index++;
        }
    }

_RPXExternal.prototype = {
    _calculateWindowOffset: _RPXExternal$_calculateWindowOffset, 
    cascadeTableWindows: _RPXExternal$cascadeTableWindows,   
    closeAllTableWindows: _RPXExternal$closeAllTableWindows,    
    closeLobby: _RPXExternal$closeLobby,
    closeTableWindow: _RPXExternal$closeTableWindow,
    closeWindowID: _RPXExternal$closeWindowID,
	checkExit: _RPXExternal$checkExit,
//  closeTableWindow: _RPXExternal$closeTableWindow,
    closeWindow: _RPXExternal$closeWindow,
    focusOpenerWindow: _RPXExternal$focusOpenerWindow,
    focusTableWindow: _RPXExternal$focusTableWindow,
    focusWindow: _RPXExternal$focusWindow,
    historyInitialized: _RPXExternal$historyInitialized,
    historyPlaybackFinished: _RPXExternal$historyPlaybackFinished,
    isHistoryInitialized: _RPXExternal$isHistoryInitialized,
    getTableOpenStatus: _RPXExternal$getTableOpenStatus,
    loginWeb: _RPXExternal$loginWeb,
    initApplicationScreen: _RPXExternal$_initApplicationScreen,
    initTableScreen: _RPXExternal$_initTableScreen,
    initLobbyScreen: _RPXExternal$_initLobbyScreen,
    isTableWindowFocused: _RPXExternal$isTableWindowFocused,
    minimizeTableWindow: _RPXExternal$minimizeTableWindow,
    processTableClose: _RPXExternal$processTableClose,
    _reportPopupBlocker: _RPXExternal$_reportPopupBlocker,
    onTableWindowClose: _RPXExternal$onTableWindowClose,
    //onAppWindowResize: _RPXExternal$onAppWindowResize,
    onLobbyWindowResize: _RPXExternal$onLobbyWindowResize,
    onTableWindowResize: _RPXExternal$onTableWindowResize,
    //onTableWindowResize: _RPXExternal$onTableWindowResize,
    openTableWindow: _RPXExternal$openTableWindow,
    openWindow: _RPXExternal$openWindow,
	refreshPage: _RPXExternal$refreshPage,
    resizeWindow: _RPXExternal$resizeWindow,
    restoreAppWindow: _RPXExternal$restoreAppWindow,
    restoreAppWindowAspectRatio: _RPXExternal$restoreAppWindowAspectRatio,
    restoreTableWindow: _RPXExternal$restoreTableWindow,
    //restoreTableWindowAspectRatio: _RPXExternal$restoreTableWindowAspectRatio,
    setHistoryPlay: _RPXExternal$setHistoryPlay,
    setHistorySound: _RPXExternal$setHistorySound,
    setHistoryTimeline: _RPXExternal$setHistoryTimeline,
    setHistoryTimelineByIndex: _RPXExternal$setHistoryTimelineByIndex,
    setWindowTitle: _RPXExternal$setWindowTitle,
    tileTableWindows: _RPXExternal$tileTableWindows
};

var RPXExternal = new _RPXExternal();

