/// <reference path="ITransport.ts" />
/// <reference path="../../net/Uri.ts" />
/// <reference path="../../econdaConfig.ts" />
/// <reference path="../../env/UserAgent.ts" />
/// <reference path="../Response.ts" />
/// <reference path="../Request.ts" />
var econda;
(function (econda) {
    var ajax;
    (function (ajax) {
        var transport;
        (function (transport) {
            var Response = econda.ajax.Response;
            var Uri = econda.net.Uri;
            /**
             * Legacy x-domain requests using window.name transport. There is not reason to directly use this class. See {@link econda.Ajax} for details.
             * This transport supports only GET requests.
             *
             * How it works: create invisible iframe; load data document in iframe, document must set data to window.name; navigate back to a document with same origin and read data from window.name
             *
             * @class econda.ajax.transport.WindowName
             */
            var WindowName = (function () {
                // Constructor
                function WindowName() {
                    /**
                     * Reference to iframe used for this request
                     * @property {HTMLElement} _iframe
                     * @private
                     */
                    this._iframe = null;
                    /**
                     * Reference to ajax request object. That's where we have to read our data from and pass the response to
                     * @property {econda.ajax.Request} _request
                     * @private
                     */
                    this._request = null;
                    /**
                     * Index of this instance. We'll use it to have a unique number for our iframe names
                     * @property {Number} _instanceIndex
                     * @private
                     */
                    this._instanceIndex = null;
                    /**
                     * Current state of request
                     * @property {Number} _state
                     * @private
                     */
                    this._state = 0;
                    this._instanceIndex = WindowName._instanceCount++;
                }
                WindowName.setBlankUri = function (uri) {
                    econdaConfig.blankUri = new Uri(uri);
                };
                /**
                 * Get blank uri.
                 * @static
                 * @returns {econda.net.Uri}
                 */
                WindowName.getBlankUri = function () {
                    if (typeof econdaConfig != 'undefined') {
                        var c = econdaConfig;
                        if (typeof c.blankUri != 'undefined') {
                            return new Uri(c.blankUri);
                        }
                    }
                    return new Uri(WindowName.defaultBlankUri);
                };
                /**
                 * Set reference to request
                 * @param {econda.ajax.Request} request
                 * @private
                 */
                WindowName.prototype.setRequest = function (request) {
                    this._request = request;
                };
                /**
                 * Nothing to do in init.
                 */
                WindowName.prototype.init = function () {
                    // nothing to do
                };
                /**
                 * Send request
                 */
                WindowName.prototype.send = function (request) {
                    var uri = this._request.getUri();
                    uri = uri.appendParams({ windowname: "true" });
                    uri = uri.appendParams(this._request.getParams());
                    this.setupIFrame();
                    econda.debug.log('Sending request using window.name transport to uri: ' + uri);
                    this.navigateIFrameToTarget(uri);
                };
                /**
                 * True, if current browser supports the initialized request using this transport
                 * @returns {Boolean}
                 */
                WindowName.prototype.isSupportedRequest = function () {
                    // should work with all browsers ??
                    return true;
                };
                /**
                 * Navigate iframe to the uri where we want to read data from
                 * @private
                 */
                WindowName.prototype.navigateIFrameToTarget = function (uri) {
                    this._iframe.contentWindow.location.href = uri.toString();
                    this._state = WindowName.STATE_LOADING;
                };
                // @private
                WindowName.prototype.navigateIFrameToOwnHost = function () {
                    this._iframe.contentWindow.location.href = WindowName.getBlankUri().toString();
                };
                /**
                 * Handles iframe onload event.
                 * @private
                 */
                WindowName.prototype.handleOnLoad = function () {
                    switch (this._state) {
                        case WindowName.STATE_LOADING:
                            this._state = WindowName.STATE_LOADED;
                            this.navigateIFrameToOwnHost();
                            break;
                        case WindowName.STATE_LOADED:
                            var response = new Response();
                            try {
                                response.responseText = this._iframe.contentWindow.name;
                                response.status = 200;
                                response.isError = false;
                            }
                            catch (e) {
                                econda.debug.error('Could not read content from iframe for request to ' + this._request.getUri().toString(), { exception: e, iframe: this._iframe });
                                response.responseText = '';
                                response.status = 0;
                                response.isError = true;
                            }
                            this._request.handleResponse(response);
                            this.removeIFrame();
                            break;
                    }
                };
                /**
                 * Cleanup dom
                 */
                WindowName.prototype.removeIFrame = function () {
                    this._iframe.parentElement.removeChild(this._iframe);
                };
                /**
                 * Create iframe in dom and assign callbacks
                 * @private
                 */
                WindowName.prototype.setupIFrame = function () {
                    var cmp = this;
                    var body = document.getElementsByTagName('body')[0];
                    var iframe;
                    iframe = document.createElement('iframe');
                    iframe.style.display = "none";
                    iframe.style.width = "1px";
                    iframe.style.height = "1px";
                    var onloadHandler = function () {
                        cmp.handleOnLoad.apply(cmp, arguments);
                    };
                    if (typeof iframe.attachEvent === 'function') {
                        iframe.attachEvent('onload', onloadHandler);
                    }
                    else {
                        // can't attach event handler this way in old IE versions
                        iframe.onload = onloadHandler;
                    }
                    body.appendChild(iframe);
                    this._iframe = iframe;
                    this._state = WindowName.STATE_INITIALIZED;
                };
                WindowName.defaultBlankUri = "/favicon.ico";
                /**
                 * Number of instances of this class
                 * @static
                 * @private
                 */
                WindowName._instanceCount = 0;
                // State: Iframe not created, request not started
                WindowName.STATE_UNINITIALIZED = 0;
                // State: Iframe created, but request not started
                WindowName.STATE_INITIALIZED = 1;
                // State: Request started in iframe
                WindowName.STATE_LOADING = 2;
                // State: Content loaded
                WindowName.STATE_LOADED = 3;
                return WindowName;
            }());
            transport.WindowName = WindowName; // end of class
        })(transport = ajax.transport || (ajax.transport = {}));
    })(ajax = econda.ajax || (econda.ajax = {}));
})(econda || (econda = {})); // end of module