<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// create namespace
if (typeof Mozilla == 'undefined') {
    var Mozilla = {};
}

;(function($) {
    'use strict';

    // create namespace
    if (typeof Mozilla.FxOs == 'undefined') {
        Mozilla.FxOs = {};
    }

    /*
    List of countries where phones are available.

    If partner entry has 'developer_only' set to true, that partner should only
    be available on developer facing pages (/firefox/os/devices/). Currently
    used for ZTE Open C eBay links.

    Full list of ISO_3166-1 country codes is available here
    for reference: http://en.wikipedia.org/wiki/ISO_3166-1
    */

    Mozilla.FxOs.Countries = {
        'br': {
            'display': 'Brazil',
            'partner': [
                {
                    'name': 'Vivo',
                    'url': 'http://www.vivo.com.br/firefox'
                }
            ]
        },
        'cl': {
            'display': 'Chile',
            "partner": [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.cl/equipos/catalogo/producto/847/contrato/'
                }
            ]
        },
        'co': {
            'display': 'Colombia',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.co'
                }
            ]
        },
        'de': {
            'display': 'Germany',
            'partner': [
                {
                    'name': 'Alcatel One Touch Fire',
                    'url': 'http://aktion.congstar.de/firefox-os'
                },
                {
                    'name': 'Alcatel One Touch Fire E',
                    'url': 'http://www.congstar.de/handy/alcatel-one-touch-fire-e-orange/'
                },
                {
                    'name': 'ZTE Open C',
                    'url': 'http://www.ebay.de/itm/eBay-Exklusiv-ZTE-OPEN-C-Neuesten-Firefox-OS-DualCore-1-2-GHz-4-0-3G-Smartphone-/131151681046?ssPageName=STRK:MESE:IT',
                    'developer_only': true
                }
            ]
        },
        'es': {
            'display': 'Spain',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.es/firefoxos?aff=aff-firefoxOS1'
                }
            ]
        },
        'gb': {
            'display': 'United Kingdom',
            'partner': [
                {
                    'name': 'eBay',
                    'url': 'http://item.ebay.co.uk/171301269724',
                    'developer_only': true
                }
            ]
        },
        'fr': {
            'display': 'France',
            'partner': [
                {
                    'name': 'ZTE France',
                    'url': 'http://www.ztefrance.com/firefox-open-c.php'
                }
            ]
        },
        'gr': {
            'display': 'Greece',
            'partner': [
                {
                    'name': 'Cosmote',
                    'url': 'http://www.cosmote.gr/cosmoportal/cosmote.portal?_nfpb=true&_pageLabel=HDV&sku=20290038&s=0'
                }
            ]
        },
        'hu': {
            'display': 'Hungary',
            'partner': [
                {
                    'name': 'T-Mobile',
                    'url': 'https://webshop.t-mobile.hu/webapp/wcs/stores/ProductDisplay?catalogId=2001&storeId=2001&langId=-11&productId=644566'
                },
                {
                    'name': 'Telenor',
                    'url': 'http://www.telenor.hu/mobiltelefon/alcatel/one-touch-fire'
                }
            ]
        },
        'it': {
            'display': 'Italy',
            'partner': [
                {
                    'name': 'TIM',
                    'url': 'http://www.tim.it/prodotti/alcatel-one-touch-fire-mozilla-orange'
                }
            ]
        },
        'me': {
            'display': 'Montenegro',
            'partner': [
                {
                    'name': 'Telenor',
                    'url': 'http://www.telenor.me/sr/Privatni-korisnici/Uredjaji/Mobilni-telefoni/Alcatel/OT_Fire'
                }
            ]
        },
        'mx': {
            'display': 'Mexico',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'https://www.movistar.com.mx/catalogo'
                },
                {
                    'name': 'Telcel',
                    'url': 'http://www.telcel.com/portal/equipos/begin.do?idEquipo=3618'
                }
            ]
        },
        'pe': {
            'display': 'Peru',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://movistarfirefoxos.pe/'
                }
            ]
        },
        'pl': {
            'display': 'Poland',
            'partner': [
                {
                    'name': 'T-Mobile',
                    'url': 'http://www.t-mobile.pl/pl/firefox'
                }
            ]
        },
        'rs': {
            'display': 'Serbia',
            'partner': [
                {
                    'name': 'Telenor',
                    'url': 'https://www.telenor.rs/sr/Privatni-korisnici/webshop/Mobilni-telefoni/Alcatel/One_Touch_Fire'
                }
            ]
        },
        'ru': {
            'display': 'Russia',
            'partner': [
                {
                    'name': 'eBay',
                    'url': 'http://www.ebay.com/itm/eBay-Exclusive-ZTE-OPEN-C-Dual-Core-4-Latest-Firefox-OS-3G-Unlocked-Smartphone-/111326263156?ssPageName=STRK:MESE:IT',
                    'developer_only': true
                }
            ]
        },
        'us': {
            'display': 'United States',
            'partner': [
                {
                    'name': 'eBay',
                    'url': 'http://item.ebay.com/291125433026',
                    'developer_only': true
                }
            ]
        },
        'uy': {
            'display': 'Uruguay',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.firefoxos.movistar.com.uy/'
                }
            ]
        },
        've': {
            'display': 'Venezuela',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.com.ve/movistar_firefox/index.html'
                }
            ]
        }
    };

    Mozilla.FxOs.Devices = {
        'alcatel_onetouchfire': {
            'type': 'smartphone',
            'display': 'Alcatel One Touch Fire',
            'countries': ['br', 'cl', 'co', 'de', 'gr', 'hu', 'it', 'me', 'mx', 'pe', 'pl', 'rs', 'uy', 've']
        },
        'alcatel_onetouchfirec': {
            'type': 'smartphone',
            'display': 'Alcatel One Touch Fire C',
            'countries': []
        },
        'alcatel_onetouchfiree': {
            'type': 'smartphone',
            'display': 'Alcatel One Touch Fire E',
            'countries': ['de']
        },
        'huawei_y300-2': {
            'type': 'smartphone',
            'display': 'Huawei Y300II',
            'countries': ['mx']
        },
        'lg_fireweb': {
            'type': 'smartphone',
            'display': 'LG Fireweb',
            'countries': ['br', 'uy']
        },
        'zte_open': {
            'type': 'smartphone',
            'display': 'ZTE Open',
            'countries': ['co', 'es', 'mx', 'pe', 'uy', 've']
        },
        'zte_openc': {
            'type': 'smartphone',
            'display': 'ZTE Open C',
            'countries': ['de', 'fr', 'gb', 'ru', 'us', 'uy']
        },
        'zte_open2': {
            'type': 'smartphone',
            'display': 'ZTE Open II',
            'countries': ['co', 'pe']
        }
    };
})(window.jQuery);
<commit_msg>Change purchase URL for Alcatel OTF E. Bug 1042902.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// create namespace
if (typeof Mozilla == 'undefined') {
    var Mozilla = {};
}

