var Config = {
    apiDomain : "content.guardianapis.com"
}


function ApiQuery() {
    this.rootUrl = "http://" + Config.apiDomain;
    this.params = {};
    this.endpoint = "";

    this.updateFromPath = function(path) {
        var parts = path.split('?');
        this.endpoint = parts[0];

        
        this.params = $.deparam.querystring(parts[1]);
        if(!this.params['format']) {
            this.params['format'] = 'json';
            if (this.endpoint === "/") {
                this.endpoint = "/search";
            }
        }

        delete this.params['callback']
    }

    this.updateFromApiUrl = function(apiUrl) {
        this.updateFromPath(apiUrl.replace(this.rootUrl, ''));               
    }

    this.updateParams = function(newParams) {
        $.extend(this.params, newParams);
    }

    this.deleteParams = function(paramNames) {
        for (i in paramNames) {
            delete this.params[paramNames[i]];
        }
    }

    this.getParam = function(paramName) {
        return this.params[paramName];
    }

    this.setParam = function(paramName, paramValue) {
        if(paramValue) {
            this.params[paramName] = paramValue;
        } else {
            delete this.params[paramName];
        }
    }

    this.toString = function() {
        return this.rootUrl + this.getPath();
    }

    this.getPath = function() {
        return jQuery.param.querystring(this.endpoint, this.params, 0 );
    }

    this.isSearchQuery = function() {
        return this.endpoint == "/search";
    }

    this.isPaginated = function() {
        return this.endpoint == "/search" || this.endpoint == "/tags" || this.endpoint == "/folders";
    }

    this.getResults = function(successCallback, errorCallback) {
        var apiQuery = this;

        $.ajax({
            url: this.toString(),
            dataType: 'jsonp',
            success:
                function(data) {
                    successCallback(apiQuery, data);
                },
            error: errorCallback
        });
    }
}


