﻿/* urlBuilder */
/* used to serve up the correct url for AJAX / JSON calls */

/// create the correct url builder for the current context (e.g. client / app)
function createUrlBuilder(){
    var ab = new appUrlBuilder();
    return isUsingProxy()
            ? new proxyUrlBuilder(ab) 
            : ab;
};


// this urlBuilder routes all requests to the application via the proxy
this.proxyUrlBuilder = function(urlBuilder){

    this.buildJsonUrl = function(qs){
        var uri = urlBuilder.buildJsonUrl(qs);
        var result = getProxyUrl(uri);
        return result;
    };
    
    this.buildAjaxCommandUrl = function(qs){
        var uri = urlBuilder.buildAjaxCommandUrl(qs);
        var result = getProxyUrl(uri);
        return result;
    };
    
};

// this urlBuilder routes all requests to the application directly
this.appUrlBuilder = function(){

    this.buildJsonUrl = function(qs){
        qs = qs.indexOf('?') == 0 ? qs : ('?' + qs);
        return APPLICATION_ROOT + "json.aspx" + qs + '&' + getUniqueParameter();    
    };
    
    this.buildAjaxCommandUrl = function(qs){
        qs = qs.indexOf('?') == 0 ? qs : ('?' + qs);
        return APPLICATION_ROOT + "aspx/ajax_command_receiver.aspx" + qs + '&' + getUniqueParameter(); 
    };
};

// get the proxy url
function getProxyUrl(uri){
    if(null == PROXY_RELATIVE_URL || typeof(PROXY_RELATIVE_URL) == 'undefined' || PROXY_RELATIVE_URL == ''){
        throw('PROXY_RELATIVE_URL is empty or undefined');
    };
    return PROXY_RELATIVE_URL + '?' + getUniqueParameter() + '&uri=' + encodeURIComponent(uri);
}

function getUniqueParameter(){
    return 'tx=' + new Date().getTime();
};