;(function($) {
    'use strict';

    // create namespace
    if (typeof Mozilla.FxOs == 'undefined') {
        Mozilla.FxOs = {};
    }

    /*
    List of countries where phones are available.

    If partner entry has 'developer_only' set to true, that partner should only
    be available on developer facing pages (/firefox/os/devices/). Currently
    used for ZTE Open C eBay links.

    Full list of ISO_3166-1 country codes is available here
    for reference: http://en.wikipedia.org/wiki/ISO_3166-1
    */

    Mozilla.FxOs.Countries = {
        'br': {
            'display': 'Brazil',
            'partner': [
                {
                    'name': 'Vivo',
                    'url': 'http://www.vivo.com.br/firefox'
                }
            ]
        },
        'cl': {
            'display': 'Chile',
            "partner": [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.cl/equipos/catalogo/producto/847/contrato/'
                }
            ]
        },
        'co': {
            'display': 'Colombia',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.co'
                }
            ]
        },
        'de': {
            'display': 'Germany',
            'partner': [
                {
                    'name': 'Alcatel One Touch Fire',
                    'url': 'http://aktion.congstar.de/firefox-os'
                },
                {
                    'name': 'Alcatel One Touch Fire E',
                    'url': 'http://www.congstar.de/handy/alcatel-one-touch-fire-e-braun/'
                },
                {
                    'name': 'ZTE Open C',
                    'url': 'http://www.ebay.de/itm/eBay-Exklusiv-ZTE-OPEN-C-Neuesten-Firefox-OS-DualCore-1-2-GHz-4-0-3G-Smartphone-/131151681046?ssPageName=STRK:MESE:IT',
                    'developer_only': true
                }
            ]
        },
        'es': {
            'display': 'Spain',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.es/firefoxos?aff=aff-firefoxOS1'
                }
            ]
        },
        'gb': {
            'display': 'United Kingdom',
            'partner': [
                {
                    'name': 'eBay',
                    'url': 'http://item.ebay.co.uk/171301269724',
                    'developer_only': true
                }
            ]
        },
        'fr': {
            'display': 'France',
            'partner': [
                {
                    'name': 'ZTE France',
                    'url': 'http://www.ztefrance.com/firefox-open-c.php'
                }
            ]
        },
        'gr': {
            'display': 'Greece',
            'partner': [
                {
                    'name': 'Cosmote',
                    'url': 'http://www.cosmote.gr/cosmoportal/cosmote.portal?_nfpb=true&_pageLabel=HDV&sku=20290038&s=0'
                }
            ]
        },
        'hu': {
            'display': 'Hungary',
            'partner': [
                {
                    'name': 'T-Mobile',
                    'url': 'https://webshop.t-mobile.hu/webapp/wcs/stores/ProductDisplay?catalogId=2001&storeId=2001&langId=-11&productId=644566'
                },
                {
                    'name': 'Telenor',
                    'url': 'http://www.telenor.hu/mobiltelefon/alcatel/one-touch-fire'
                }
            ]
        },
        'it': {
            'display': 'Italy',
            'partner': [
                {
                    'name': 'TIM',
                    'url': 'http://www.tim.it/prodotti/alcatel-one-touch-fire-mozilla-orange'
                }
            ]
        },
        'me': {
            'display': 'Montenegro',
            'partner': [
                {
                    'name': 'Telenor',
                    'url': 'http://www.telenor.me/sr/Privatni-korisnici/Uredjaji/Mobilni-telefoni/Alcatel/OT_Fire'
                }
            ]
        },
        'mx': {
            'display': 'Mexico',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'https://www.movistar.com.mx/catalogo'
                },
                {
                    'name': 'Telcel',
                    'url': 'http://www.telcel.com/portal/equipos/begin.do?idEquipo=3618'
                }
            ]
        },
        'pe': {
            'display': 'Peru',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://movistarfirefoxos.pe/'
                }
            ]
        },
        'pl': {
            'display': 'Poland',
            'partner': [
                {
                    'name': 'T-Mobile',
                    'url': 'http://www.t-mobile.pl/pl/firefox'
                }
            ]
        },
        'rs': {
            'display': 'Serbia',
            'partner': [
                {
                    'name': 'Telenor',
                    'url': 'https://www.telenor.rs/sr/Privatni-korisnici/webshop/Mobilni-telefoni/Alcatel/One_Touch_Fire'
                }
            ]
        },
        'ru': {
            'display': 'Russia',
            'partner': [
                {
                    'name': 'eBay',
                    'url': 'http://www.ebay.com/itm/eBay-Exclusive-ZTE-OPEN-C-Dual-Core-4-Latest-Firefox-OS-3G-Unlocked-Smartphone-/111326263156?ssPageName=STRK:MESE:IT',
                    'developer_only': true
                }
            ]
        },
        'us': {
            'display': 'United States',
            'partner': [
                {
                    'name': 'eBay',
                    'url': 'http://item.ebay.com/291125433026',
                    'developer_only': true
                }
            ]
        },
        'uy': {
            'display': 'Uruguay',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.firefoxos.movistar.com.uy/'
                }
            ]
        },
        've': {
            'display': 'Venezuela',
            'partner': [
                {
                    'name': 'Movistar',
                    'url': 'http://www.movistar.com.ve/movistar_firefox/index.html'
                }
            ]
        }
    };

    Mozilla.FxOs.Devices = {
        'alcatel_onetouchfire': {
            'type': 'smartphone',
            'display': 'Alcatel One Touch Fire',
            'countries': ['br', 'cl', 'co', 'de', 'gr', 'hu', 'it', 'me', 'mx', 'pe', 'pl', 'rs', 'uy', 've']
        },
        'alcatel_onetouchfirec': {
            'type': 'smartphone',
            'display': 'Alcatel One Touch Fire C',
            'countries': []
        },
        'alcatel_onetouchfiree': {
            'type': 'smartphone',
            'display': 'Alcatel One Touch Fire E',
            'countries': ['de']
        },
        'huawei_y300-2': {
            'type': 'smartphone',
            'display': 'Huawei Y300II',
            'countries': ['mx']
        },
        'lg_fireweb': {
            'type': 'smartphone',
            'display': 'LG Fireweb',
            'countries': ['br', 'uy']
        },
        'zte_open': {
            'type': 'smartphone',
            'display': 'ZTE Open',
            'countries': ['co', 'es', 'mx', 'pe', 'uy', 've']
        },
        'zte_openc': {
            'type': 'smartphone',
            'display': 'ZTE Open C',
            'countries': ['de', 'fr', 'gb', 'ru', 'us', 'uy']
        },
        'zte_open2': {
            'type': 'smartphone',
            'display': 'ZTE Open II',
            'countries': ['co', 'pe']
        }
    };
})(window.jQuery);
<|endoftext|>


<commit_before>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape */

