﻿/// <reference path="../Content/Scripts/jquery.vsdoc.js" />
/// the last parameter in the function signature is intended to make the symbol '$' a local variable to the function

function AjaxGetCommand(url, dataBuilder, successCallback, errorCallback, timeoutInMilliseconds)
{
	/// <summary>Encapsulates an AJAX GET request in a command</summary>
	/// <param name="url" type="string">The URL to request</param>
    /// <param name="dataBuilder" type="string">Builds the querystring parameters to send with the request</param>
	/// <param name="successCallback" type="function">The callback function to execute on a successful response</param>
	/// <param name="errorCallback" type="function">The callback function to execute if an error occurs</param>
	/// <param name="timeoutInMilliseconds" type="Number" integer="true">The timeout to place on the request, in milliseconds</param>
    var $ = jQuery;
    var dataBuilder = dataBuilder;
    var requestData = {};
	var url = url;

	if (timeoutInMilliseconds == undefined)
	{
		timeoutInMilliseconds = AjaxGetCommand.DefaultTimeout;
	}

	var type = "GET";

	// Records if the command is executing
	var executing = false;

	function executeAjax()
	{
		/// <summary>Executes the ajax call</summary>
		
		$.ajax(
                {
                	url: url,
                	cache: false,
                	data: requestData,
                	type: type,
                	timeout: timeoutInMilliseconds,
                	success: successHandler,
                	error: errorHandler
                }
            );
	}

	function successHandler(data)
	{
		/// <summary>Invokes the success callback</summary>

		// Only invoke the callback if its defined
		if (successCallback != undefined)
		{
			try
			{
				successCallback(data);
			}
			catch (e)
			{
				// Do nothing because the callback should have handled the error
			}


        }

        executing = false;

	}

	function errorHandler(XMLHttpRequest, textStatus, errorThrown)
	{
		/// <summary>Handles any errors and invokes the error callback</summary>
		
		// 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;
		
	}

	this.Execute = function() {
	    /// <summary>Executes the command</summary>

	    // Build the request data using the builder
	    requestData = 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

AjaxGetCommand.DefaultTimeout = 30000;
