﻿///
/// Encapsulates an AJAX request in a command that has the ability to retry on failure
///
function AjaxPostCommand(url, dataBuilder, successCallback, errorCallback, timeoutInMilliseconds, retries, dataType) {
	/// <summary>Encapsulates an AJAX request in a command that has the ability to retry on failure</summary>
	/// <field name="dataType" type="string" optional="true">The data type we expect back from the request. See JQuery AJAX documentation</field>

    var dataBuilder = dataBuilder;
    var postData = {};
    var url = url;

    if (retries == undefined) {
        retries = 3;
    }

    if (timeoutInMilliseconds == undefined) {
    	timeoutInMilliseconds = AjaxPostCommand.DefaultTimeout;
    }
          
    var type = "POST";
        
    // Records the number of execution attempts
    var attemptCount = 0;

    // Records if the command is executing
    var executing = false;
    
    // Executes the ajax call and sets the attempt count
    function executeAjax () {
        attemptCount = attemptCount + 1;
        $.ajax(
                {
                    url: url,
                    cache: false,
                    data: postData,
                    type: type,
                    timeout: timeoutInMilliseconds,
                    success: successHandler,
                    error: errorHandler,
                    dataType: dataType
                }
            )
    }

    // Invokes the success callback
    function successHandler(data)
    {
    	// Only invoke the callback if its defined
    	if (successCallback != undefined)
    	{
    		try
    		{
    			successCallback(data);
    		}
    		catch (e)
    		{
    			if (typeof(console) != "undefined")
    			{
    				console.log('Error in AJAX success callback: ' + e);
    			}
    			// Do nothing because the callback should have handled the error
    		}

    	}

    	executing = false;
    }

    // Handles any errors and invokes the error callback when the number of retries have been exceeded
    function errorHandler(XMLHttpRequest, textStatus, errorThrown) {

        if (attemptCount < retries) {
            // Try again
            executeAjax()
        }
        else {
        
            // Only invoke the callback if its defined
            if (errorCallback != undefined) {

                try {

                    errorCallback(XMLHttpRequest, textStatus, errorThrown);
                    
                }
                catch (e) {
                    // Do nothing because the callback should have handled the error
                }

            }

            executing = false;
            
        }
    }

    ///
    /// Executes the command
    ///
    this.Execute = function()
    {
    	// Build the post data using the builder
    	postData = dataBuilder.Build();

    	// let it be know that we are executing
    	executing = true;

    	// Execute the ajax call
    	executeAjax();
     }

     this.ExecuteStep5 = function() 
     {
         // Build the post data using the builder
         postData = unescape(dataBuilder.Build());
         
         // let it be know that we are executing
         executing = true;

         // Execute the ajax call
         executeAjax();
     }

    ///
    /// Determines if the command has finished executing
    //
    this.HasExecutionCompleted = function() {
        return !executing;
    }

    return this;
        
}

/// Static fields

AjaxPostCommand.DefaultTimeout = 30000;