(function(){

    /**
     * @class easyXDM.transport.HashTransport
     * HashTransport is a transport class that uses the IFrame URL Technique for communication.

     * http://msdn.microsoft.com/en-us/library/bb735305.aspx

     * This requires the precense of hash.html on the hosting domain for optimal performance, but can also be used with any other
     * static file present. If used with static file (like an image) as the local: property, you must set the readyAfter property.

     * The library will try to be ready earlier, so this should be set to a safe value, when you are certain that the file will be loaded.

     * If this file is already present in the document, and therefor most likely cached, then this can be set to low value.
     *

     * The ReliableBehavior, QueueBehavior and VerifyBehavior are applied to this class.
     * @constructor
     * @param {easyXDM.configuration.TransportConfiguration} config The transports configuration.
     * @param {Function} onReady A method that should be called when the transport is ready
     * @cfg {Number} readyAfter The number of milliseconds to wait before firing onReady. To support using passive hash files.
     * @cfg {String/Window} local The url to the local document for calling back, or the local window.
     * @cfg {String} remote The url to the remote document to interface with
     * @cfg {Function} onMessage The method that should handle incoming messages.
 This method should accept two arguments, the message as a string, and the origin as a string.
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport = function(config, onReady){
        // #ifdef debug
        easyXDM.Debug.trace("easyXDM.transport.HashTransport.constructor");
        // #endif
        // If no protocol is set then it means this is the host
        var me = this, query = easyXDM.Url.Query(), isHost = (typeof query.xdm_p === "undefined");
        if (!isHost) {
            config.channel = query.xdm_c;
            config.remote = decodeURIComponent(query.xdm_e);
        }
        var _timer, pollInterval = config.interval || 300, usePolling = false, useParent = false, useResize = true;
        var _lastMsg = "#" + config.channel, _msgNr = 0, _listenerWindow, _callerWindow;
        var _remoteUrl, _remoteOrigin = easyXDM.Url.getLocation(config.remote);

        if (isHost) {
            var parameters = {
                xdm_c: config.channel,
                xdm_p: 0 // 0 = HashTransport
            };
            if (config.local === window) {
                // We are using the current window to listen to
                usePolling = true;
                useParent = true;
                parameters.xdm_e = encodeURIComponent(config.local = location.protocol + "//" + location.host + location.pathname + location.search);
                parameters.xdm_pa = 1; // use parent
            }
            else {
                parameters.xdm_e = easyXDM.Url.resolveUrl(config.local);
            }
            if (config.container) {
                useResize = false;
                parameters.xdm_po = 1; // use polling
            }
            _remoteUrl = easyXDM.Url.appendQueryParameters(config.remote, parameters);
        }
        else {
            _listenerWindow = window;
            useParent = (typeof query.xdm_pa !== "undefined");
            if (useParent) {
                useResize = false;
            }
            usePolling = (typeof query.xdm_po !== "undefined");
            _remoteUrl = config.remote;
        }

        // #ifdef debug
        if (usePolling) {
            easyXDM.Debug.trace("using polling to listen");
        }
        if (useResize) {
            easyXDM.Debug.trace("using resizing to call");
        }
        if (useParent) {
            easyXDM.Debug.trace("using current window as " + (config.local ? "listenerWindow" : "callerWindow"));
        }
        // #endif

        function _sendMessage(message){
            // #ifdef debug
            easyXDM.Debug.trace("sending message '" + (_msgNr + 1) + " " + message + "' to " + _remoteOrigin);
            // #endif
            if (!_callerWindow) {
                // #ifdef debug
                easyXDM.Debug.trace("no caller window");
                // #endif
                return;
            }
            var url = _remoteUrl + "#" + (_msgNr++) + "_" + message;

            if (isHost || !useParent) {
                // We are referencing an iframe
                _callerWindow.contentWindow.location = url;
                if (useResize) {
                    // #ifdef debug
                    easyXDM.Debug.trace("resizing to new size " + (_callerWindow.width > 75 ? 50 : 100));
                    // #endif
                    _callerWindow.width = _callerWindow.width > 75 ? 50 : 100;
                }
            }
            else {
                // We are referencing the parent window
                _callerWindow.location = url;
            }
        }

        this.up = {
            incomming: function(message, origin){
                config.onMessage(decodeURIComponent(message), origin);
            },
            outgoing: function(message){
                _sendMessage(encodeURIComponent(message));
            },
            callback: function(succes){
                if (onReady) {
                    window.setTimeout(onReady, 10);
                }
            },
            destroy: function(){
            }
        };
        this.down = {
            incomming: function(message, origin){
                this.up.incomming(message, origin);
            },
            outgoing: function(message, origin){
                this.down.outgoing(message, origin);
            },
            callback: function(success){
                this.up.callback(success);
            },
            destroy: function(){
                this.down.destroy();
            }
        };

        easyXDM.applyBehaviors(this, [new easyXDM.transport.behaviors.ReliableBehavior({
            timeout: ((useResize ? 50 : pollInterval * 1.5) + (usePolling ? pollInterval * 1.5 : 50))
        }), new easyXDM.transport.behaviors.QueueBehavior({
            maxLength: 4000 - _remoteUrl.length
        }), new easyXDM.transport.behaviors.VerifyBehavior({
            initiate: isHost
        })]);

        function _handleHash(hash){
            _lastMsg = hash;
            // #ifdef debug
            easyXDM.Debug.trace("received message '" + _lastMsg + "' from " + _remoteOrigin);
            // #endif
            me.down.incomming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
        }

        function _onResize(e){
            _handleHash(_listenerWindow.location.hash);
        }

        /**
         * Checks location.hash for a new message and relays this to the receiver.
         * @private
         */
        function _pollHash(){
            if (_listenerWindow.location.hash && _listenerWindow.location.hash != _lastMsg) {
                // #ifdef debug
                easyXDM.Debug.trace("poll: new message");
                // #endif
                _handleHash(_listenerWindow.location.hash);
            }
        }

        /**
         * Calls the supplied onReady method

         * We delay this so that the the call to createChannel or createTransport will have completed.
         * @private
         */
        function _onReady(){
            if (isHost && !_listenerWindow) {
                if (useParent) {
                    _listenerWindow = window;
                }
                else if (config.readyAfter) {
                    // We must try obtain a reference to the correct window, this might fail
                    try {
                        // This works in IE6
                        _listenerWindow = _callerWindow.contentWindow.frames["remote_" + config.channel];
                    }
                    catch (ex) {
                        // #ifdef debug
                        easyXDM.Debug.trace("Falling back to using window.open");
                        // #endif
                        _listenerWindow = window.open("", "remote_" + config.channel);
                    }
                }
                else {
                    _listenerWindow = easyXDM.transport.HashTransport.getWindow(config.channel);
                }
                if (!_listenerWindow) {
                    // #ifdef debug
                    easyXDM.Debug.trace("Failed to obtain a reference to the window");
                    // #endif
                    throw new Error("Failed to obtain a reference to the window");
                }
            }

            (function getBody(){
                if (_listenerWindow && _listenerWindow.document && _listenerWindow.document.body) {
                    if (usePolling) {
                        // #ifdef debug
                        easyXDM.Debug.trace("starting polling");
                        // #endif
                        _timer = window.setInterval(_pollHash, pollInterval);
                    }
                    else if ((!isHost && !usePolling) || config.readyAfter) {
                        // This cannot handle resize on its own
                        easyXDM.DomHelper.addEventListener(_listenerWindow, "resize", _onResize);

                    }
                    me.down.callback(true);
                }
                else {
                    window.setTimeout(getBody, 10);
                }
            }());
        }

        /**
         * Sends a message by encoding and placing it in the hash part of _callerWindows url.
         * We include a message number so that identical messages will be read as separate messages.
         * @param {String} message The message to send
         */
        this.postMessage = function(message){
            me.down.outgoing(message, _remoteOrigin);
        };

        /**
         * Tries to clean up the DOM
         */
        this.destroy = function(){
            // #ifdef debug
            easyXDM.Debug.trace("destroying transport");
            // #endif
            me.down.destroy();
            if (usePolling) {
                window.clearInterval(_timer);
            }
            else if ((!isHost && !usePolling) || config.readyAfter) {
                easyXDM.DomHelper.removeEventListener(_listenerWindow, "resize", _pollHash);
            }
            if (isHost || !useParent) {
                _callerWindow.parentNode.removeChild(_callerWindow);
            }
            _callerWindow = null;
        };

        if (isHost) {
            if (config.readyAfter) {
                // Fire the onReady method after a set delay
                _timer = window.setTimeout(_onReady, config.readyAfter);
            }
            else {
                // Register onReady callback in the library so that
                // it can be called when hash.html has loaded.
                easyXDM.Fn.set(config.channel, _onReady);
                easyXDM.Fn.set(config.channel + "_onresize", _handleHash);
            }
        }
        else {

        }
        if (!isHost && useParent) {
            _callerWindow = parent;
            _onReady();
        }
        else {
            _callerWindow = easyXDM.DomHelper.createFrame((isHost ? _remoteUrl : _remoteUrl + "#" + config.channel), config.container, (isHost && !useParent) ? null : _onReady, (isHost ? "local_" : "remote_") + config.channel);
            if (isHost && config.readyAfter) {
                var tries = 0, max = config.readyAfter / 50;
                (function getRef(){
                    if (++tries > max) {
                        return;
                    }
                    if (_listenerWindow) {
                        return;
                    }
                    try {
                        // This works in IE6
                        _listenerWindow = _callerWindow.contentWindow.frames["remote_" + config.channel];
                        // #ifdef debug
                        easyXDM.Debug.trace("got an early reference to _listenerWindow");
                        // #endif
                        window.clearTimeout(_timer);
                        _onReady();
                        return;
                    }
                    catch (ex) {
                        window.setTimeout(getRef, 50);
                    }
                }());
            }
        }
    };

    /**
     * Contains the proxy windows used to read messages from remote when
     * using HashTransport.
     * @static
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport.windows = {};

    /**
     * Notify that a channel is ready and register a window to be used for reading messages
     * for on the channel.
     * @static
     * @param {String} channel
     * @param {Window} contentWindow
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport.channelReady = function(channel, contentWindow){
        var ht = easyXDM.transport.HashTransport;
        ht.windows[channel] = contentWindow;
        // #ifdef debug
        easyXDM.Debug.trace("executing onReady callback for channel " + channel);
        // #endif
        easyXDM.Fn.get(channel, true)();
    };

    /**
     * Returns the window associated with a channel
     * @static
     * @param {String} channel
     * @return {Window} The window
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport.getWindow = function(channel){
        return easyXDM.transport.HashTransport.windows[channel];
    };
}());
<commit_msg>Fixed a typo<commit_after>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape */

(function(){

    /**
     * @class easyXDM.transport.HashTransport
     * HashTransport is a transport class that uses the IFrame URL Technique for communication.

     * http://msdn.microsoft.com/en-us/library/bb735305.aspx

     * This requires the precense of hash.html on the hosting domain for optimal performance, but can also be used with any other
     * static file present. If used with a static file (like an image) as the local: property, you must set the readyAfter property.

     * The library will try to be ready earlier, so this should be set to a safe value, when you are certain that the file will be loaded.

     * If this file is already present in the document, and therefor most likely cached, then this can be set to low value.
     *

     * The ReliableBehavior, QueueBehavior and VerifyBehavior are applied to this class.
     * @constructor
     * @param {easyXDM.configuration.TransportConfiguration} config The transports configuration.
     * @param {Function} onReady A method that should be called when the transport is ready
     * @cfg {Number} readyAfter The number of milliseconds to wait before firing onReady. To support using passive hash files.
     * @cfg {String/Window} local The url to the local document for calling back, or the local window.
     * @cfg {String} remote The url to the remote document to interface with
     * @cfg {Function} onMessage The method that should handle incoming messages.
 This method should accept two arguments, the message as a string, and the origin as a string.
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport = function(config, onReady){
        // #ifdef debug
        easyXDM.Debug.trace("easyXDM.transport.HashTransport.constructor");
        // #endif
        // If no protocol is set then it means this is the host
        var me = this, query = easyXDM.Url.Query(), isHost = (typeof query.xdm_p === "undefined");
        if (!isHost) {
            config.channel = query.xdm_c;
            config.remote = decodeURIComponent(query.xdm_e);
        }
        var _timer, pollInterval = config.interval || 300, usePolling = false, useParent = false, useResize = true;
        var _lastMsg = "#" + config.channel, _msgNr = 0, _listenerWindow, _callerWindow;
        var _remoteUrl, _remoteOrigin = easyXDM.Url.getLocation(config.remote);

        if (isHost) {
            var parameters = {
                xdm_c: config.channel,
                xdm_p: 0 // 0 = HashTransport
            };
            if (config.local === window) {
                // We are using the current window to listen to
                usePolling = true;
                useParent = true;
                parameters.xdm_e = encodeURIComponent(config.local = location.protocol + "//" + location.host + location.pathname + location.search);
                parameters.xdm_pa = 1; // use parent
            }
            else {
                parameters.xdm_e = easyXDM.Url.resolveUrl(config.local);
            }
            if (config.container) {
                useResize = false;
                parameters.xdm_po = 1; // use polling
            }
            _remoteUrl = easyXDM.Url.appendQueryParameters(config.remote, parameters);
        }
        else {
            _listenerWindow = window;
            useParent = (typeof query.xdm_pa !== "undefined");
            if (useParent) {
                useResize = false;
            }
            usePolling = (typeof query.xdm_po !== "undefined");
            _remoteUrl = config.remote;
        }

        // #ifdef debug
        if (usePolling) {
            easyXDM.Debug.trace("using polling to listen");
        }
        if (useResize) {
            easyXDM.Debug.trace("using resizing to call");
        }
        if (useParent) {
            easyXDM.Debug.trace("using current window as " + (config.local ? "listenerWindow" : "callerWindow"));
        }
        // #endif

        function _sendMessage(message){
            // #ifdef debug
            easyXDM.Debug.trace("sending message '" + (_msgNr + 1) + " " + message + "' to " + _remoteOrigin);
            // #endif
            if (!_callerWindow) {
                // #ifdef debug
                easyXDM.Debug.trace("no caller window");
                // #endif
                return;
            }
            var url = _remoteUrl + "#" + (_msgNr++) + "_" + message;

            if (isHost || !useParent) {
                // We are referencing an iframe
                _callerWindow.contentWindow.location = url;
                if (useResize) {
                    // #ifdef debug
                    easyXDM.Debug.trace("resizing to new size " + (_callerWindow.width > 75 ? 50 : 100));
                    // #endif
                    _callerWindow.width = _callerWindow.width > 75 ? 50 : 100;
                }
            }
            else {
                // We are referencing the parent window
                _callerWindow.location = url;
            }
        }

        this.up = {
            incomming: function(message, origin){
                config.onMessage(decodeURIComponent(message), origin);
            },
            outgoing: function(message){
                _sendMessage(encodeURIComponent(message));
            },
            callback: function(succes){
                if (onReady) {
                    window.setTimeout(onReady, 10);
                }
            },
            destroy: function(){
            }
        };
        this.down = {
            incomming: function(message, origin){
                this.up.incomming(message, origin);
            },
            outgoing: function(message, origin){
                this.down.outgoing(message, origin);
            },
            callback: function(success){
                this.up.callback(success);
            },
            destroy: function(){
                this.down.destroy();
            }
        };

        easyXDM.applyBehaviors(this, [new easyXDM.transport.behaviors.ReliableBehavior({
            timeout: ((useResize ? 50 : pollInterval * 1.5) + (usePolling ? pollInterval * 1.5 : 50))
        }), new easyXDM.transport.behaviors.QueueBehavior({
            maxLength: 4000 - _remoteUrl.length
        }), new easyXDM.transport.behaviors.VerifyBehavior({
            initiate: isHost
        })]);

        function _handleHash(hash){
            _lastMsg = hash;
            // #ifdef debug
            easyXDM.Debug.trace("received message '" + _lastMsg + "' from " + _remoteOrigin);
            // #endif
            me.down.incomming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
        }

        function _onResize(e){
            _handleHash(_listenerWindow.location.hash);
        }

        /**
         * Checks location.hash for a new message and relays this to the receiver.
         * @private
         */
        function _pollHash(){
            if (_listenerWindow.location.hash && _listenerWindow.location.hash != _lastMsg) {
                // #ifdef debug
                easyXDM.Debug.trace("poll: new message");
                // #endif
                _handleHash(_listenerWindow.location.hash);
            }
        }

        /**
         * Calls the supplied onReady method

         * We delay this so that the the call to createChannel or createTransport will have completed.
         * @private
         */
        function _onReady(){
            if (isHost && !_listenerWindow) {
                if (useParent) {
                    _listenerWindow = window;
                }
                else if (config.readyAfter) {
                    // We must try obtain a reference to the correct window, this might fail
                    try {
                        // This works in IE6
                        _listenerWindow = _callerWindow.contentWindow.frames["remote_" + config.channel];
                    }
                    catch (ex) {
                        // #ifdef debug
                        easyXDM.Debug.trace("Falling back to using window.open");
                        // #endif
                        _listenerWindow = window.open("", "remote_" + config.channel);
                    }
                }
                else {
                    _listenerWindow = easyXDM.transport.HashTransport.getWindow(config.channel);
                }
                if (!_listenerWindow) {
                    // #ifdef debug
                    easyXDM.Debug.trace("Failed to obtain a reference to the window");
                    // #endif
                    throw new Error("Failed to obtain a reference to the window");
                }
            }

            (function getBody(){
                if (_listenerWindow && _listenerWindow.document && _listenerWindow.document.body) {
                    if (usePolling) {
                        // #ifdef debug
                        easyXDM.Debug.trace("starting polling");
                        // #endif
                        _timer = window.setInterval(_pollHash, pollInterval);
                    }
                    else if ((!isHost && !usePolling) || config.readyAfter) {
                        // This cannot handle resize on its own
                        easyXDM.DomHelper.addEventListener(_listenerWindow, "resize", _onResize);

                    }
                    me.down.callback(true);
                }
                else {
                    window.setTimeout(getBody, 10);
                }
            }());
        }

        /**
         * Sends a message by encoding and placing it in the hash part of _callerWindows url.
         * We include a message number so that identical messages will be read as separate messages.
         * @param {String} message The message to send
         */
        this.postMessage = function(message){
            me.down.outgoing(message, _remoteOrigin);
        };

        /**
         * Tries to clean up the DOM
         */
        this.destroy = function(){
            // #ifdef debug
            easyXDM.Debug.trace("destroying transport");
            // #endif
            me.down.destroy();
            if (usePolling) {
                window.clearInterval(_timer);
            }
            else if ((!isHost && !usePolling) || config.readyAfter) {
                easyXDM.DomHelper.removeEventListener(_listenerWindow, "resize", _pollHash);
            }
            if (isHost || !useParent) {
                _callerWindow.parentNode.removeChild(_callerWindow);
            }
            _callerWindow = null;
        };

        if (isHost) {
            if (config.readyAfter) {
                // Fire the onReady method after a set delay
                _timer = window.setTimeout(_onReady, config.readyAfter);
            }
            else {
                // Register onReady callback in the library so that
                // it can be called when hash.html has loaded.
                easyXDM.Fn.set(config.channel, _onReady);
                easyXDM.Fn.set(config.channel + "_onresize", _handleHash);
            }
        }
        else {

        }
        if (!isHost && useParent) {
            _callerWindow = parent;
            _onReady();
        }
        else {
            _callerWindow = easyXDM.DomHelper.createFrame((isHost ? _remoteUrl : _remoteUrl + "#" + config.channel), config.container, (isHost && !useParent) ? null : _onReady, (isHost ? "local_" : "remote_") + config.channel);
            if (isHost && config.readyAfter) {
                var tries = 0, max = config.readyAfter / 50;
                (function getRef(){
                    if (++tries > max) {
                        return;
                    }
                    if (_listenerWindow) {
                        return;
                    }
                    try {
                        // This works in IE6
                        _listenerWindow = _callerWindow.contentWindow.frames["remote_" + config.channel];
                        // #ifdef debug
                        easyXDM.Debug.trace("got an early reference to _listenerWindow");
                        // #endif
                        window.clearTimeout(_timer);
                        _onReady();
                        return;
                    }
                    catch (ex) {
                        window.setTimeout(getRef, 50);
                    }
                }());
            }
        }
    };

    /**
     * Contains the proxy windows used to read messages from remote when
     * using HashTransport.
     * @static
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport.windows = {};

    /**
     * Notify that a channel is ready and register a window to be used for reading messages
     * for on the channel.
     * @static
     * @param {String} channel
     * @param {Window} contentWindow
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport.channelReady = function(channel, contentWindow){
        var ht = easyXDM.transport.HashTransport;
        ht.windows[channel] = contentWindow;
        // #ifdef debug
        easyXDM.Debug.trace("executing onReady callback for channel " + channel);
        // #endif
        easyXDM.Fn.get(channel, true)();
    };

    /**
     * Returns the window associated with a channel
     * @static
     * @param {String} channel
     * @return {Window} The window
     * @namespace easyXDM.transport
     */
    easyXDM.transport.HashTransport.getWindow = function(channel){
        return easyXDM.transport.HashTransport.windows[channel];
    };
}());
<|endoftext|>


