var lastPurchaseAmount = false;
var chipBalance = 0;
var resetTimeout = -1;
var actionsArray = new Array( "purchase", "cashout", "promotions" );
var currentAction = "";

/*
 * Returns an new XMLHttpRequest object, or false if the browser doesn't support it
 */
function newXMLHttpRequest()
{
  var xmlreq = false;
	try
	{
		xmlreq=new ActiveXObject( "Msxml2.XMLHTTP" );
	}
	catch ( e )
	{
		try
		{
			xmlreq=new ActiveXObject( "Microsoft.XMLHTTP" );
		}
		catch ( e2 )
		{
			xmlreq=null;
		}
	}
	if( !xmlreq && typeof XMLHttpRequest != "undefined" )
	{
		xmlreq = new XMLHttpRequest();
	}
    return xmlreq;
}


 /*
  * Returns a function that waits for the specified XMLHttpRequest
  * to complete, then passes it XML response to the given handler function.
  * req - The XMLHttpRequest whose state is changing
  * responseXmlHandler - Function to pass the XML response to
  */
function getReadyStateHandler( xmlHttpRequest, responseXmlHandler )
{
	// Return an anonymous function that listens to the XMLHttpRequest instance
	return function ()
    {
        // If the request's status is "complete"
        if ( xmlHttpRequest.readyState == 4 )
        {
            // Check that we received a successful response from the server
            if ( xmlHttpRequest.status == 200 )
            {
                // Pass the XML payload of the response to the handler function.
                responseXmlHandler( xmlHttpRequest.responseXML );
            }
            else
            {
                // An HTTP problem has occurred
                alert( "HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText );
            }
        }
    }
}


/*
* Allows user to purchase more chips
*/
function purchaseChips() 
{
	
	currentAction = "purchase";
    var xmlHttpRequest = newXMLHttpRequest();
    if ( !xmlHttpRequest ) {
        alert( "Javascript could not get a handle on the XMLHttpRequest object." );
        return;
    }
    
    // disable purchase buttons after they're clicked once
    disableButton( "purchase-button", true );
    disableButton( "purchase-cancel" );
    
	
    // set the value of the "last purchase amount" for populating the input field next time the user wants to make a purchase
    lastPurchaseAmount = document.purchaseForm.amount.value;
    
    try 
    {
        var url = "/servlets/casinoAjax?hash=" + Math.random() + "&action=purchaseChips&amount=" + document.purchaseForm.amount.value;
        xmlHttpRequest.open( "POST", url, true );
        xmlHttpRequest.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
        xmlHttpRequest.onreadystatechange = getReadyStateHandler( xmlHttpRequest, updatePurchase );
        xmlHttpRequest.send( null );
    }
    catch (e)
    {
        alert( "error while sending: " + e.description );
    }
    return true;
}


/*
* sends the response of purchaseChips() to be handled and displayed on the page
*/
function updatePurchase( purchaseXML ) 
{
    var err = handleError( purchaseXML, "purchase" );
    
    if ( err == 0 )
    {
        var purchase = purchaseXML.getElementsByTagName( "purchase" ).item(0);
        displayError( false, purchase, "purchase" );
        
        // update balance in RTG flash client
        refreshBalanceInGame(); 
    }
    
    // re-enable purchase buttons after the XML response has come back
    enableButton( "purchase-button", "Purchase" );
    enableButton( "purchase-cancel" );
	
	refreshBalance();	
}


/*
* Allows user to cash out some/all of their chips
*/
function cashoutChips() 
{
	currentAction = "cashout";
    var xmlHttpRequest = newXMLHttpRequest();
    if ( !xmlHttpRequest ) {
        alert( "Javascript could not get a handle on the XMLHttpRequest object." );
        return;
    }
    // disable cashout buttons as soon as they're pressed once
    disableButton( "cashout-button", true );
    disableButton( "cashout-cancel" );

    try 
    {
        var url = "/servlets/casinoAjax?hash=" + Math.random() + "&action=cashoutChips&amount=" + document.cashoutForm.amount.value;
        xmlHttpRequest.open( "POST", url, true );
        xmlHttpRequest.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
        xmlHttpRequest.onreadystatechange = getReadyStateHandler( xmlHttpRequest, updateCashout );
        xmlHttpRequest.send( null );
    } catch ( e ) {
        alert( "error while sending" );
    }
    return true;
}


/*
* sends the response of cashoutChips() to be handled and displayed on the page
*/
function updateCashout( cashoutXML ) 
{
    var err = handleError( cashoutXML, "cashout" );
    if ( err == 0 )
    {
        var cashout = cashoutXML.getElementsByTagName( "cashout" ).item(0);
        displayError( false, cashout, "cashout" );
        
        // update balance in RTG flash client 
        refreshBalanceInGame(); 
    }
    
    // re-enable cashout buttons
    enableButton( "cashout-button", "Cashout" );
    enableButton( "cashout-cancel" );
	
	refreshBalance();

}


/*
* Send request for current balance
*/
function refreshBalance() 
{
    var xmlHttpRequest = newXMLHttpRequest();
    if ( !xmlHttpRequest )
    {
        alert( "Javascript could not get a handle on the XMLHttpRequest object." );
        return;
    }
    
    try 
    {
        var url = "/servlets/casinoAjax?hash=" + Math.random() + "&action=getPlayerBalance";
        xmlHttpRequest.open( "POST", url, true );
        xmlHttpRequest.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
        xmlHttpRequest.onreadystatechange = getReadyStateHandler( xmlHttpRequest, updateRefreshBalance );
        xmlHttpRequest.send( null );

    }
    catch ( e )
    {
        alert( "error while sending" );
    }
    return true;
}


/*
* When the response comes back from refreshBalance(), update the page with it
*/
function updateRefreshBalance( refreshBalanceXML ) 
{
    var err = handleError( refreshBalanceXML );
    if ( err == 0 )
    {
        var refreshBalance = refreshBalanceXML.getElementsByTagName( "player_balance" ).item(0);

        // update the variable holding the player's chip balance
//        chipBalance = refreshBalance.getAttribute( "withdrawable_chip_balance" );
//        document.cashoutForm.amount.value =  chipBalance;

		displayBalances( refreshBalance, currentAction );
    }
}


/*
* checks to see which balances should be displayed and then updates them with the values from the xml
*/
function displayBalances( balanceXML, action )
{
	// update eCash balances (including the values in the dashboard at the top of the page)
	$( "#eCash" ).html(balanceXML.getAttribute( "ecash_balance" ));
    $( "#eCashBonus" ).html(balanceXML.getAttribute( "ecash_bonus_balance" ));
	$( "#global-account-balance" ).html(balanceXML.getAttribute( "ecash_balance" ));

	// only display extra information if withdrawable chips and chip balance don't match
	if ( balanceXML.getAttribute( "withdrawable_chip_balance" ) != balanceXML.getAttribute( "chip_balance" ) && action=="cashout" )
	{
		$( "#casino-balances" ).show();
        $( "#playableCasinoChips" ).html( balanceXML.getAttribute( "chip_balance" ));
        $( "#withdrawableChips" ).html(balanceXML.getAttribute( "withdrawable_chip_balance" ));
        $( "#bonusChips" ).html(balanceXML.getAttribute( "bonus_chip_balance" ));
        $( "#rolloverRemaining" ).html(balanceXML.getAttribute( "rollover_chip_balance" ));
	}
	else
	{
		$( "#casino-balances" ).hide();
	}
}

/*
* checks response for errors and sends them off to be displayed accordingly with displayError()
*/
function handleError( whateverXml, action )
{
     var errorNodeList = whateverXml.getElementsByTagName( "error" );
     if ( errorNodeList.length == 0 ) 
     {
        return 0; // '0' is good!
     }
     else
     {
        var errorItem = errorNodeList.item(0);
        displayError( true, errorItem, action );
        return -1;
     }
}


/*
* Brings cashier back to the default state (with the two buttons "Purchase Chips" and "Cashout Chips")
*/
function resetCashier()
{
	currentAction = "";
    if ( resetTimeout != -1 )
    {
        window.clearTimeout( resetTimeout );
    }

    // these arrays hold all the elements that need to be handled one way or another
    // some of them need to be visible, some of them need to be hidden
    var displayArray = new Array( "cashier-help-link", "game-objectives-tabs" );
   // var visibilityArray = new Array( "purchase-heading", "cashout-heading", "cashier-help-link" );
	var visibilityArray = new Array( "cashier-help-link" );
    var hideArray = new Array( "cashier-step-two", "cashier-step-three", "purchase-success", "cashout-success", "cashier-balance-info", "cashier-error", "casino-balances", "purchase-chips-tabs", "cashout-chips-tabs", "promotions-chips-tabs", "promotions-block" );

    // display all blocks specified in displayArray
    for ( i=0 ; i<displayArray.length ; i++ )
    {
        if ( $( "#"+displayArray[i] ) )
        {
            $( "#"+displayArray[i] ).show();
        }
        
    }
    // make visible all blocks that may have been hidden
    for ( i=0 ; i<visibilityArray.length ; i++ )
    {
        if ( $( "#"+visibilityArray[i] ) )
        {
            $( "#"+visibilityArray[i] ).show();
        }
    }
	
	
	
    // hide all blocks specified in array
    for ( i=0 ; i<hideArray.length ; i++ )
    {
        if ( $( "#"+hideArray[i] ) )
        {
            $( "#"+hideArray[i] ).hide();
        }
    }
    
    // reset the css classes of input boxes (in case there were errors, in which case their classes change)
    document.purchaseForm.amount.className = "text";
    document.purchaseForm.amount.value = "";
    document.cashoutForm.amount.className = "text";
    document.cashoutForm.amount.value = "";
}


/*
* called from the default cashier state when user selects either "Purchase Chips" or "Cashout Chips"
* action is either "cashout" or "purchase"
*/

$(function(){
	//jquery - if promotions-chips-tabs id exists, set default on after dom is loaded
	if ($("#promotions-chips-tabs").length){
		showPromotion();
	}
});
	function showPromotion(){
		$( "#purchase-block" ).hide();
		$( "#cashout-block" ).hide();
		$( "#dollar-sign" ).hide();
		
		$( "#cashier-help-link" ).hide();
		$( "#cashier-error" ).hide();
		$( "#promotions-block" ).hide();
	    $( "#cashier-step-two" ).show();
		$( "#cashier-balance-info" ).hide();
		$( "#promotions-block" ).show();
		
		//hide /show the tab panels for the navigation of the bottom panel
	    $( "#game-objectives-tabs" ).hide();
		$( "#purchase-chips-tabs" ).hide();
		$( "#cashout-chips-tabs" ).hide();
		$( "#promotions-chips-tabs" ).hide();
		$( "#promotions-chips-tabs" ).show();
	}
	

function cashierStepTwo( action )
{
	currentAction = action;
    // make sure the eCash Balance and eCash Bonus Balance are updated
    refreshBalance();
    
    // if they've made a purchase before, default the input box value to this ammount
    if ( lastPurchaseAmount )
    {
        document.purchaseForm.amount.value = lastPurchaseAmount;
    }
    
    // handle the visual elements on the page that need to be displayed or hidden
    //document.getElementById( "cashier-step-one" ).hide();
    $( "#cashier-help-link" ).hide();
	$( "#promotions-block" ).hide();
    $( "#cashier-step-two" ).show();
    //document.getElementById( action + "-heading" ).show();
    $( "#" + action + "-block" ).show();
    $( "#cashier-balance-info" ).show();
   
    //hide /show the tab panels for the navigation of the bottom panel
    $( "#game-objectives-tabs" ).hide();
	$( "#purchase-chips-tabs" ).hide();
	$( "#cashout-chips-tabs" ).hide();
	
	$( "#promotions-chips-tabs" ).hide();
	
	$( "#" + action + "-chips-tabs" ).show();
		
		
		
    // put the focus in the ammount text box
   	var inputText = eval("document." + action + "Form.amount");
   	inputText.focus();
   	inputText.select();

    // hide the form elements of other cashier option (i.e. if the user's selected "cashout" we need to hide the "purchase" elements)
    for ( i=0 ; i<actionsArray.length ; i++ )
    {
        if ( actionsArray[i] != action )
        {
            //document.getElementById( actionsArray[i] + "-heading" ).hide();
            $( "#" + actionsArray[i] + "-block" ).hide();
        }
    }    
}

 
/*
* disables button after they are pushed so let user know the transaction is in progress
* changeText is Boolean
*/
function disableButton( buttId, changeText )
{
    document.getElementById( buttId ).disabled = true;
    document.getElementById( buttId ).className = "button button-disabled";
    if ( changeText ) {
        document.getElementById( buttId ).value = "Processing...";
    }
}


/*
* enables button after XML response has been recieved
* label is a String value
*/ 
function enableButton( buttId, label )
{
    document.getElementById( buttId ).disabled = false;
    document.getElementById( buttId ).className = "button";
    if ( label ) {
        document.getElementById( buttId ).value = label;
    }
}


/*
* after the XML response is recieved, this function handles what to do with them
* isError is Boolean
* actionXML is the returned XML
* action is either "cashout" or "purchase"
*/
function displayError( isError, actionXml, action )
{

    // if isError is false, then we are displaying a success message
    if ( !isError ) {
	
        // if user cashes out ALL of their chips, display a "successfully cashed out" page and hide the game
        if ( actionXml.getAttribute( "zero_chips" ) == "true" && action == "cashout" )
        {
            // handle the visual elements on the page 
            $("#flash-game").hide();
            //document.getElementById("cashier-step-one").hide();
            $("#cashier-help-link").hide();
            $("#cashier-success-block").show();
            
            // hide the denominations bar (slots/video-poker) if there is one
            $( "#flash-game-denominations" ).hide();
        }
        else
        {
            if ( action == "purchase" && chipBalance == 0 )
            {
                $( "#flash-game-denominations" ).show();
            }
            
                $( "#flash-game" ).show();
                $( "#cashier-low-balance" ).hide();
            	$( "#cashier-success-block" ).hide();
           
        }

        // display the cashier-step-three block and the success block since there are no errors
        $( "#cashier-error" ).hide();
        $( "#cashier-step-three" ).show();
        $( "#" + action + "-success" ).show();
        $( "#cashier-step-two" ).hide();
        
        // update the eCash and eCash Bonus values with the new totals
		displayBalances( actionXml, action );
        
        // reset the cashier after 5 seconds if the user doesn't do anything
        resetTimeout = window.setTimeout( "resetCashier()", 5000 );
    }
    else // handle the error
    {
        // change text field's css class to display error
		try {
	        var inputText = eval( "document." + action + "Form.amount" );
	        inputText.className = "text input-error";
    	    inputText.focus();
        	inputText.select();
		} catch ( err ) {
			// Needs to handle error case
		}
        
        // display the error message block
        $( "#cashier-error" ).show();
        
        // if the user's session has expired and they are logged out (err 5), display a link to the login page
        if ( actionXml.getAttribute( "code" ) == 5 )
        {
            var theError = "You are not currently signed in. Please <a href=\"/account/app/Login\">sign in to your account.</a>";
        }
        else
        {
            var theError = actionXml.getAttribute( "msg" );
        }
        $( "#cashier-error" ).html(theError);
		
    }
}


/*
* since IE and Netscape refer to the movie object differently, this returns the proper syntax
*/
function getMovie( movieName )
{ 
    if ( navigator.appName.indexOf( "Microsoft" ) !=-1 )
    {
        return window[movieName];
    }
    else
    {
        return document[movieName];
    }
}


/*
* Updates the balance in RTG's flash game
*/
function refreshBalanceInGame()
{
	if ( document.reloadGame == true )
	{
		document.location.reload(true);
	}
	else 
	{
		var flash_client = (document.getElementById("flash_client") ? "flash_client" : "flash_client_casbo");
		if (document.getElementById("flash-game").style.display != "none")
		{
			var movie = getMovie( flash_client );
			var casbo = flash_client=="flash_client_casbo" ? true : false;
			try
			{
				if (casbo) {
					movie.RefreshBalance();
				} else {
					movie.TGotoFrame("/jsObject", 1);
				}
			}
			catch ( e )
			{
				//alert("Couldn't update movie " + e.message);
			}
		}
	}
}