/*jslint forin:true */

/**
 * The default constructor for the URLBuilder object
 * @param base the base url that everything else should be appended to.
 */
function URLBuilder(base)
{
    this._base       = base;
    this._params     = [];
    this._anchor     = null;
    this._paramCount = 0;
}

/**
 * Adds a parameter to the list of parameters that will be appended
 * to the query string of the url
 * @param name the name of the parameter
 * @param value the parameter's value
 */
URLBuilder.prototype.addParam = function(name, value)
{
    if (typeof(value) != "undefined")
    {
        this._params[name] = encodeURIComponent(value);
        this._paramCount++;
    }
};

/**
 * Sets the anchor value of the URL
 * @param anchor the name of the anchor
 */
URLBuilder.prototype.setAnchor = function(anchor)
{
    if (typeof(anchor) != "undefined")
    {
        this._anchor = anchor;
    }
};

/**
 * Builds and returns the url
 * @return the URL
 */
URLBuilder.prototype.toString = function()
{
    var ret = this._base;

    if (this._paramCount > 0)
    {
        if (ret.indexOf('?') < 0) {
            ret += "?";
        } else {
            ret += "&";
        }
        var i = 0;
        for (var name in this._params) 
        {
            ret += name + "=" + this._params[name];
            if (i < this._paramCount-1)
            {
                ret += "&";
            }
            ++i;
        }
    }

    if (this._anchor !== null) {
        ret += "#" + this._anchor;
    }

    return ret;
};