<commit_before>// Amara, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('unisubs.translate.Dialog');

/**
 * @constructor
 *
 */
unisubs.translate.Dialog = function(opener, serverModel, videoSource, subtitleState, standardSubState, reviewOrApprovalType) {
    unisubs.Dialog.call(this, videoSource);
    unisubs.SubTracker.getInstance().start(true);
    this.opener_ = opener;
    this.subtitleState_ = subtitleState;
    this.standardSubState_ = standardSubState;

    this.serverModel_ = serverModel;
    this.serverModel_.init();

    this.saved_ = false;
    this.rightPanelListener_ = new goog.events.EventHandler(this);
    this.reviewOrApprovalType_ = reviewOrApprovalType;
    // if this is a review approve dialog, we must fetch saved notes for this task if available
    // but we should only do it when the dialog laods the first time
    // (else as users move back and forward between panels we might
    // overwrite their notes). This is what this flag is for
    this.notesFectched_ = false;
    if ( !Boolean(this.reviewOrApprovalType_)){
       this.notesFectched_ = true;
    }
};

goog.inherits(unisubs.translate.Dialog, unisubs.subtitle.Dialog);

unisubs.translate.Dialog.State_ = {
    TRANSLATE: 0,
    EDIT_METADATA: 1
};

unisubs.translate.Dialog.prototype.createDom = function() {
    unisubs.translate.Dialog.superClass_.createDom.call(this);
    this.setDraggable(false);
    this.showGuidelines_();
    this.enterState_(unisubs.translate.Dialog.State_.TRANSLATE);
};
unisubs.translate.Dialog.prototype.showGuidelines_ = function() {
    var skipGuidelines = unisubs.UserSettings.getBooleanValue(
                            unisubs.UserSettings.Settings.ALWAYS_SKIP_GUIDELINES);

    if(skipGuidelines){
        return;
    }

    if (!unisubs.guidelines['translate']) var s = unisubs.subtitle.Dialog.State_;
    // the same dialog can be used in transcribing or review approval, which guidelines should we use?
    var guideline = this.reviewOrApprovalType_ ? this.getTeamGuidelineForReview() : unisubs.guidelines['translate'];

    if (!guideline) {
        return;
    }
    var guidelinesPanel = new unisubs.GuidelinesPanel(guideline);
    this.showTemporaryPanel(guidelinesPanel);
    this.displayingGuidelines_ = true;

    var that = this;
    this.getHandler().listenOnce(guidelinesPanel, unisubs.GuidelinesPanel.CONTINUE, function(e) {
        goog.Timer.callOnce(function() {
            that.displayingGuidelines_ = false;
            that.hideTemporaryPanel();
        });
    });
};
unisubs.translate.Dialog.prototype.handleSaveAndExitKeyPress_ = function(e) {
    e.preventDefault();
    this.saveWork(false, true);
};
unisubs.translate.Dialog.prototype.handleDoneKeyPress_ = function(event) {
    event.preventDefault();
    if (this.state_ == unisubs.translate.Dialog.State_.EDIT_METADATA)
        this.saveWork(true, false);
    else
        this.enterState_(unisubs.translate.Dialog.State_.EDIT_METADATA);
};
unisubs.translate.Dialog.prototype.isWorkSaved = function() {
    if (this.reviewOrApprovalType_) {
        if (this.getNotesContent_(this.currentSubtitlePanel_) !== '') {
            return this.saved_;
        }
    }
    return this.saved_ || !this.serverModel_.anySubtitlingWorkDone();
};
unisubs.translate.Dialog.prototype.enterDocument = function() {
    // this is where we listen to the dialog close button
    unisubs.subtitle.Dialog.superClass_.enterDocument.call(this);
    unisubs.Dialog.translationDialogOpen = true;

    if (this.reviewOrApprovalType_ && !this.notesFectched_){
        var func  = this.serverModel_.fetchReviewData ;
        var that = this;
        if (this.reviewOrApprovalType_ == unisubs.Dialog.REVIEW_OR_APPROVAL.APPROVAL){
            func = this.serverModel_.fetchApproveData;
        }

        // make sure we retain the correct scope
        func.call(this.serverModel_, unisubs.task_id, function(body) {
            that.onNotesFetched_(body);
        });
    }
};
unisubs.translate.Dialog.prototype.onNotesFetched_ = function(body) {
    if( this.currentSubtitlePanel_ && this.currentSubtitlePanel_.setNotesContent_){
        this.currentSubtitlePanel_.setNotesContent_(body);
    }
};
unisubs.translate.Dialog.prototype.saveWorkInternal = function(closeAfterSave, saveForLater) {
    var notes = this.getNotesContent_(this.currentSubtitlePanel_);
    if (notes !== '') {
        this.serverModel_.setTaskNotes(notes);
    }

    if (goog.array.isEmpty(
        this.serverModel_.captionSet_.nonblankSubtitles())){
        // there are no subs here, close dialog or back to subtitling
        this.showEmptySubsDialog();
        return;
    }
    var that = this;
    this.getRightPanelInternal().showLoading(true);
    this.serverModel_.finish(
        function(serverMsg){
            unisubs.subtitle.OnSavedDialog.show(serverMsg, function(){
                that.onWorkSaved(closeAfterSave);
            });
        },
        function(opt_status) {
            if (that.finishFailDialog_)
                that.finishFailDialog_.failedAgain(opt_status);
            else
                that.finishFailDialog_ = unisubs.finishfaildialog.Dialog.show(
                    that.serverModel_.getCaptionSet(), opt_status,
                    goog.bind(that.saveWorkInternal, that, closeAfterSave));
        },
        null,
        saveForLater);
};
unisubs.translate.Dialog.prototype.showGuidelinesForState_ = function(state) {
    this.setState_(state);
};
unisubs.Dialog.prototype.setVisible = function(visible) {
    if (visible) {
        unisubs.Dialog.superClass_.setVisible.call(this, true);
        goog.dom.getDocumentScrollElement().scrollTop = 0;
    }
    else {
        if (this.isWorkSaved()) {
            this.hideDialogImpl_();
        }
        else {
            this.showSaveWorkDialog_();
        }
    }
};
unisubs.translate.Dialog.prototype.onWorkSaved = function() {
    if (this.finishFailDialog_) {
        this.finishFailDialog_.setVisible(false);
        this.finishFailDialog_ = null;
    }
    unisubs.widget.ResumeEditingRecord.clear();
    this.getRightPanelInternal().showLoading(false);
    this.saved_ = true;
    this.setVisible(false);
};
unisubs.translate.Dialog.prototype.disposeInternal = function() {
    unisubs.translate.Dialog.superClass_.disposeInternal.call(this);
    this.serverModel_.dispose();
};
unisubs.translate.Dialog.prototype.enterState_ = function(state) {
    this.showGuidelinesForState_(state);
};
unisubs.translate.Dialog.prototype.suspendKeyEvents_ = function(suspended) {
    this.keyEventsSuspended_ = suspended;
    if (this.currentSubtitlePanel_ && this.currentSubtitlePanel_.suspendKeyEvents)
        this.currentSubtitlePanel_.suspendKeyEvents(suspended);
};
unisubs.translate.Dialog.prototype.setState_ = function(state) {
    this.state_ = state;

    this.suspendKeyEvents_(false);

    var s = unisubs.translate.Dialog.State_;

    this.setExtraClass_();

    var nextSubPanel = this.makeCurrentStateSubtitlePanel_();
    var captionPanel = this.getCaptioningAreaInternal();
    captionPanel.removeChildren(true);
    captionPanel.addChild(nextSubPanel, true);

    var rightPanel = nextSubPanel.getRightPanel();
    this.setRightPanelInternal(rightPanel);

    this.getTimelinePanelInternal().removeChildren(true);

    if (this.currentSubtitlePanel_ && this.currentSubtitlePanel_.getNotesContent_){
       var currentNoteContent =  this.currentSubtitlePanel_.getNotesContent_();
       if (nextSubPanel  && nextSubPanel.setNotesContent_){
           nextSubPanel.setNotesContent_(currentNoteContent);
       }
    }

    this.disposeCurrentPanels_();
    this.currentSubtitlePanel_ = nextSubPanel;

    var et = unisubs.RightPanel.EventType;
    this.rightPanelListener_.
        listen(
            rightPanel, et.LEGENDKEY, this.handleLegendKeyPress_).
        listen(
            rightPanel, et.DONE, this.handleDoneKeyPress_).
        listen(
            rightPanel, et.SAVEANDEXIT, this.handleSaveAndExitKeyPress_).
        listen(
            rightPanel, et.GOTOSTEP, this.handleGoToStep_);
    var backButtonText = null;
    if (state == s.EDIT_METADATA ){
        backButtonText = "Back to Translation";
    }
    if (backButtonText){
        rightPanel.showBackLink(backButtonText);
        this.rightPanelListener_.listen(
            rightPanel, et.BACK, this.handleBackKeyPress_);

    }

    var videoPlayer = this.getVideoPlayerInternal();
    if (this.isInDocument()) {
        if (!videoPlayer.isPaused()){
            videoPlayer.pause();
        }
        if(videoPlayer.getPlayheadTime()){
            videoPlayer.setPlayheadTime(0);
            videoPlayer.pause();
        }
    }

    var that = this;
    this.getRightPanelInternal().showDownloadLink(
        function() {
            return that.makeJsonSubs();
        });
};
unisubs.translate.Dialog.prototype.makeCurrentStateSubtitlePanel_ = function() {
    var s = unisubs.translate.Dialog.State_;

    if (this.state_ == s.TRANSLATE){
        this.translationPanel_ =  new unisubs.translate.TranslationPanel(
            this.serverModel_.getCaptionSet(),
            this.standardSubState_,
            this,
            this.reviewOrApprovalType_,
            this.serverModel_);
        return this.translationPanel_;
    }
    else if (this.state_ == s.EDIT_METADATA)
        return new unisubs.editmetadata.Panel(
            this.serverModel_.getCaptionSet(),
            this.getVideoPlayerInternal(),
            this.serverModel_,
            this.standardSubState_ ,
            false,
            this.reviewOrApprovalType_,
            this);
};

