﻿
function AjaxDataBuilder(includeBasketState) {

    this.names = new Array();
    this.values = new Array();

    ///
    /// Guards a method by throwing an exception if a parameter is null when it should not be passed
    /// in null.
    ///
    this.Guard = function(parameterName, value)
    {
    	if (value == undefined || value == null)
    	{
    		throw ("parameter " + parameterName + " can not be null");
    	}
    }


    this.Add = function(name, value) {
        /// <summary>
        /// Adds data to the builder
        /// </summary>
        /// <param name="name">The name of the posted field.</param>
        /// <param name="value">The value of the posted field.</param>

        this.Guard("name", name);
        this.Guard("value", value);

        this.names.push(name);
        this.values.push(value);

        return this;
    }

    this.Build = function() {
        /// <summary>
        /// Builds the data string for post or get
        /// </summary>

        //  jquery causes a 411 in firefox if you do not set post data to something so we
        //  must default the post data to a blank array.
        var data = "{}";

        // Basket state should be added by default
        if (includeBasketState || includeBasketState == undefined) {
            // Add the basket state by default
            this.names.push("__BasketState");
            this.values.push($('#__BasketState').val());
        }

        var index = 0;
        var count = this.names.length;

        for (index = 0; index < count; index++) {

            var name = this.names[index];
            var value = escape(this.values[index]);

            var assignment = name + "=" + value;

            if (index == 0) {
                data = assignment;
            }
            else {
                data = data + "&" + assignment;
            }
        }


        return data;

    }

    return this;

}





