if (typeof MQA == 'undefined') { window.MQA = {}; }

(function() {
    var _makeRequest =  function(url, serverUrl, callbackId, id, done) {
        var script = document.createElement('script'), data = "";
        
        data = 'http://' + serverUrl + '/longurl/v1/?data=' + encodeURIComponent(url) 
            + "&callback=MQA.LongURL.CALLBACKS['" + callbackId + "']";
        
        if (id) { 
            data += '&id=' + id; 
        }
        
        if (done) {
            data += '&done=true'; 
        }
        
        script.type = 'text/javascript';
        script.src = data;
        document.body.appendChild(script);
    },
    
    _salt = 0,
    
    _makeCallbackId = function() {
        return ('c' + new Date().getTime() + (++_salt));
    };
    
    /**
     * Creates a LongURL object to handle sending a long url in parts to the server.
     *
     * @param {String} url  the long url to send
     * @param {Object} options  options to configure the object
     *     maxLength: (Integer) the max length to that each chunk of the url can be, defaults to 1900
     *     server: {String} the host:port for the long url service, defaults to platform.beta.mapquest.com
     */
    MQA.LongURL = function(url, options) {
        if (! options) {
            options = {};
        }
        
        this.url = url;
        this.maxLength = options.maxLength || 1900;
        this.server = options.server || 'platform.beta.mapquest.com';
        this.parts = [];
        this.callbackId = _makeCallbackId();
    };
    
    MQA.LongURL.prototype = {        
        send: function() {
            var len = this.url.length, 
                start = 0,
                self = this;
            
            while (start < len) {
                this.parts.push(this.url.substring(start, (start + this.maxLength)));
                start = start + this.maxLength;
            }
            
            MQA.LongURL.CALLBACKS[this.callbackId] = function(response) {
                self.getNext(response);
            };
            
            this.getNext(null);
        },
        
        getNext: function(response) {
            var part = this.parts.shift(), id, done = false;
            
            if (! part) {
                return;
            }
            
            if (response && response.id) {
                id = response.id;
            }
            
            if (this.parts.length == 0) {
                done = true;
            }
            
            _makeRequest(part, this.server, this.callbackId, id, done);
        }
    };
    
    // object to hold dynamically generated callbacks
    MQA.LongURL.CALLBACKS = {};
})();