/**
 * Tries translate subtitles with BingTranslator
 */
unisubs.translate.Dialog.prototype.translateViaBing = function(){
    //I don't know how better call this. I think it should be incapsulated in translationList_,
    //but have chain of function calls can confuse.
    this.translationPanel_.getTranslationList().translateViaBing(
        this.standardSubState_.LANGUAGE, this.subtitleState_.LANGUAGE);
};
unisubs.translate.Dialog.prototype.getStandardLanguage = function(){
    return this.standardSubState_.LANGUAGE;
};
unisubs.translate.Dialog.prototype.getSubtitleLanguage = function(){
    return this.subtitleState_.LANGUAGE;
};
unisubs.translate.Dialog.prototype.getServerModel = function(){
    return this.serverModel_;
};
unisubs.translate.Dialog.prototype.makeJsonSubs =  function (){
    return this.serverModel_.getCaptionSet().makeJsonSubs();
};
unisubs.translate.Dialog.prototype.forkAndClose = function() {
    var dialog = new unisubs.translate.ForkDialog(
        goog.bind(this.forkImpl_, this));
    dialog.setVisible(true);
};
unisubs.translate.Dialog.prototype.forkImpl_ = function() {
    this.subtitleState_.fork();
    this.serverModel_.fork(this.standardSubState_);
    this.hideToFork();
    this.opener_.openSubtitlingDialog(
        this.serverModel_,
        this.subtitleState_);
};
unisubs.translate.Dialog.prototype.disposeCurrentPanels_ = function() {
    if (this.currentSubtitlePanel_) {
        this.currentSubtitlePanel_.dispose();
        this.currentSubtitlePanel_ = null;
    }
    this.rightPanelListener_.removeAll();
    if (this.timelineSubtitleSet_) {
        this.timelineSubtitleSet_.dispose();
        this.timelineSubtitleSet_ = null;
    }
};
unisubs.subtitle.Dialog.prototype.captionReached_ = function(event) {
    var c = event.caption;
    this.getVideoPlayerInternal().showCaptionText(c ? c.getText() : '');
};
<commit_msg>Re-add captionManager to call for rightPanel. Broke translate process.<commit_after>// Amara, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('unisubs.translate.Dialog');

/**
 * @constructor
 *
 */
unisubs.translate.Dialog = function(opener, serverModel, videoSource, subtitleState, standardSubState, reviewOrApprovalType) {
    unisubs.Dialog.call(this, videoSource);
    unisubs.SubTracker.getInstance().start(true);
    this.opener_ = opener;
    this.subtitleState_ = subtitleState;
    this.standardSubState_ = standardSubState;

    this.serverModel_ = serverModel;

    this.serverModel_.init();

    this.saved_ = false;
    this.rightPanelListener_ = new goog.events.EventHandler(this);
    this.reviewOrApprovalType_ = reviewOrApprovalType;
    // if this is a review approve dialog, we must fetch saved notes for this task if available
    // but we should only do it when the dialog laods the first time
    // (else as users move back and forward between panels we might
    // overwrite their notes). This is what this flag is for
    this.notesFectched_ = false;
    if ( !Boolean(this.reviewOrApprovalType_)){
       this.notesFectched_ = true;
    }
};

goog.inherits(unisubs.translate.Dialog, unisubs.subtitle.Dialog);

unisubs.translate.Dialog.State_ = {
    TRANSLATE: 0,
    EDIT_METADATA: 1
};

unisubs.translate.Dialog.prototype.createDom = function() {
    unisubs.translate.Dialog.superClass_.createDom.call(this);
    this.setDraggable(false);
    this.showGuidelines_();
    this.enterState_(unisubs.translate.Dialog.State_.TRANSLATE);
};
unisubs.translate.Dialog.prototype.showGuidelines_ = function() {
    var skipGuidelines = unisubs.UserSettings.getBooleanValue(
                            unisubs.UserSettings.Settings.ALWAYS_SKIP_GUIDELINES);

    if(skipGuidelines){
        return;
    }

    if (!unisubs.guidelines['translate']) var s = unisubs.subtitle.Dialog.State_;
    // the same dialog can be used in transcribing or review approval, which guidelines should we use?
    var guideline = this.reviewOrApprovalType_ ? this.getTeamGuidelineForReview() : unisubs.guidelines['translate'];

    if (!guideline) {
        return;
    }
    var guidelinesPanel = new unisubs.GuidelinesPanel(guideline);
    this.showTemporaryPanel(guidelinesPanel);
    this.displayingGuidelines_ = true;

    var that = this;
    this.getHandler().listenOnce(guidelinesPanel, unisubs.GuidelinesPanel.CONTINUE, function(e) {
        goog.Timer.callOnce(function() {
            that.displayingGuidelines_ = false;
            that.hideTemporaryPanel();
        });
    });
};
unisubs.translate.Dialog.prototype.handleSaveAndExitKeyPress_ = function(e) {
    e.preventDefault();
    this.saveWork(false, true);
};
unisubs.translate.Dialog.prototype.handleDoneKeyPress_ = function(event) {
    event.preventDefault();
    if (this.state_ == unisubs.translate.Dialog.State_.EDIT_METADATA)
        this.saveWork(true, false);
    else
        this.enterState_(unisubs.translate.Dialog.State_.EDIT_METADATA);
};
unisubs.translate.Dialog.prototype.isWorkSaved = function() {
    if (this.reviewOrApprovalType_) {
        if (this.getNotesContent_(this.currentSubtitlePanel_) !== '') {
            return this.saved_;
        }
    }
    return this.saved_ || !this.serverModel_.anySubtitlingWorkDone();
};
unisubs.translate.Dialog.prototype.enterDocument = function() {
    // this is where we listen to the dialog close button
    unisubs.subtitle.Dialog.superClass_.enterDocument.call(this);
    unisubs.Dialog.translationDialogOpen = true;

    if (this.reviewOrApprovalType_ && !this.notesFectched_){
        var func  = this.serverModel_.fetchReviewData ;
        var that = this;
        if (this.reviewOrApprovalType_ == unisubs.Dialog.REVIEW_OR_APPROVAL.APPROVAL){
            func = this.serverModel_.fetchApproveData;
        }

        // make sure we retain the correct scope
        func.call(this.serverModel_, unisubs.task_id, function(body) {
            that.onNotesFetched_(body);
        });
    }
};
unisubs.translate.Dialog.prototype.onNotesFetched_ = function(body) {
    if( this.currentSubtitlePanel_ && this.currentSubtitlePanel_.setNotesContent_){
        this.currentSubtitlePanel_.setNotesContent_(body);
    }
};
unisubs.translate.Dialog.prototype.saveWorkInternal = function(closeAfterSave, saveForLater) {
    var notes = this.getNotesContent_(this.currentSubtitlePanel_);
    if (notes !== '') {
        this.serverModel_.setTaskNotes(notes);
    }

    if (goog.array.isEmpty(
        this.serverModel_.captionSet_.nonblankSubtitles())){
        // there are no subs here, close dialog or back to subtitling
        this.showEmptySubsDialog();
        return;
    }
    var that = this;
    this.getRightPanelInternal().showLoading(true);
    this.serverModel_.finish(
        function(serverMsg){
            unisubs.subtitle.OnSavedDialog.show(serverMsg, function(){
                that.onWorkSaved(closeAfterSave);
            });
        },
        function(opt_status) {
            if (that.finishFailDialog_)
                that.finishFailDialog_.failedAgain(opt_status);
            else
                that.finishFailDialog_ = unisubs.finishfaildialog.Dialog.show(
                    that.serverModel_.getCaptionSet(), opt_status,
                    goog.bind(that.saveWorkInternal, that, closeAfterSave));
        },
        null,
        saveForLater);
};
unisubs.translate.Dialog.prototype.showGuidelinesForState_ = function(state) {
    this.setState_(state);
};
unisubs.Dialog.prototype.setVisible = function(visible) {
    if (visible) {
        unisubs.Dialog.superClass_.setVisible.call(this, true);
        goog.dom.getDocumentScrollElement().scrollTop = 0;
    }
    else {
        if (this.isWorkSaved()) {
            this.hideDialogImpl_();
        }
        else {
            this.showSaveWorkDialog_();
        }
    }
};
unisubs.translate.Dialog.prototype.onWorkSaved = function() {
    if (this.finishFailDialog_) {
        this.finishFailDialog_.setVisible(false);
        this.finishFailDialog_ = null;
    }
    unisubs.widget.ResumeEditingRecord.clear();
    this.getRightPanelInternal().showLoading(false);
    this.saved_ = true;
    this.setVisible(false);
};
unisubs.translate.Dialog.prototype.disposeInternal = function() {
    unisubs.translate.Dialog.superClass_.disposeInternal.call(this);
    this.serverModel_.dispose();
};
unisubs.translate.Dialog.prototype.enterState_ = function(state) {
    this.showGuidelinesForState_(state);
};
unisubs.translate.Dialog.prototype.suspendKeyEvents_ = function(suspended) {
    this.keyEventsSuspended_ = suspended;
    if (this.currentSubtitlePanel_ && this.currentSubtitlePanel_.suspendKeyEvents)
        this.currentSubtitlePanel_.suspendKeyEvents(suspended);
};
unisubs.translate.Dialog.prototype.setState_ = function(state) {
    this.state_ = state;

    this.suspendKeyEvents_(false);

    var s = unisubs.translate.Dialog.State_;

    this.setExtraClass_();

    var nextSubPanel = this.makeCurrentStateSubtitlePanel_();
    var captionPanel = this.getCaptioningAreaInternal();
    captionPanel.removeChildren(true);
    captionPanel.addChild(nextSubPanel, true);

    var rightPanel = nextSubPanel.getRightPanel();
    this.setRightPanelInternal(rightPanel);

    this.getTimelinePanelInternal().removeChildren(true);

    if (this.currentSubtitlePanel_ && this.currentSubtitlePanel_.getNotesContent_){
       var currentNoteContent =  this.currentSubtitlePanel_.getNotesContent_();
       if (nextSubPanel  && nextSubPanel.setNotesContent_){
           nextSubPanel.setNotesContent_(currentNoteContent);
       }
    }

    this.disposeCurrentPanels_();
    this.currentSubtitlePanel_ = nextSubPanel;

    var et = unisubs.RightPanel.EventType;
    this.rightPanelListener_.
        listen(
            rightPanel, et.LEGENDKEY, this.handleLegendKeyPress_).
        listen(
            rightPanel, et.DONE, this.handleDoneKeyPress_).
        listen(
            rightPanel, et.SAVEANDEXIT, this.handleSaveAndExitKeyPress_).
        listen(
            rightPanel, et.GOTOSTEP, this.handleGoToStep_);
    var backButtonText = null;
    if (state == s.EDIT_METADATA ){
        backButtonText = "Back to Translation";
    }
    if (backButtonText){
        rightPanel.showBackLink(backButtonText);
        this.rightPanelListener_.listen(
            rightPanel, et.BACK, this.handleBackKeyPress_);

    }

    var videoPlayer = this.getVideoPlayerInternal();
    if (this.isInDocument()) {
        if (!videoPlayer.isPaused()){
            videoPlayer.pause();
        }
        if(videoPlayer.getPlayheadTime()){
            videoPlayer.setPlayheadTime(0);
            videoPlayer.pause();
        }
    }

    var that = this;
    this.getRightPanelInternal().showDownloadLink(
        function() {
            return that.makeJsonSubs();
        });
};
unisubs.translate.Dialog.prototype.makeCurrentStateSubtitlePanel_ = function() {
    var s = unisubs.translate.Dialog.State_;

    if (this.state_ == s.TRANSLATE){
        this.translationPanel_ =  new unisubs.translate.TranslationPanel(
            this.serverModel_.getCaptionSet(),
            this.standardSubState_,
            this,
            this.reviewOrApprovalType_,
            this.serverModel_);
        return this.translationPanel_;
    }
    else if (this.state_ == s.EDIT_METADATA)
        return new unisubs.editmetadata.Panel(
            this.serverModel_.getCaptionSet(),
            this.getVideoPlayerInternal(),
            this.serverModel_,
            this.captionManager_,
            this.standardSubState_ ,
            false,
            this.reviewOrApprovalType_,
            this);
};

/**
 * Tries translate subtitles with BingTranslator
 */
unisubs.translate.Dialog.prototype.translateViaBing = function(){
    //I don't know how better call this. I think it should be incapsulated in translationList_,
    //but have chain of function calls can confuse.
    this.translationPanel_.getTranslationList().translateViaBing(
        this.standardSubState_.LANGUAGE, this.subtitleState_.LANGUAGE);
};
unisubs.translate.Dialog.prototype.getStandardLanguage = function(){
    return this.standardSubState_.LANGUAGE;
};
unisubs.translate.Dialog.prototype.getSubtitleLanguage = function(){
    return this.subtitleState_.LANGUAGE;
};
unisubs.translate.Dialog.prototype.getServerModel = function(){
    return this.serverModel_;
};
unisubs.translate.Dialog.prototype.makeJsonSubs =  function (){
    return this.serverModel_.getCaptionSet().makeJsonSubs();
};
unisubs.translate.Dialog.prototype.forkAndClose = function() {
    var dialog = new unisubs.translate.ForkDialog(
        goog.bind(this.forkImpl_, this));
    dialog.setVisible(true);
};
unisubs.translate.Dialog.prototype.forkImpl_ = function() {
    this.subtitleState_.fork();
    this.serverModel_.fork(this.standardSubState_);
    this.hideToFork();
    this.opener_.openSubtitlingDialog(
        this.serverModel_,
        this.subtitleState_);
};
unisubs.translate.Dialog.prototype.disposeCurrentPanels_ = function() {
    if (this.currentSubtitlePanel_) {
        this.currentSubtitlePanel_.dispose();
        this.currentSubtitlePanel_ = null;
    }
    this.rightPanelListener_.removeAll();
    if (this.timelineSubtitleSet_) {
        this.timelineSubtitleSet_.dispose();
        this.timelineSubtitleSet_ = null;
    }
};
unisubs.subtitle.Dialog.prototype.captionReached_ = function(event) {
    var c = event.caption;
    this.getVideoPlayerInternal().showCaptionText(c ? c.getText() : '');
};
<|endoftext|>


<commit_before>const domReady = function (callback) {
	const state = document.readyState;
	if (state === 'interactive' || state === 'complete') {
		callback();
	} else {
		document.addEventListener('DOMContentLoaded', callback);
	}
};

domReady(function () {
	const projectname = document.createElement('a');
	projectname.classList.add('project-name');
	projectname.text = 'aureooms/js-partition';
	projectname.href = './index.html';

	const header = document.querySelectorAll('header')[0];
	header.insertBefore(projectname, header.firstChild);

	const testlink = document.querySelector('header > a[data-ice="testLink"]');
	testlink.href =
		'https://coveralls.io/github/make-github-pseudonymous-again/js-partition';
	testlink.target = '_BLANK';

	const searchBox = document.querySelector('.search-box');
	const input = document.querySelector('.search-input');

	// Active search box when focus on searchBox.
	input.addEventListener('focus', function () {
		searchBox.classList.add('active');
	});
});
<commit_msg>:robot: docs: Simplify scripts.<commit_after>const domReady = function (callback) {
	const state = document.readyState;
	if (state === 'interactive' || state === 'complete') {
		callback();
	} else {
		document.addEventListener('DOMContentLoaded', callback);
	}
};

domReady(function () {
	const projectname = document.createElement('a');
	projectname.classList.add('project-name');
	projectname.text = 'aureooms/js-partition';
	projectname.href = './index.html';

	const header = document.querySelector('header');
	header.insertBefore(projectname, header.firstChild);

	const testlink = document.querySelector('header > a[data-ice="testLink"]');
	testlink.href =
		'https://coveralls.io/github/make-github-pseudonymous-again/js-partition';
	testlink.target = '_BLANK';

	const searchBox = document.querySelector('.search-box');
	const input = document.querySelector('.search-input');

	// Active search box when focus on searchBox.
	input.addEventListener('focus', function () {
		searchBox.classList.add('active');
	});
});
<|endoftext|>


<commit_before>/*

// opera.scopeSendToHost(service, message)

onload = function() {
function put(str)
{
	document.getElementById('info').innerHTML += str + "
";
}

function enable_service(str)
{
	put('Enabling service ' + str);
	opera.scopeEnableService('console-logger');
}

function host_connected(services)
{
	put('Host connected');
	services = services.split(',');
	put("Host has services: " + services);
	enable_service(services[0]);
}
function receive(service, msg)
{
	put('Got data on service ' + service +':
' + msg + '
');
}
function quit()
{
	put('Host quit');
}

opera.scopeAddClient(host_connected, receive, quit);
put('Ready.');
}

*/

var client = new function()
{
  var self = this;

  var services = [];
  var services_dict = {};
  var services_avaible = {};

  this.addService = function(service)
  {
    services[services.length] = service;
    services_dict[service.name] = service;
  }

  var host_connected = function(_services)
  {
    opera.postError('on host_connected: '+_services);
    services_avaible = eval("({\"" + _services.replace(/,/g, "\":1,\"") + "\":1})");
    var service = null, i = 0;
    for( ; service = services[i]; i++)
    {
      if (service.name in services_avaible)
      {
        opera.postError(service.name);
        opera.scopeEnableService(service.name);
      }
      else
      {
        alert
        (
           'Service is avaible: ' + service.name
        );

      }
    }

  }

  var receive = function(service, msg)
  {
    opera.postError(service+' '+msg);
    var xml_doc = ( new DOMParser() ).parseFromString(msg, "application/xml");
    if(xml_doc)
    {
      services_dict[service].onreceive(xml_doc);
    }
  }

  var quit = function()
  {
    alert('Session quited');
  }

  this.setup = function()
  {

    document.addEventListener('load', arguments.callee, false);

    var args = location.search, params = {}, arg = '', i = 0, ele = null;

    if( args )
    {
      args = args.slice(1).split(';');
      for( ; arg = args[i]; i++)
      {
        arg = arg.split('=');
        params[arg[0]] = arg[1] ? arg[1] : true;
      }
    }
    if( params.debug || params['event-flow'] )
    {
      Debug.init();
      if(params.debug) ini.debug = true;
      if(params['event-flow']) window.__debug_event_flow__ = true;
    }

    if( params['profiling'] )
    {
      Debug.init();
      window.__profiling__ = true;
      window.__times__ = [];
    }

    if( params['test'] )
    {
      Debug.init();
      window.__testing__ = true;
      window.__times_spotlight__ = [];
    }

    if( params['profile-dom'] )
    {
      Debug.init();
      window.__times_dom = [];
    }

    window[defaults.viewport] = document.getElementsByTagName(defaults.viewport_main_container)[0];

    if( viewport )
    {
      setupMarkup();

      opera.scopeAddClient(host_connected, receive, quit);
      opera.postError('opera.scopeAddClient');

    }
    else
    {
      opera.postError('missing viewport');
    }

  }

  var setupMarkup = function()
  {

    UIBase.copyCSS(resolve_map);

    // TODO clean up

    container = viewport.appendChild(document.createElement('div'));
    container.style.cssText = 'position:absolute;top:0;left:-1000px;';
    container.innerHTML = resolve_map_2.markup;

    var set = null, i = 0;

    for( ; set = resolve_map_2[i]; i++ )
    {
      defaults[set.target] = set.getValue();
    }
    viewport.removeChild(container);

    new CompositeView('console_new', 'Console', console_rough_layout);
    new CompositeView('js_new', 'JS', js_rough_layout);
    new CompositeView('dom_new', 'DOM', dom_rough_layout);

    window.topCell = new TopCell
    (
      main_layout,
      function()
      {
        this.top = 0;
        this.left = 0;
        this.width = innerWidth;
        this.height = innerHeight;
      },
      function()
      {
        this.setStartDimesions();
        this.update();
        this.setup();
      }
    );

    new SlideViews(document);
  }

  this.onquit = function()
  {
    viewport.render
    (
      ['div',
        ['h2', 'There is no longer a connection to the proxy'],
      'class', 'info']

    );
  }

  this.post = function(service, msg)
  {
    opera.postError('command: '+service+' '+ msg)
    opera.scopeSendToHost(service, msg)
  }

  document.addEventListener('load', this.setup, false);

}

/* TODO take that out from the global scope */

new ToolbarConfig
(
  'main-view',
  [
    {
      handler: 'create-all-runtimes',
      title: 'Create all runtimes'
    }
  ]
)

var console_rough_layout =
{
  dir: 'v', width: 700, height: 700,
  children:
  [
    { height: 200, tabs: ['runtimes'] },
    { height: 200, tabs: ['console'] }
  ]
}

var dom_rough_layout =
{
  dir: 'h', width: 700, height: 700,
  children:
  [
    { width: 200, tabs: ['dom-markup-style', 'dom-tree-style'] }
  ]
}

var js_rough_layout =
{
  dir: 'h', width: 700, height: 700,
  children:
  [
    { width: 650, tabs: ['js_source']},
    {
      width: 300,
      children:
      [
        { height: 250, tabs: ['callstack'] },
        { height: 1000, tabs: ['frame_inspection'] }
      ]
    }
  ]
}

var main_layout =
{
  id: 'main-view',
  tabs: ['console_new', 'js_new', 'dom_new']
}

var resolve_map_properties =
[
  {s_name: 'border-top-width'},
  {s_name: 'border-right-width'},
  {s_name: 'border-bottom-width'},
  {s_name: 'border-left-width'},
  {s_name: 'padding-top'},
  {s_name: 'padding-right'},
  {s_name: 'padding-bottom'},
  {s_name: 'padding-left'},
  {s_name: 'width'},
  {s_name: 'height'}
]

var resolve_map =
[
  {
    source: 'toolbar',
    target: Toolbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'tabs',
    target: Tabs.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'container',
    target: Container.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-tabs',
    target: TopTabs.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-container',
    target: TopContainer.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-statusbar',
    target: Statusbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-toolbar',
    target: TopToolbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-toolbar',
    target: WindowToolbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-header',
    target: defaults,
    properties:
    [
      {
        t_name: 'window_header_offsetHeight',
        setProp: function(source, decalaration)
        {
          return source.offsetHeight;
        }
      }
    ]
  },
  {
    source: 'window-container',
    target: WindowContainer.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-satusbar',
    target: WindowStatusbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-statusbar',
    target: defaults,
    properties:
    [
      {
        t_name: 'window_statusbar_offsetHeight',
        setProp: function(source, decalaration)
        {
          return source.offsetHeight;
        }
      }
    ]
  },
];

var resolve_map_2 =
[
  {
    id: 'test-line-height',
    property: 'lineHeight',
    target: 'js-source-line-height',
    getValue: function(){return parseInt(document.getElementById(this.id).currentStyle[this.property])}
  },
  {
    id: 'test-scrollbar-width',
    target: 'scrollbar-width',
    getValue: function(){return ( 100 - document.getElementById(this.id).offsetWidth )}
  }
];

resolve_map_2.markup =
  "
"+
    "
"+
      "
"+
        "
test
"+
        "
"+
          "

"+
        "
"
      "
"+
    "
"+
  "
";

<commit_msg>Make sure client sends well-formed XML.<commit_after>/*

// opera.scopeSendToHost(service, message)

onload = function() {
function put(str)
{
	document.getElementById('info').innerHTML += str + "
";
}

function enable_service(str)
{
	put('Enabling service ' + str);
	opera.scopeEnableService('console-logger');
}

function host_connected(services)
{
	put('Host connected');
	services = services.split(',');
	put("Host has services: " + services);
	enable_service(services[0]);
}
function receive(service, msg)
{
	put('Got data on service ' + service +':
' + msg + '
');
}
function quit()
{
	put('Host quit');
}

opera.scopeAddClient(host_connected, receive, quit);
put('Ready.');
}

*/

var client = new function()
{
  var self = this;

  var services = [];
  var services_dict = {};
  var services_avaible = {};

  this.addService = function(service)
  {
    services[services.length] = service;
    services_dict[service.name] = service;
  }

  var host_connected = function(_services)
  {
    opera.postError('on host_connected: '+_services);
    services_avaible = eval("({\"" + _services.replace(/,/g, "\":1,\"") + "\":1})");
    var service = null, i = 0;
    for( ; service = services[i]; i++)
    {
      if (service.name in services_avaible)
      {
        opera.postError(service.name);
        opera.scopeEnableService(service.name);
      }
      else
      {
        alert
        (
           'Service is avaible: ' + service.name
        );

      }
    }

  }

  var receive = function(service, msg)
  {
    opera.postError(service+' '+msg);
    var xml_doc = ( new DOMParser() ).parseFromString(msg, "application/xml");
    if(xml_doc)
    {
      services_dict[service].onreceive(xml_doc);
    }
  }

  var quit = function()
  {
    alert('Session quited');
  }

  this.setup = function()
  {

    document.addEventListener('load', arguments.callee, false);

    var args = location.search, params = {}, arg = '', i = 0, ele = null;

    if( args )
    {
      args = args.slice(1).split(';');
      for( ; arg = args[i]; i++)
      {
        arg = arg.split('=');
        params[arg[0]] = arg[1] ? arg[1] : true;
      }
    }
    if( params.debug || params['event-flow'] )
    {
      Debug.init();
      if(params.debug) ini.debug = true;
      if(params['event-flow']) window.__debug_event_flow__ = true;
    }

    if( params['profiling'] )
    {
      Debug.init();
      window.__profiling__ = true;
      window.__times__ = [];
    }

    if( params['test'] )
    {
      Debug.init();
      window.__testing__ = true;
      window.__times_spotlight__ = [];
    }

    if( params['profile-dom'] )
    {
      Debug.init();
      window.__times_dom = [];
    }

    window[defaults.viewport] = document.getElementsByTagName(defaults.viewport_main_container)[0];

    if( viewport )
    {
      setupMarkup();

      opera.scopeAddClient(host_connected, receive, quit);
      opera.postError('opera.scopeAddClient');

    }
    else
    {
      opera.postError('missing viewport');
    }

  }

  var setupMarkup = function()
  {

    UIBase.copyCSS(resolve_map);

    // TODO clean up

    container = viewport.appendChild(document.createElement('div'));
    container.style.cssText = 'position:absolute;top:0;left:-1000px;';
    container.innerHTML = resolve_map_2.markup;

    var set = null, i = 0;

    for( ; set = resolve_map_2[i]; i++ )
    {
      defaults[set.target] = set.getValue();
    }
    viewport.removeChild(container);

    new CompositeView('console_new', 'Console', console_rough_layout);
    new CompositeView('js_new', 'JS', js_rough_layout);
    new CompositeView('dom_new', 'DOM', dom_rough_layout);

    window.topCell = new TopCell
    (
      main_layout,
      function()
      {
        this.top = 0;
        this.left = 0;
        this.width = innerWidth;
        this.height = innerHeight;
      },
      function()
      {
        this.setStartDimesions();
        this.update();
        this.setup();
      }
    );

    new SlideViews(document);
  }

  this.onquit = function()
  {
    viewport.render
    (
      ['div',
        ['h2', 'There is no longer a connection to the proxy'],
      'class', 'info']

    );
  }

  this.post = function(service, msg)
  {
    opera.postError('command: '+service+' '+ msg)
    opera.scopeSendToHost(service, "<?xml version=\"1.0\"?>" + msg)
  }

  document.addEventListener('load', this.setup, false);

}

/* TODO take that out from the global scope */

new ToolbarConfig
(
  'main-view',
  [
    {
      handler: 'create-all-runtimes',
      title: 'Create all runtimes'
    }
  ]
)

var console_rough_layout =
{
  dir: 'v', width: 700, height: 700,
  children:
  [
    { height: 200, tabs: ['runtimes'] },
    { height: 200, tabs: ['console'] }
  ]
}

var dom_rough_layout =
{
  dir: 'h', width: 700, height: 700,
  children:
  [
    { width: 200, tabs: ['dom-markup-style', 'dom-tree-style'] }
  ]
}

var js_rough_layout =
{
  dir: 'h', width: 700, height: 700,
  children:
  [
    { width: 650, tabs: ['js_source']},
    {
      width: 300,
      children:
      [
        { height: 250, tabs: ['callstack'] },
        { height: 1000, tabs: ['frame_inspection'] }
      ]
    }
  ]
}

var main_layout =
{
  id: 'main-view',
  tabs: ['console_new', 'js_new', 'dom_new']
}

var resolve_map_properties =
[
  {s_name: 'border-top-width'},
  {s_name: 'border-right-width'},
  {s_name: 'border-bottom-width'},
  {s_name: 'border-left-width'},
  {s_name: 'padding-top'},
  {s_name: 'padding-right'},
  {s_name: 'padding-bottom'},
  {s_name: 'padding-left'},
  {s_name: 'width'},
  {s_name: 'height'}
]

var resolve_map =
[
  {
    source: 'toolbar',
    target: Toolbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'tabs',
    target: Tabs.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'container',
    target: Container.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-tabs',
    target: TopTabs.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-container',
    target: TopContainer.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-statusbar',
    target: Statusbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'top-toolbar',
    target: TopToolbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-toolbar',
    target: WindowToolbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-header',
    target: defaults,
    properties:
    [
      {
        t_name: 'window_header_offsetHeight',
        setProp: function(source, decalaration)
        {
          return source.offsetHeight;
        }
      }
    ]
  },
  {
    source: 'window-container',
    target: WindowContainer.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-satusbar',
    target: WindowStatusbar.prototype,
    properties: resolve_map_properties
  },
  {
    source: 'window-statusbar',
    target: defaults,
    properties:
    [
      {
        t_name: 'window_statusbar_offsetHeight',
        setProp: function(source, decalaration)
        {
          return source.offsetHeight;
        }
      }
    ]
  },
];

var resolve_map_2 =
[
  {
    id: 'test-line-height',
    property: 'lineHeight',
    target: 'js-source-line-height',
    getValue: function(){return parseInt(document.getElementById(this.id).currentStyle[this.property])}
  },
  {
    id: 'test-scrollbar-width',
    target: 'scrollbar-width',
    getValue: function(){return ( 100 - document.getElementById(this.id).offsetWidth )}
  }
];

resolve_map_2.markup =
  "
"+
    "
"+
      "
"+
        "
test
"+
        "
"+
          "

"+
        "
"
      "
"+
    "
"+
  "
";

<|endoftext|>


<commit_before>
import Observer from '../observer/Observer';
import ObservableHandler from '../observer/ObservableHandler';
import View from './View';

class ViewHandler extends ObservableHandler {

    constructor(loadingClient) {
        this._loadingClient = loadingClient;
        this._views = {};
    }

    get listenersToDispatch() {
        const listeners = [];
        for (let viewId in this._views) {
            const view = this._views[viewId];
            if (view.changed()) {
                listeners = listeners.concat(view.listeners);
            }
        }
        return listeners;
    }

    createObserver() {
        return new Observer('view');
    }

    clearAllChanges() {
        for (let viewId in this._views) {
            this._views[viewId].clearAllChanges();
        }
        return this;
    }

    exists(viewId) {
        return this._views.hasOwnProperty(viewId);
    }

    find(viewId) {
        return this.exists(viedId) ? this._view[viewId] : undefined;
    }

    findOrCreateByBuilder(builder) {
        const viewId = builder.itemType + '-' + builder->buildHash();
        if (!this.exists(viewId)) {
            this._views[viewId] = new View(viewId, builder, this);
        }
        return this._views[viewId];
    }

    load(view) {
        this._loadingClient.load(view);
        return this;
    }
}

export default ViewHandler;<commit_msg>code cleanup<commit_after>
import Observer from '../observer/Observer';
import ObservableHandler from '../observer/ObservableHandler';
import View from './View';

class ViewHandler extends ObservableHandler {

    constructor(client) {
        this._client = client;
        this._views = {};
    }

    get listenersToDispatch() {
        const listeners = [];
        for (let viewId in this._views) {
            const view = this._views[viewId];
            if (view.changed()) {
                listeners = listeners.concat(view.listeners);
            }
        }
        return listeners;
    }

    createObserver() {
        return new Observer('view');
    }

    clearAllChanges() {
        for (let viewId in this._views) {
            this._views[viewId].clearAllChanges();
        }
        return this;
    }

    exists(viewId) {
        return this._views.hasOwnProperty(viewId);
    }

    find(viewId) {
        return this.exists(viedId) ? this._view[viewId] : undefined;
    }

    findOrCreateByBuilder(builder) {
        const viewId = builder.itemType + '-' + builder->buildHash();
        if (!this.exists(viewId)) {
            this._views[viewId] = new View(viewId, builder, this);
        }
        return this._views[viewId];
    }

    load(view) {
        this._client.load(view);
        return this;
    }
}

export default ViewHandler;<|endoftext|>