<commit_before>{
    vidyoComponents : null,
    loaded: {
        session: false,
        contribution: false
    },

    start : function(booking, iframeElement) {
        window.open(booking.url);
    },

    checkStart : function(booking) {
        booking.permissionToStart = true;
        return true;
    },

    checkConnect : function(booking) {
        booking.permissionToConnect = true;
        return true;
    },

    checkDisconnect : function(booking) {
        booking.permissionToDisconnect = true;
        return true;
    },

    checkParams: function() {
        var self = this;
        return {
            'roomName' : ['text', false, function(name, values){
                var maxNameLength = ${ MaxNameLength };
                var errors = [];
                if (name.length > maxNameLength) {
                    errors.push($T("The room name cannot be longer than ") + maxNameLength + $T(" characters."));
                }
                if (name.length == 0) {
                    errors.push($T("The room name has not been defined"));
                }
                return errors;
            }],
            'roomDescription' : ['text', false],
            'pin': ['non_negative_int', true],
            'moderatorPin': ['non_negative_int', true],
            'videoLinkSession': ['text', true, function(option, values){
                var errors = [];
                if(self.vidyoComponents["link"].get()=="session" && ["","None"].indexOf(option)!=-1){
                    errors.push($T("No session has been defined."));
                }
                return errors;
            }],
            'videoLinkContribution': ['text', true, function(option, values){
                var errors = [];
                if(self.vidyoComponents["link"].get()=="contribution" && ["","None"].indexOf(option)!=-1){
                    errors.push($T("No contribution has been defined."));
                }
                return errors;
            }]
        };
    },

    errorHandler: function(event, error, booking, popup) {
        if (event === 'create' || event === 'edit') {
            if (error.errorType === 'invalidName') {
                var message = $T("That room name is not valid. Please write a new name that starts " +
                                 "with a letter or a number, and does not contain punctuation, except periods, underscores or dashes. " +
                                 "Unicode characters are allowed (é, ñ, 漢字) but some may cause problems.");
                IndicoUtil.markInvalidField($E('roomName'), message);
            }

            if (error.errorType === 'invalidDescription') {
                var message = $T("That room description is not valid. Maybe an Unicode character is causing a problem.");
                IndicoUtil.markInvalidField($E('roomDescription'), message);
            }

            if (error.errorType === 'nameTooLong') {
                var message = $T("The room name cannot be longer than ") + ${ MaxNameLength } + $T(" characters.");
                IndicoUtil.markInvalidField($E('roomName'), message);
            }

            if (error.errorType === 'duplicated') {
                // the name is duplicated
                var message = $T("There is already a Vidyo Public Room in this event with the same name. Please give a different name to the room.");
                IndicoUtil.markInvalidField($E('roomName'), message);

            }
            if (error.errorType === 'duplicatedWithOwner') {
                var conferenceId = this.vidyoComponents.params.conference;
                var handler = function(confirm) {
                    if (confirm) {
                        attachBooking(booking, "Vidyo", conferenceId);
                        popup.close();
                    }
                };
                var container = $('<div/>').css("max-width", "550px");
                var warningMessage = $('<div/>').addClass("warningMessage").css("text-align", "justify").append($T('Please be aware that if you attach the room, the data you may have filled in the form (Meeting PIN, Moderator PIN, description, owner, etc) will not be taken into account. Instead, the data from the original attached room will be used.'));
                container.append(warningMessage);
                container.append(error.userMessage);
                new ConfirmPopup($T('Attach room'), container.get(0), handler, $T("Attach room")).open();
            }
            if (error.errorType === 'badOwner') {
                CSErrorPopup($T("Invalid owner"), [$T("The user ") + this.vidyoComponents["ownerField"].get().name + $T(" does not have a Vidyo account.")]);
            }

            if (error.errorType === 'userHasNoAccounts') {
                CSErrorPopup($T("Invalid owner"), [$T("The user ") + this.vidyoComponents["ownerField"].get().name + $T(" is currently not registered to use Vidyo, please see http://cern.ch/Vidyo for how to register")]);
            }
            if (error.errorType === 'sessionNotDefined') {
                CSErrorPopup($T("No session defined"), [$T("A session must be set.")]);
            }
            if (error.errorType === 'contributionNotDefined') {
                CSErrorPopup($T("Invalid owner"), [$T("A contribution must be set.")]);
            }

        }

        if (event === 'attach' && error.errorType === 'notValidRoom') {
            CSErrorPopup($T("Duplicate room name"), [error.userMessage]);
        }

        if (event === 'attach' && error.errorType === 'duplicated') {
            CSErrorPopup($T("Public room duplicated name"),
                    [$T("There is already a Vidyo Public Room linked to this event with the same name."),
                     $T("Please give a different name to the room.")]);
        }

        if ((event === 'edit' || event === 'checkStatus' || event === 'connect') && error.errorType === 'unknownRoom') {
            vidyoMarkBookingNotPresent(booking);
            CSErrorPopup($T("Public room removed in Vidyo"),
                    [$T("This public room seems to have been deleted in Vidyo."),
                     $T("Please delete it and try to create it again.")]);
        }

        if (event === 'connect' && error.errorType === 'noValidConferenceRoom') {
            CSErrorPopup($T("Not valid conference room"),
                    [$T("The conference room is not a valid Vidyo capable room."),
                     $T("Please select one that is Vidyo capable.")]);
        }

        if (event === 'connect' && error.errorType === 'noExistsRoom') {
            CSErrorPopup($T("Connect room failed"),[error.userMessage]);
        }

        if (event === 'connect' && error.errorType === 'connectFailed') {
            CSErrorPopup($T("Connect room failed"),[error.userMessage]);
        }

        if (event === 'connect' && error.errorType === 'alreadyConnected') {
            CSErrorPopup($T("Already connected"),[error.userMessage]);
        }

        if (event === 'disconnect' && error.errorType === 'disconnectFailed') {
            CSErrorPopup($T("Disconnect room failed"),[error.userMessage]);
        }
        if (event === 'disconnect' && error.errorType === 'alreadyDisconnected') {
            CSErrorPopup($T("Already disconnected"),[error.userMessage]);
        }
        if (event === 'roomConnected' && error.errorType === 'roomCheckFailed') {
            CSErrorPopup($T("Room connection status failed"),[error.userMessage]);
        }
    },

    customText: function(booking) {
        if (!booking.error) {
            return $T("Ext: ") + booking.extension + $T("; Linked to: ") + Util.truncate(booking.linkVideoText, 15);
        } else {
            return '';
        }
    },

    showInfo : function(booking) {
        var infoTbody = Html.tbody();

        if (booking.error && booking.errorDetails) {
            var errorCell = Html.td({colspan:2, colSpan:2});
            errorCell.append(Html.span('collaborationWarning', booking.errorDetails));
            infoTbody.append(Html.tr({}, errorCell));
        }

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Room name:')),
            Html.td({}, booking.bookingParams.roomName)));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Extension:')),
            Html.td({}, booking.extension)));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Room moderator:')),
            Html.td({}, booking.bookingParams.owner.name)));

        var moderatorPinInfo;
        if (booking.bookingParams.hasModeratorPin) {
            moderatorPinInfo = new HiddenText(booking.bookingParams.moderatorPin, Html.span("VidyoHiddenModeratorPIN", "********"), false).draw();
        } else {
            moderatorPinInfo = $T("No moderator PIN was defined");
        }

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Moderator PIN:')),
                Html.td({}, moderatorPinInfo)));

        var pinInfo;
        if (booking.bookingParams.hasPin) {
            pinInfo = new HiddenText(booking.bookingParams.pin, Html.span("HiddenPIN", "********"), false).draw();
        } else {
            pinInfo = $T("No meeting PIN was defined");
        }

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Meeting PIN:')),
                Html.td({}, pinInfo)));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Description:')),
            Html.td({}, booking.bookingParams.roomDescription)));

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Auto-join URL:')),
                Html.td({}, booking.url ? Html.a({href:booking.url}, booking.url) : $T("not assigned yet"))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Visibility:')),
            Html.td({}, booking.bookingParams.hidden? $T("Hidden") : $T("Visible"))));

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Auto-Mute:')),
                Html.td({}, booking.bookingParams.autoMute? $T("Enabled") : $T("Disabled"))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Created on:')),
            Html.td({}, formatDateTimeCS(booking.creationDate))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Last modified on:')),
            Html.td({}, formatDateTimeCS(booking.modificationDate))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Linked to:')),
            Html.td({}, booking.linkVideoText)));

        return Html.div({}, Html.table({}, infoTbody));
    },

    observeRadioButtons: function(vidyoComponents) {
        var self = this;

        vidyoComponents["link"].observe(function(value){
            switch(value) {
            case"session":
                if (vidyoComponents["changed"] == false) {
                    vidyoComponents["dummy"] = $('#videoEventLinkSelection').html();
                    vidyoComponents["changed"] = true;
                }
                if(self.loaded["session"] === true && vidyoComponents["session"]){
                    $E('videoEventLinkSelection').set(vidyoComponents["session"].draw());
                }else{
                    $E('videoEventLinkSelection').set(progressIndicator(true, true));
                }
                break;
            case"contribution":
                if (vidyoComponents["changed"] == false) {
                    vidyoComponents["dummy"] = $('#videoEventLinkSelection').html();
                    vidyoComponents["changed"] = true;
                }
                if(self.loaded["contribution"] === true && vidyoComponents["contribution"]){
                    $E('videoEventLinkSelection').set(vidyoComponents["contribution"].draw());
                }else{
                    $E('videoEventLinkSelection').set(progressIndicator(true, true));
                }

                break;
            case"None":
            default:
                if (vidyoComponents["changed"]) {
                    $('#videoEventLinkSelection').html(vidyoComponents["dummy"]);
                }
                break;
            }
        });
    },

    getVidyoComponents : function(ajaxPending) {
        var self = this;
        var params = {conference : confId};

        self.vidyoComponents = {
            params : params,
            ownerField : new SingleUserField(${ jsonEncode(LoggedInUser) },
                'owner',
                true, true, null,
                null, false,
                false, false,
                singleUserNothing, singleUserNothing),
            pinField : new ShowablePasswordField('pin', '', false),
            moderatorPinField : new ShowablePasswordField('moderatorPin', '', false),
            link : new RadioFieldWidget([
                 ['event', $T("Leave default Vidyo association")],
                 ['contribution', $T("Link to a contribution")],
                 ['session', $T("Link to a session")]
             ], 'nobulletsListInline','videoLinkType'),
            session :new SelectRemoteWidget('event.sessions.listAll',
                params, function() {
                        ajaxPending["session"].resolve();
                }, 'videoLinkSession', "No sessions"),
            contribution : new SelectRemoteWidget('event.contributions.listAll',
                params, function() {
                        ajaxPending["contribution"].resolve();
                }, 'videoLinkContribution', "No contributions"),
            autoMuteField : $("<input/>").attr({type:"checkbox",name:"autoMute", id:"autoMute", value:"yes", "checked":true}).css("vertical-align", "middle")[0],
            dummy : "",
            changed : false
        };

        return self.vidyoComponents;
    },

    addComponents: function(bookingPopup){
        var self = this;
        self.loaded["session"] = false;
        self.loaded["contribution"] = false;
        ajaxPending= {
            session : $.Deferred(),
            contribution : $.Deferred()
        };

        var vidyoComponents = self.getVidyoComponents(ajaxPending);

        $E('owner').set(vidyoComponents["ownerField"].draw());
        $E('PINField').set(vidyoComponents["pinField"].draw());
        $E('moderatorPINField').set(vidyoComponents["moderatorPinField"].draw());
        $E('videoEventLinkType').set(vidyoComponents["link"].draw());
        $E('autoMuteField').set(vidyoComponents["autoMuteField"]);

        bookingPopup.addComponent(vidyoComponents["ownerField"]);
        bookingPopup.addComponent(vidyoComponents["pinField"]);
        bookingPopup.addComponent(vidyoComponents["moderatorPinField"]);
        bookingPopup.addComponent(vidyoComponents["autoMuteField"]);
        bookingPopup.addComponent(vidyoComponents["session"]);
        bookingPopup.addComponent(vidyoComponents["contribution"]);
        bookingPopup.addComponent(vidyoComponents["link"]); /* This must be the last component added. */
        vidyoDrawContextHelpIcons(vidyoComponents["pinField"]);

        $.when(ajaxPending["session"]).done(function() {
            if(vidyoComponents["link"].get() == "session"){
                $E('videoEventLinkSelection').set(vidyoComponents["session"].draw());
            }
            self.loaded["session"] = true;
        });

        $.when(ajaxPending["contribution"]).done(function() {
            if(vidyoComponents["link"].get() == "contribution"){
                $E('videoEventLinkSelection').set(vidyoComponents["contribution"].draw());
            }
            self.loaded["contribution"] = true;
        });

        self.observeRadioButtons(vidyoComponents);

        if(bookingPopup.booking !== undefined){
            if(bookingPopup.booking.isRoomInMultipleBookings) $(".redWarningMessage").show();
            else $(".redWarningMessage").hide();
        }
        return vidyoComponents;
    },

    onCreate: function(bookingPopup) {
        var vidyoComponents = this.addComponents(bookingPopup);
        vidyoComponents["link"].select('event');

    },

    onEdit: function(booking, bookingPopup) {
        this.addComponents(bookingPopup);
    },

    postCreate: function(booking) {
    },

    postEdit: function(booking) {
    },

    postCheckStatus: function(booking) {
        if (booking.warning) {
            if (booking.warning === 'invalidName') {
                var popup = new AlertPopup($T("Problem retrieving the room name"),
                        Html.span({}, $T("The room name could not be decoded and updated in Indico."),
                                      Html.br(),
                                      $T("Maybe it contains some Unicode characters that Indico is not able to handle.")));
                popup.open();
            }
            if (booking.warning === 'invalidDescription') {
                var popup = new AlertPopup($T("Problem retrieving the description text"),
                        Html.span({}, $T("The description text could not be decoded and updated in Indico."),
                                      Html.br(),
                                      $T("Maybe it contains some Unicode characters that Indico is not able to handle.")));
                popup.open();
            }
        }
    },

    postDelete: function(booking) {
        if (booking.warning) {
            if (booking.warning === 'cannotDeleteNonExistant') {
                var popup = new AlertPopup($T("Public room deletion"),
                        Html.span({}, $T("The public room was deleted successfully from Indico."),
                                      Html.br(),
                                      $T("However, please note that the public room had already been removed from the Vidyo system previously.")));
                popup.open();
            }
        }
    }
}

<commit_msg>[FIX] Duplicated name Vidyo error message<commit_after>{
    vidyoComponents : null,
    loaded: {
        session: false,
        contribution: false
    },

    start : function(booking, iframeElement) {
        window.open(booking.url);
    },

    checkStart : function(booking) {
        booking.permissionToStart = true;
        return true;
    },

    checkConnect : function(booking) {
        booking.permissionToConnect = true;
        return true;
    },

    checkDisconnect : function(booking) {
        booking.permissionToDisconnect = true;
        return true;
    },

    checkParams: function() {
        var self = this;
        return {
            'roomName' : ['text', false, function(name, values){
                var maxNameLength = ${ MaxNameLength };
                var errors = [];
                if (name.length > maxNameLength) {
                    errors.push($T("The room name cannot be longer than ") + maxNameLength + $T(" characters."));
                }
                if (name.length == 0) {
                    errors.push($T("The room name has not been defined"));
                }
                return errors;
            }],
            'roomDescription' : ['text', false],
            'pin': ['non_negative_int', true],
            'moderatorPin': ['non_negative_int', true],
            'videoLinkSession': ['text', true, function(option, values){
                var errors = [];
                if(self.vidyoComponents["link"].get()=="session" && ["","None"].indexOf(option)!=-1){
                    errors.push($T("No session has been defined."));
                }
                return errors;
            }],
            'videoLinkContribution': ['text', true, function(option, values){
                var errors = [];
                if(self.vidyoComponents["link"].get()=="contribution" && ["","None"].indexOf(option)!=-1){
                    errors.push($T("No contribution has been defined."));
                }
                return errors;
            }]
        };
    },

    errorHandler: function(event, error, booking, popup) {
        if (event === 'create' || event === 'edit') {
            if (error.errorType === 'invalidName') {
                var message = $T("That room name is not valid. Please write a new name that starts " +
                                 "with a letter or a number, and does not contain punctuation, except periods, underscores or dashes. " +
                                 "Unicode characters are allowed (é, ñ, 漢字) but some may cause problems.");
                IndicoUtil.markInvalidField($E('roomName'), message);
            }

            if (error.errorType === 'invalidDescription') {
                var message = $T("That room description is not valid. Maybe an Unicode character is causing a problem.");
                IndicoUtil.markInvalidField($E('roomDescription'), message);
            }

            if (error.errorType === 'nameTooLong') {
                var message = $T("The room name cannot be longer than ") + ${ MaxNameLength } + $T(" characters.");
                IndicoUtil.markInvalidField($E('roomName'), message);
            }

            if (error.errorType === 'duplicated') {
                // the name is duplicated
                var message = $T("There is already a Vidyo Room in the system with the same name. Please give a different name to the room.");
                IndicoUtil.markInvalidField($E('roomName'), message);

            }
            if (error.errorType === 'duplicatedWithOwner') {
                var conferenceId = this.vidyoComponents.params.conference;
                var handler = function(confirm) {
                    if (confirm) {
                        attachBooking(booking, "Vidyo", conferenceId);
                        popup.close();
                    }
                };
                var container = $('<div/>').css("max-width", "550px");
                var warningMessage = $('<div/>').addClass("warningMessage").css("text-align", "justify").append($T('Please be aware that if you attach the room, the data you may have filled in the form (Meeting PIN, Moderator PIN, description, owner, etc) will not be taken into account. Instead, the data from the original attached room will be used.'));
                container.append(warningMessage);
                container.append(error.userMessage);
                new ConfirmPopup($T('Attach room'), container.get(0), handler, $T("Attach room")).open();
            }
            if (error.errorType === 'badOwner') {
                CSErrorPopup($T("Invalid owner"), [$T("The user ") + this.vidyoComponents["ownerField"].get().name + $T(" does not have a Vidyo account.")]);
            }

            if (error.errorType === 'userHasNoAccounts') {
                CSErrorPopup($T("Invalid owner"), [$T("The user ") + this.vidyoComponents["ownerField"].get().name + $T(" is currently not registered to use Vidyo, please see http://cern.ch/Vidyo for how to register")]);
            }
            if (error.errorType === 'sessionNotDefined') {
                CSErrorPopup($T("No session defined"), [$T("A session must be set.")]);
            }
            if (error.errorType === 'contributionNotDefined') {
                CSErrorPopup($T("Invalid owner"), [$T("A contribution must be set.")]);
            }

        }

        if (event === 'attach' && error.errorType === 'notValidRoom') {
            CSErrorPopup($T("Duplicate room name"), [error.userMessage]);
        }

        if (event === 'attach' && error.errorType === 'duplicated') {
            CSErrorPopup($T("Public room duplicated name"),
                    [$T("There is already a Vidyo Public Room linked to this event with the same name."),
                     $T("Please give a different name to the room.")]);
        }

        if ((event === 'edit' || event === 'checkStatus' || event === 'connect') && error.errorType === 'unknownRoom') {
            vidyoMarkBookingNotPresent(booking);
            CSErrorPopup($T("Public room removed in Vidyo"),
                    [$T("This public room seems to have been deleted in Vidyo."),
                     $T("Please delete it and try to create it again.")]);
        }

        if (event === 'connect' && error.errorType === 'noValidConferenceRoom') {
            CSErrorPopup($T("Not valid conference room"),
                    [$T("The conference room is not a valid Vidyo capable room."),
                     $T("Please select one that is Vidyo capable.")]);
        }

        if (event === 'connect' && error.errorType === 'noExistsRoom') {
            CSErrorPopup($T("Connect room failed"),[error.userMessage]);
        }

        if (event === 'connect' && error.errorType === 'connectFailed') {
            CSErrorPopup($T("Connect room failed"),[error.userMessage]);
        }

        if (event === 'connect' && error.errorType === 'alreadyConnected') {
            CSErrorPopup($T("Already connected"),[error.userMessage]);
        }

        if (event === 'disconnect' && error.errorType === 'disconnectFailed') {
            CSErrorPopup($T("Disconnect room failed"),[error.userMessage]);
        }
        if (event === 'disconnect' && error.errorType === 'alreadyDisconnected') {
            CSErrorPopup($T("Already disconnected"),[error.userMessage]);
        }
        if (event === 'roomConnected' && error.errorType === 'roomCheckFailed') {
            CSErrorPopup($T("Room connection status failed"),[error.userMessage]);
        }
    },

    customText: function(booking) {
        if (!booking.error) {
            return $T("Ext: ") + booking.extension + $T("; Linked to: ") + Util.truncate(booking.linkVideoText, 15);
        } else {
            return '';
        }
    },

    showInfo : function(booking) {
        var infoTbody = Html.tbody();

        if (booking.error && booking.errorDetails) {
            var errorCell = Html.td({colspan:2, colSpan:2});
            errorCell.append(Html.span('collaborationWarning', booking.errorDetails));
            infoTbody.append(Html.tr({}, errorCell));
        }

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Room name:')),
            Html.td({}, booking.bookingParams.roomName)));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Extension:')),
            Html.td({}, booking.extension)));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Room moderator:')),
            Html.td({}, booking.bookingParams.owner.name)));

        var moderatorPinInfo;
        if (booking.bookingParams.hasModeratorPin) {
            moderatorPinInfo = new HiddenText(booking.bookingParams.moderatorPin, Html.span("VidyoHiddenModeratorPIN", "********"), false).draw();
        } else {
            moderatorPinInfo = $T("No moderator PIN was defined");
        }

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Moderator PIN:')),
                Html.td({}, moderatorPinInfo)));

        var pinInfo;
        if (booking.bookingParams.hasPin) {
            pinInfo = new HiddenText(booking.bookingParams.pin, Html.span("HiddenPIN", "********"), false).draw();
        } else {
            pinInfo = $T("No meeting PIN was defined");
        }

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Meeting PIN:')),
                Html.td({}, pinInfo)));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Description:')),
            Html.td({}, booking.bookingParams.roomDescription)));

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Auto-join URL:')),
                Html.td({}, booking.url ? Html.a({href:booking.url}, booking.url) : $T("not assigned yet"))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Visibility:')),
            Html.td({}, booking.bookingParams.hidden? $T("Hidden") : $T("Visible"))));

        infoTbody.append(Html.tr({},
                Html.td("collaborationInfoLeftCol", $T('Auto-Mute:')),
                Html.td({}, booking.bookingParams.autoMute? $T("Enabled") : $T("Disabled"))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Created on:')),
            Html.td({}, formatDateTimeCS(booking.creationDate))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Last modified on:')),
            Html.td({}, formatDateTimeCS(booking.modificationDate))));

        infoTbody.append(Html.tr({},
            Html.td("collaborationInfoLeftCol", $T('Linked to:')),
            Html.td({}, booking.linkVideoText)));

        return Html.div({}, Html.table({}, infoTbody));
    },

    observeRadioButtons: function(vidyoComponents) {
        var self = this;

        vidyoComponents["link"].observe(function(value){
            switch(value) {
            case"session":
                if (vidyoComponents["changed"] == false) {
                    vidyoComponents["dummy"] = $('#videoEventLinkSelection').html();
                    vidyoComponents["changed"] = true;
                }
                if(self.loaded["session"] === true && vidyoComponents["session"]){
                    $E('videoEventLinkSelection').set(vidyoComponents["session"].draw());
                }else{
                    $E('videoEventLinkSelection').set(progressIndicator(true, true));
                }
                break;
            case"contribution":
                if (vidyoComponents["changed"] == false) {
                    vidyoComponents["dummy"] = $('#videoEventLinkSelection').html();
                    vidyoComponents["changed"] = true;
                }
                if(self.loaded["contribution"] === true && vidyoComponents["contribution"]){
                    $E('videoEventLinkSelection').set(vidyoComponents["contribution"].draw());
                }else{
                    $E('videoEventLinkSelection').set(progressIndicator(true, true));
                }

                break;
            case"None":
            default:
                if (vidyoComponents["changed"]) {
                    $('#videoEventLinkSelection').html(vidyoComponents["dummy"]);
                }
                break;
            }
        });
    },

    getVidyoComponents : function(ajaxPending) {
        var self = this;
        var params = {conference : confId};

        self.vidyoComponents = {
            params : params,
            ownerField : new SingleUserField(${ jsonEncode(LoggedInUser) },
                'owner',
                true, true, null,
                null, false,
                false, false,
                singleUserNothing, singleUserNothing),
            pinField : new ShowablePasswordField('pin', '', false),
            moderatorPinField : new ShowablePasswordField('moderatorPin', '', false),
            link : new RadioFieldWidget([
                 ['event', $T("Leave default Vidyo association")],
                 ['contribution', $T("Link to a contribution")],
                 ['session', $T("Link to a session")]
             ], 'nobulletsListInline','videoLinkType'),
            session :new SelectRemoteWidget('event.sessions.listAll',
                params, function() {
                        ajaxPending["session"].resolve();
                }, 'videoLinkSession', "No sessions"),
            contribution : new SelectRemoteWidget('event.contributions.listAll',
                params, function() {
                        ajaxPending["contribution"].resolve();
                }, 'videoLinkContribution', "No contributions"),
            autoMuteField : $("<input/>").attr({type:"checkbox",name:"autoMute", id:"autoMute", value:"yes", "checked":true}).css("vertical-align", "middle")[0],
            dummy : "",
            changed : false
        };

        return self.vidyoComponents;
    },

    addComponents: function(bookingPopup){
        var self = this;
        self.loaded["session"] = false;
        self.loaded["contribution"] = false;
        ajaxPending= {
            session : $.Deferred(),
            contribution : $.Deferred()
        };

        var vidyoComponents = self.getVidyoComponents(ajaxPending);

        $E('owner').set(vidyoComponents["ownerField"].draw());
        $E('PINField').set(vidyoComponents["pinField"].draw());
        $E('moderatorPINField').set(vidyoComponents["moderatorPinField"].draw());
        $E('videoEventLinkType').set(vidyoComponents["link"].draw());
        $E('autoMuteField').set(vidyoComponents["autoMuteField"]);

        bookingPopup.addComponent(vidyoComponents["ownerField"]);
        bookingPopup.addComponent(vidyoComponents["pinField"]);
        bookingPopup.addComponent(vidyoComponents["moderatorPinField"]);
        bookingPopup.addComponent(vidyoComponents["autoMuteField"]);
        bookingPopup.addComponent(vidyoComponents["session"]);
        bookingPopup.addComponent(vidyoComponents["contribution"]);
        bookingPopup.addComponent(vidyoComponents["link"]); /* This must be the last component added. */
        vidyoDrawContextHelpIcons(vidyoComponents["pinField"]);

        $.when(ajaxPending["session"]).done(function() {
            if(vidyoComponents["link"].get() == "session"){
                $E('videoEventLinkSelection').set(vidyoComponents["session"].draw());
            }
            self.loaded["session"] = true;
        });

        $.when(ajaxPending["contribution"]).done(function() {
            if(vidyoComponents["link"].get() == "contribution"){
                $E('videoEventLinkSelection').set(vidyoComponents["contribution"].draw());
            }
            self.loaded["contribution"] = true;
        });

        self.observeRadioButtons(vidyoComponents);

        if(bookingPopup.booking !== undefined){
            if(bookingPopup.booking.isRoomInMultipleBookings) $(".redWarningMessage").show();
            else $(".redWarningMessage").hide();
        }
        return vidyoComponents;
    },

    onCreate: function(bookingPopup) {
        var vidyoComponents = this.addComponents(bookingPopup);
        vidyoComponents["link"].select('event');

    },

    onEdit: function(booking, bookingPopup) {
        this.addComponents(bookingPopup);
    },

    postCreate: function(booking) {
    },

    postEdit: function(booking) {
    },

    postCheckStatus: function(booking) {
        if (booking.warning) {
            if (booking.warning === 'invalidName') {
                var popup = new AlertPopup($T("Problem retrieving the room name"),
                        Html.span({}, $T("The room name could not be decoded and updated in Indico."),
                                      Html.br(),
                                      $T("Maybe it contains some Unicode characters that Indico is not able to handle.")));
                popup.open();
            }
            if (booking.warning === 'invalidDescription') {
                var popup = new AlertPopup($T("Problem retrieving the description text"),
                        Html.span({}, $T("The description text could not be decoded and updated in Indico."),
                                      Html.br(),
                                      $T("Maybe it contains some Unicode characters that Indico is not able to handle.")));
                popup.open();
            }
        }
    },

    postDelete: function(booking) {
        if (booking.warning) {
            if (booking.warning === 'cannotDeleteNonExistant') {
                var popup = new AlertPopup($T("Public room deletion"),
                        Html.span({}, $T("The public room was deleted successfully from Indico."),
                                      Html.br(),
                                      $T("However, please note that the public room had already been removed from the Vidyo system previously.")));
                popup.open();
            }
        }
    }
}

<|endoftext|>


<commit_before>// import {BarChart} from 'react-d3-components'
// import React from 'react'
// import axios from 'axios'

// class DiscussionAnalytics extends React.Component{
//   constructor(props){
//     super(props)
//     this.state = {
//       ages: null,
//       showAges: false,
//       politics: null,
//       showPolitics: false
//     }
//   }
//   getAges() {
//     if(this.state.ages === null){
//       axios.get(`/discussionAges/${this.props.discussionId}`)
//         .then(function(response){
//           console.log('response ages ------', response)
//           var ageRanges = {
//             kids: 0,
//             teens: 0,
//             twenties: 0,
//             thirties: 0,
//             forties: 0,
//             fifties: 0,
//             sixties: 0,
//             seventies: 0
//           }
//           response.data.rows.forEach((userAge, index)=>{
//             if(userAge.age <= 10) {
//               ageRanges.kids++
//             } else if(userAge.age <= 20) {
//               ageRanges.teens++
//             } else if(userAge.age <= 30) {
//               ageRanges.twenties++
//             } else if(userAge.age <= 40) {
//               ageRanges.thirties++
//             } else if(userAge.age <= 50) {
//               ageRanges.forties++
//             } else if(userAge.age <= 60) {
//               ageRanges.fifties++
//             } else if(userAge.age <= 70) {
//               ageRanges.sixties++
//             } else if(userAge.age <= 80) {
//               ageRanges.seventies++
//             }
//           })
//           console.log('ageRanges', ageRanges)
//           this.setState({
//             ages: ageRanges,
//             showAges: !this.state.showAges
//           })
//           console.log('this state...........', this.state)
//         }.bind(this))
//     } else {
//       this.setState({
//         showAges: !this.state.showAges
//       })
//     }
//   }

//   getPolitics() {
//     if(this.state.politics === null) {
//       axios.get(`/discussionPolitics/${this.props.discussionId}`)
//         .then(function(response) {
//           console.log('response politics ------', response)
//           var politics = {
//             Conservative: 0,
//             Authoritarian: 0,
//             Centrist: 0,
//             Libertarian: 0,
//             Progressive: 0
//           }
//           response.data.rows.forEach((userPolitics, index) => {
//             if(userPolitics.politicalleaning === 1) {
//               politics.Conservative++
//             } else if(userPolitics.politicalleaning === 2) {
//               politics.Authoritarian++
//             } else if(userPolitics.politicalleaning === 3) {
//               politics.Centrist++
//             } else if(userPolitics.politicalleaning === 4) {
//               politics.Libertarian++
//             } else if(userPolitics.politicalleaning === 5) {
//               politics.Progressive++
//             }
//           })
//           this.setState({
//             politics: politics,
//             showPolitics: !this.state.showPolitics
//           })
//           console.log('show politics', this.state)
//         }.bind(this))
//     } else {
//       this.setState({
//         showPolitics: !this.state.showPolitics
//       })
//     }
//   }
// // 1 - Conservative
// // 2 - Authoritarian
// // 3 - Centrist
// // 4 - Libertarian
// // 5 - Progressive

//   render() {
//     var barchartData = [{
//       label: 'somethingA',
//       values: [{x: 'SomethingA', y: 10}, {x: 'SomethingB', y: 4}, {x: 'SomethingC', y: 3}]
//     }];
//     if(this.state.ages !== null) {
//       barchartData = [{
//         label: 'Discussion users by Age-Group',
//         values: [{x: '0-10', y: this.state.ages.kids}, {x: '11 - 20', y: this.state.ages.teens}, {x: '21 - 30', y: this.state.ages.twenties}, {x: '31 - 40', y: this.state.ages.thirties}, {x: '41 - 50', y: this.state.ages.forties}, {x: '51 - 60', y: this.state.ages.fifties}, {x: '61 - 70', y: this.state.ages.sixties}, {x: '71 - 80', y: this.state.ages.seventies}]
//       }]
//     }
//     //var BarChart = ReactD3.BarChart
//     var politicsBarchartData = [{
//       label: 'somethingA',
//       values: [{x: 'SomethingA', y: 10}, {x: 'SomethingB', y: 4}, {x: 'SomethingC', y: 3}]
//     }];
//     if(this.state.politics !== null) {
//       politicsBarchartData = [{
//         label: 'Discussion users by Political Leanings',
//         values: [{x: 'Conservative', y: this.state.politics.Conservative}, {x: 'Authoritarian', y: this.state.politics.Authoritarian}, {x: 'Centrist', y: this.state.politics.Centrist}, {x: 'Libertarian', y: this.state.politics.Libertarian}, {x: 'Progressive', y: this.state.politics.Progressive}]
//       }]
//     }

//     return (
//       <div>
//       <button onClick={()=>this.getAges()}>Get ages of commenters</button>
//       {this.state.showAges && <BarChart data={barchartData} width={800} height={400}
//       margin={{top: 10, bottom: 50, left: 50, right: 10}} />}
//       <button onClick={()=>this.getPolitics()}>Get political leanings of commenters</button>
//       {this.state.showPolitics && <BarChart data={politicsBarchartData} width={800} height={400}
//       margin={{top: 10, bottom: 50, left: 50, right: 10}} />}
//       </div>
//     )
//   }
// }

// export default DiscussionAnalytics<commit_msg>removing one of the analytics files<commit_after><|endoftext|>


<commit_before>'use strict';

(function () {
  angular.module('google-maps').

  /**
   * Directive controller which is owned by the googleMap directive and shared
   * among all other google maps directives.
   */
  factory('googleMapControllerFactory', ['googleMapsUtils', 'googleMapsDefaults', 'googleMapsContainer',
    function (googleMapsUtils, googleMapsDefaults, googleMapsContainer) {

    /** aliases */
    var latLngEqual = googleMapsUtils.latLngEqual;
    var boundsEqual = googleMapsUtils.boundsEqual;
    var latLngToObj = googleMapsUtils.latLngToObj;
    var hasNaN = googleMapsUtils.hasNaN;
    var gMDefaults = googleMapsDefaults;
    var gMContainer = googleMapsContainer;

    /** MapController class **/

    /*
     * @param {google.maps.Map} map
     */
    var MapController = function($scope, $element, $attrs) {

      var mapId = $attrs.mapId;
      if (!mapId) { throw 'googleMap must have non-empty mapId attribute'; }

      var mapDiv = $element.find('[id]');
      mapDiv.attr('id', mapId);

      var config = this._getConfig($scope, gMDefaults);

      // 'private' properties
      this._map = this._createMap(mapId, mapDiv, config, gMContainer);
      this._markers = {};

      // 'public' properties
      this.dragging = false;

      Object.defineProperty(this, 'center', {
        get: function() {
               return this._map.getCenter();
             },
        set: function(center) {
               if (hasNaN(center))
                 throw 'center contains null or NaN';
               var changed = !latLngEqual(this.center, center);
               if (changed) {
                 this._map.setCenter(center);
               }
             }
      });

      Object.defineProperty(this, 'zoom', {
        get: function() {
               return this._map.getZoom();
             },
        set: function(zoom) {
               if (!(zoom != null && !isNaN(zoom)))
                 throw 'zoom was null or NaN';
               var changed = this.zoom !== zoom;
               if (changed) {
                this._map.setZoom(self.zoom);
               }
             }
      });

      Object.defineProperty(this, 'bounds', {
        get: function() {
               return this._map.getBounds();
             },
        set: function(bounds) {
               var numbers = !hasNaN(bounds.getSouthWest()) &&
                             !hasNaN(bounds.getNorthEast());
               if (!numbers)
                 throw 'bounds contains null or NaN';

               var changed = !(boundsEqual(this.bounds, bounds));
               if (changed) {
                 this._map.fitBounds(bounds);
               }
             }
      });

      this._initDragListeners();
    };

    // Constant for toUrlValue() of google.maps.LatLng
    MapController.precision = 4;

    MapController.prototype._getConfig = function($scope, gMDefaults) {
      // Get config or defaults
      var defaults = gMDefaults.mapOptions;
      var config = {};
      angular.extend(config, defaults, $scope.mapOptions());
      return config;
    };

    MapController.prototype._createMap = function(id, element, config, gMContainer) {
      var map = gMContainer.getMap(id);
      if (!map) {
        map = new google.maps.Map(element[0], config);
        gMContainer.addMap(id, map);
      } else {
        throw 'A map with id ' + id + ' already exists. You must use' +
          ' different ids for each instance of the googleMap directive.';
      }
      return map;
    };

    MapController.prototype._initDragListeners = function() {
      var self = this;
      this.addListener('dragstart', function () {
        self.dragging = true;
      });

      this.addListener('idle', function () {
        self.dragging = false;
      });

      this.addListener('drag', function() {
        self.dragging = true;
      });
    };

    MapController.prototype.addListener = function(event, handler) {
      google.maps.event.addListener(this._map,
          event, handler);
    };

    MapController.prototype.addListenerOnce = function(event, handler) {
      google.maps.event.addListenerOnce(this._map,
          event, handler);
    };

    /**
     * @param {google.maps.MarkerOptions} markerOptions
     */
    MapController.prototype.addMarker = function(markerOptions) {
      var opts = {};
      angular.extend(opts, gMDefaults.markerOptions, markerOptions);

      var marker = new google.maps.Marker(opts);

      var position = marker.getPosition();
      if (this.hasMarker(position.lat(), position.lng())) {
        return false;
      }

      var hash = position.toUrlValue(MapController.precision);
      this._markers[hash] = marker;
      marker.setMap(this._map);
      return true;
    };

    MapController.prototype.hasMarker = function(lat, lng) {
      return (this.getMarker(lat, lng) instanceof google.maps.Marker);
    };

    MapController.prototype.getMarker = function (lat, lng) {
      if (lat == null || lng == null)
        throw 'lat or lng was null';

      var latLng = new google.maps.LatLng(lat, lng);
      var hash = latLng.toUrlValue(MapController.precision);
      if (hash in this._markers) {
        return this._markers[hash];
      } else {
        return null;
      }
    };

    MapController.prototype.removeMarker = function(lat, lng) {
      if (lat == null || lng == null)
        throw 'lat or lng was null';

      var latLng = new google.maps.LatLng(lat, lng);

      var removed = false;
      var hash = latLng.toUrlValue(MapController.precision);
      var marker = this._markers[hash];
      if (marker) {
        marker.setMap(null);
        removed = true;
      }
      this._markers[hash] = null;
      return removed;
    };

    MapController.prototype.fitToMarkers = function () {
      var bounds = new google.maps.LatLngBounds();

      angular.forEach(this._markers, function (m, i) {
        bounds.extend(m.getPosition());
      });

      this._map.fitBounds(bounds);
    };

    MapController.prototype.forEachMarker = function(fn) {
      angular.forEach(this._markers, function(marker, hash) {
        fn(marker);
      });
    };

    return {
      MapController: MapController
    };

  }]);
})();

<commit_msg>Added docs to methods.<commit_after>'use strict';

(function () {
  angular.module('google-maps').

  /**
   * Directive controller which is owned by the googleMap directive and shared
   * among all other google maps directives.
   */
  factory('googleMapControllerFactory', ['googleMapsUtils', 'googleMapsDefaults', 'googleMapsContainer',
    function (googleMapsUtils, googleMapsDefaults, googleMapsContainer) {

    /** aliases */
    var latLngEqual = googleMapsUtils.latLngEqual;
    var boundsEqual = googleMapsUtils.boundsEqual;
    var latLngToObj = googleMapsUtils.latLngToObj;
    var hasNaN = googleMapsUtils.hasNaN;
    var gMDefaults = googleMapsDefaults;
    var gMContainer = googleMapsContainer;

    /** MapController class **/

    /*
     * Construct a new controller for the googleMap directive.
     * @param {angular.Scope} $scope
     * @param {angular.element} $element
     * @param {angular.Attributes} $attrs
     * @constructor
     */
    var MapController = function($scope, $element, $attrs) {

      var mapId = $attrs.mapId;
      if (!mapId) { throw 'googleMap must have non-empty mapId attribute'; }

      var mapDiv = $element.find('[id]');
      mapDiv.attr('id', mapId);

      var config = this._getConfig($scope, gMDefaults);

      // 'private' properties
      this._map = this._createMap(mapId, mapDiv, config, gMContainer);
      this._markers = {};

      // 'public' properties
      this.dragging = false;

      Object.defineProperty(this, 'center', {
        get: function() {
               return this._map.getCenter();
             },
        set: function(center) {
               if (hasNaN(center))
                 throw 'center contains null or NaN';
               var changed = !latLngEqual(this.center, center);
               if (changed) {
                 this._map.setCenter(center);
               }
             }
      });

      Object.defineProperty(this, 'zoom', {
        get: function() {
               return this._map.getZoom();
             },
        set: function(zoom) {
               if (!(zoom != null && !isNaN(zoom)))
                 throw 'zoom was null or NaN';
               var changed = this.zoom !== zoom;
               if (changed) {
                this._map.setZoom(self.zoom);
               }
             }
      });

      Object.defineProperty(this, 'bounds', {
        get: function() {
               return this._map.getBounds();
             },
        set: function(bounds) {
               var numbers = !hasNaN(bounds.getSouthWest()) &&
                             !hasNaN(bounds.getNorthEast());
               if (!numbers)
                 throw 'bounds contains null or NaN';

               var changed = !(boundsEqual(this.bounds, bounds));
               if (changed) {
                 this._map.fitBounds(bounds);
               }
             }
      });

      this._initDragListeners();
    };

    // Constant for toUrlValue() of google.maps.LatLng
    // used for hashing LatLng objects
    MapController.precision = 4;

    // Retrieve google.maps.MapOptions
    MapController.prototype._getConfig = function($scope, gMDefaults) {
      // Get config or defaults
      var defaults = gMDefaults.mapOptions;
      var config = {};
      angular.extend(config, defaults, $scope.mapOptions());
      return config;
    };

    // Create the map and add to googleMapsContainer
    MapController.prototype._createMap = function(id, element, config, gMContainer) {
      var map = gMContainer.getMap(id);
      if (!map) {
        map = new google.maps.Map(element[0], config);
        gMContainer.addMap(id, map);
      } else {
        throw 'A map with id ' + id + ' already exists. You must use' +
          ' different ids for each instance of the googleMap directive.';
      }
      return map;
    };

    // Set up listeners to update this.dragging
    MapController.prototype._initDragListeners = function() {
      var self = this;
      this.addListener('dragstart', function () {
        self.dragging = true;
      });

      this.addListener('idle', function () {
        self.dragging = false;
      });

      this.addListener('drag', function() {
        self.dragging = true;
      });
    };

    /**
     * Alias for google.maps.Map.addListener
     * @param {string} event an event defined on google.maps.Map
     * @param {function} a handler for the event
     */
    MapController.prototype.addListener = function(event, handler) {
      google.maps.event.addListener(this._map,
          event, handler);
    };

    /**
     * Alias for google.maps.Map.addListenerOnce
     * @param {string} event an event defined on google.maps.Map
     * @param {function} a handler for the event
     */
    MapController.prototype.addListenerOnce = function(event, handler) {
      google.maps.event.addListenerOnce(this._map,
          event, handler);
    };

    /**
     * Adds a new marker to the map.
     * @param {google.maps.MarkerOptions} markerOptions
     * @return {boolean} true if a marker was added, false if there was already
     *   a marker at this position
     * @throw if markerOptions does not have all required options (i.e. position)
     */
    MapController.prototype.addMarker = function(markerOptions) {
      var opts = {};
      angular.extend(opts, gMDefaults.markerOptions, markerOptions);

      var marker = new google.maps.Marker(opts);

      var position = marker.getPosition();
      if (position == null) {
        throw 'markerOptions did not contain a position';
      }
      if (this.hasMarker(position.lat(), position.lng())) {
        return false;
      }

      var hash = position.toUrlValue(MapController.precision);
      this._markers[hash] = marker;
      marker.setMap(this._map);
      return true;
    };

    /**
     * @param {number} lat
     * @param {number} lng
     * @return {boolean} true if there is a marker with the given lat and lng
     */
    MapController.prototype.hasMarker = function(lat, lng) {
      return (this.getMarker(lat, lng) instanceof google.maps.Marker);
    };

    /**
     * @param {number} lat
     * @param {number} lng
     * @return {google.maps.Marker} the marker at given lat and lng, or null if
     *   no such marker exists
     */
    MapController.prototype.getMarker = function (lat, lng) {
      if (lat == null || lng == null)
        throw 'lat or lng was null';

      var latLng = new google.maps.LatLng(lat, lng);
      var hash = latLng.toUrlValue(MapController.precision);
      if (hash in this._markers) {
        return this._markers[hash];
      } else {
        return null;
      }
    };

    /**
     * @param {number} lat
     * @param {number} lng
     * @return {boolean} true if a marker was removed, false if nothing
     *   happened
     */
    MapController.prototype.removeMarker = function(lat, lng) {
      if (lat == null || lng == null)
        throw 'lat or lng was null';

      var latLng = new google.maps.LatLng(lat, lng);

      var removed = false;
      var hash = latLng.toUrlValue(MapController.precision);
      var marker = this._markers[hash];
      if (marker) {
        marker.setMap(null);
        removed = true;
      }
      this._markers[hash] = null;
      return removed;
    };

    /**
     * Changes bounds of map to view all markers.
     */
    MapController.prototype.fitToMarkers = function () {
      var bounds = new google.maps.LatLngBounds();

      angular.forEach(this._markers, function (m, i) {
        bounds.extend(m.getPosition());
      });

      this._map.fitBounds(bounds);
    };

    /**
     * Applies a function to each marker.
     * @param {function} fn
     * @throw if fn is null or undefined
     */
    MapController.prototype.forEachMarker = function(fn) {
      if (fn == null) { throw 'fn was null or undefined'; };
      angular.forEach(this._markers, function(marker, hash) {
        fn(marker);
      });
    };

    return {
      MapController: MapController
    };

  }]);
})();

<|endoftext|>


<commit_before>window.extisplaing = true;

function clean_injection () {
    var elem;
    while((elem = document.getElementById("injplay"))){
        elem.remove();
    }
    while((elem = document.getElementById("injpause"))){
        elem.remove();
    }
}

function ustream_play () {
    clean_injection();
    var injscript = document.createElement('script');
    injscript.id = "injplay";
    injscript.appendChild(document.createTextNode("window.ustream.flash.viewer.UstreamViewer.play()"));
    (document.body || document.head || document.documentElement).appendChild(injscript);
    window.extisplaing = true;
}

function ustream_pause () {
    clean_injection();
    var injscript = document.createElement('script');
    injscript.id = "injpause";
    injscript.appendChild(document.createTextNode("window.ustream.flash.viewer.UstreamViewer.pause()"));
    (document.body || document.head || document.documentElement).appendChild(injscript);
    window.extisplaing = false;
}

function onKeyPress(key) {
    if (key === PLAY) {
        if (window.extisplaing) {
            ustream_pause();
        } else {
            ustream_play();
        }
    }
}
<commit_msg>Included comments to explain the basic working mechanism<commit_after>/*
 * In ustream.tv webpage there is an object that controls the player
 * this object cannot be called by a extension content script, so I
 * inject a script in the DOM to call the play/pause funcions of
 * this object.
 * I think that ustream.tv has a HTML5 controller also, but I didn't
 * test the code with the HTML5 player.
 */

window.extisplaing = true;

/*
 * Remove the injection code added by ustream_play and ustream_pause
 * that won't be used anymore.
*/
function clean_injection () {
    var elem;
    while((elem = document.getElementById("injplay"))){
        elem.remove();
    }
    while((elem = document.getElementById("injpause"))){
        elem.remove();
    }
}

/*
 * Inject a call to the play function of window.ustream.flash.viewer.UstreamViewer
 * that isn't accessible by extension script.
*/
function ustream_play () {
    clean_injection();
    var injscript = document.createElement('script');
    injscript.id = "injplay";
    injscript.appendChild(document.createTextNode("window.ustream.flash.viewer.UstreamViewer.play()"));
    (document.body || document.head || document.documentElement).appendChild(injscript);
    window.extisplaing = true;
}

/*
 * Inject a call to the pause function of window.ustream.flash.viewer.UstreamViewer
 * that isn't accessible by extension script.
*/
function ustream_pause () {
    clean_injection();
    var injscript = document.createElement('script');
    injscript.id = "injpause";
    injscript.appendChild(document.createTextNode("window.ustream.flash.viewer.UstreamViewer.pause()"));
    (document.body || document.head || document.documentElement).appendChild(injscript);
    window.extisplaing = false;
}

function onKeyPress(key) {
    if (key === PLAY) {
        if (window.extisplaing) {
            ustream_pause();
        } else {
            ustream_play();
        }
    }
}
<|endoftext|>


<commit_before>/* eslint-disable no-console */
const colors = require('colors/safe');
const concat = require('concat-files');
const glob = require('glob');
const fs = require('fs');
const postcss = require('postcss');
const prepend = require('postcss-selector-prepend');
const autoprefixer = require('autoprefixer')

let _currBuild = null;

// if called directly, do the thing.
if (process.argv[1].indexOf('build_css.js') > -1) {
  buildCSS();
} else {
  module.exports = buildCSS;
}

function buildCSS() {
  if (_currBuild) return _currBuild;

  const START = '🏗   ' + colors.yellow('Building css...');
  const END = '👍  ' + colors.green('css built');

  console.log('');
  console.log(START);
  console.time(END);

  return _currBuild =
    Promise.resolve()
      .then(() => doGlob('css/**/*.css'))
      .then(files => doConcat(files, 'dist/iD.css'))
      .then(() => {
        const css = fs.readFileSync('dist/iD.css', 'utf8');
        return postcss([
            autoprefixer,
            prepend({ selector: '.ideditor ' })
          ])
          .process(css, { from: 'dist/iD.css', to: 'dist/iD.css' });
      })
      .then(result => fs.writeFileSync('dist/iD.css', result.css))
      .then(() => {
        console.timeEnd(END);
        console.log('');
        _currBuild = null;
      })
      .catch(err => {
        console.error(err);
        console.log('');
        _currBuild = null;
        process.exit(1);
      });
}

function doGlob(pattern) {
  return new Promise((resolve, reject) => {
    glob(pattern, (err, files) => {
      if (err) return reject(err);
      resolve(files);
    });
  });
}

function doConcat(files, output) {
  return new Promise((resolve, reject) => {
    concat(files, output, (err) => {
      if (err) return reject(err);
      resolve();
    });
  });
}
<commit_msg>Fix lint error<commit_after>/* eslint-disable no-console */
const colors = require('colors/safe');
const concat = require('concat-files');
const glob = require('glob');
const fs = require('fs');
const postcss = require('postcss');
const prepend = require('postcss-selector-prepend');
const autoprefixer = require('autoprefixer');

let _currBuild = null;

// if called directly, do the thing.
if (process.argv[1].indexOf('build_css.js') > -1) {
  buildCSS();
} else {
  module.exports = buildCSS;
}

function buildCSS() {
  if (_currBuild) return _currBuild;

  const START = '🏗   ' + colors.yellow('Building css...');
  const END = '👍  ' + colors.green('css built');

  console.log('');
  console.log(START);
  console.time(END);

  return _currBuild =
    Promise.resolve()
      .then(() => doGlob('css/**/*.css'))
      .then(files => doConcat(files, 'dist/iD.css'))
      .then(() => {
        const css = fs.readFileSync('dist/iD.css', 'utf8');
        return postcss([
            autoprefixer,
            prepend({ selector: '.ideditor ' })
          ])
          .process(css, { from: 'dist/iD.css', to: 'dist/iD.css' });
      })
      .then(result => fs.writeFileSync('dist/iD.css', result.css))
      .then(() => {
        console.timeEnd(END);
        console.log('');
        _currBuild = null;
      })
      .catch(err => {
        console.error(err);
        console.log('');
        _currBuild = null;
        process.exit(1);
      });
}

function doGlob(pattern) {
  return new Promise((resolve, reject) => {
    glob(pattern, (err, files) => {
      if (err) return reject(err);
      resolve(files);
    });
  });
}

function doConcat(files, output) {
  return new Promise((resolve, reject) => {
    concat(files, output, (err) => {
      if (err) return reject(err);
      resolve();
    });
  });
}
<|endoftext|>


<commit_before>/*!
 * jQuery UI Selectmenu @VERSION
 * http://jqueryui.com
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectmenu
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 *	jquery.ui.menu.js
 */
(function( $, undefined ) {

$.widget( "ui.selectmenu", {
	version: "@VERSION",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();

		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_drawButton: function() {
		var tabindex = this.element.attr( "tabindex" );

		// Fix existing label
		this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
		this._on( this.label, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		});

		// Hide original select tag
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			"class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
			tabindex: tabindex || this.options.disabled ? -1 : 0,
			id: this.ids.button,
			width: this.element.outerWidth(),
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true"
		})
		.insertAfter( this.element );

		$( "<span>", {
			"class": "ui-icon " + this.options.icons.button
		}).prependTo( this.button );

		this.buttonText = $( "<span>", {
			"class": "ui-selectmenu-text"
		})
		.appendTo( this.button );
		this._setText( this.buttonText, this.element.find( "option:selected" ).text() );

		this._on( this.button, this._buttonEvents );
		this._hoverable( this.button );
		this._focusable( this.button );
	},

	_drawMenu: function() {
		var menuInstance,
			that = this;

		// Create menu portion, append to body
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		});

		// Wrap menu
		this.menuWrap = $( "<div>", {
				"class": "ui-selectmenu-menu",
				outerWidth: this.button.outerWidth()
			})
			.append( this.menu )
			.appendTo( this._appendTo() );

		// Init menu widget
		this.menuInstance = this.menu.menu({
			select: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				that._select( item, event );

				if ( that.isOpen ) {
					event.preventDefault();
					that.close( event );
				}
			},
			focus: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				// prevent inital focus from firing and checks if its a newly focused item
				if ( that.focusIndex !== undefined && item.index !== that.focusIndex ) {
					that._trigger( "focus", event, { item: item } );
					if ( !that.isOpen ) {
						that._select( item, event );
					}
				}
				that.focusIndex = item.index;

				that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) );
			},
			role: "listbox"
		})
		.menu( "instance" );

		// adjust menu styles to dropdown
		this.menu.addClass( "ui-corner-bottom" ).removeClass( "ui-corner-all" );

		// Make sure focus stays on selected item
		this.menuInstance.delay = 999999999;
		// Unbind uneeded Menu events
		this.menuInstance._off( this.menu, "mouseleave" );
	},

	refresh: function() {
		this.menu.empty();

		var item,
			options = this.element.find( "option" );

		if ( !options.length ) {
			return;
		}

		this._readOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menu.menu( "refresh" );
		this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ).find( "a" );

		item = this._getSelectedItem();

		// Make sure menu is selected item aware
		this.menu.menu( "focus", null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", !!this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}
		// Support: IE6-IE9 click doesn't trigger focus on the button
		if ( !this.menuItems ) {
			this.refresh();
		}

		this.isOpen = true;
		this._toggleAttr();
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		// Check if we have an item to select
		if ( this.menuItems ) {
			this.menuInstance.active = this._getSelectedItem();
		}

		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			if ( item.optgroup !== currentOptgroup ) {
				$( "<li>", {
					"class": "ui-selectmenu-optgroup" + ( item.element.parent( "optgroup" ).attr( "disabled" ) ? " ui-state-disabled" : "" ),
					text: item.optgroup
				}).appendTo( ul );
				currentOptgroup = item.optgroup;
			}
			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ),
			a = $( "<a>", { href: "#" });

		if ( item.disabled ) {
			li.addClass( "ui-state-disabled" );
		}
		this._setText( a, item.label );

		return li.append( a ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( " " );
		}
	},

	_move: function( direction, event ) {
		if ( direction === "first" || direction === "last" ) {
			// Set focus manually for first or last item
			this.menu.menu( "focus", event, this.menuItems[ direction ]() );
		} else {
			// Move to and focus next or prev item
			this.menu.menu( direction, event );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		if ( this.isOpen ) {
			this.close( event );
		} else {
			this.open( event );
		}
	},

	_documentClick: {
		click: function( event ) {
			if ( this.isOpen && !$( event.target ).closest( "li.ui-state-disabled, li.ui-selectmenu-optgroup, #" + this.ids.button ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {
		focus: function() {
			// Init Menu on first focus
			this.refresh();
			// Reset focus class as its removed by ui.widget._setOption
			this.button.addClass( "ui-state-focus" );
			this._off( this.button, "focus" );
		},
		click: function( event ) {
			this._toggle( event );
			event.preventDefault();
		},
		keydown: function( event ) {
			var prevDef = true;
			switch ( event.keyCode ) {
				case $.ui.keyCode.TAB:
				case $.ui.keyCode.ESCAPE:
					if ( this.isOpen ) {
						this.close( event );
					}
					prevDef = false;
					break;
				case $.ui.keyCode.ENTER:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					}
					break;
				case $.ui.keyCode.UP:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "previous", event );
					}
					break;
				case $.ui.keyCode.DOWN:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "next", event );
					}
					break;
				case $.ui.keyCode.SPACE:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					} else {
						this._toggle( event );
					}
					break;
				case $.ui.keyCode.LEFT:
					this._move( "previous", event );
					break;
				case $.ui.keyCode.RIGHT:
					this._move( "next", event );
					break;
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.PAGE_UP:
					this._move( "first", event );
					break;
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_DOWN:
					this._move( "last", event );
					break;
				default:
					this.menu.trigger( event );
					prevDef = false;
			}
			if ( prevDef ) {
				event.preventDefault();
			}
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;
		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this._setText( this.buttonText, item.label );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}
	},

	_setAria: function( item ) {
		var link = this.menuItems.eq( item.index ),
			id = link.attr( "id" );

		this.button.attr({
			"aria-labelledby": id,
			"aria-activedescendant": id
		});
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.button.find( "span.ui-icon" )
				.removeClass( this.options.icons.button )
				.addClass( value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}
		if ( key === "disabled" ) {
			this.menu.menu( "option", "disabled", value );
			this.button
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );

			if ( value ) {
				this.element.attr( "disabled", "disabled" );
				this.button.attr( "tabindex", -1 );
				this.close();
			} else {
				this.element.removeAttr( "disabled" );
				this.button.attr( "tabindex", 0 );
			}
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_toggleAttr: function(){
		this.button.toggleClass( "ui-corner-top", this.isOpen ).toggleClass( "ui-corner-all", !this.isOpen );
		this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
		this.menu.attr( "aria-hidden", !this.isOpen);
		this.button.attr( "aria-expanded", this.isOpen);
	},

	_getCreateOptions: function() {
		return { disabled: !!this.element.prop( "disabled" ) };
	},

	_readOptions: function( options ) {
		var data = [];
		options.each( function( index, item ) {
			var option = $( item ),
				optgroup = option.parent( "optgroup" );
			data.push({
				element: option,
				index: index,
				value: option.attr( "value" ),
				label: option.text(),
				optgroup: optgroup.attr( "label" ) || "",
				disabled: optgroup.attr( "disabled" ) || option.attr( "disabled" )
			});
		});
		this.items = data;
	},

	_destroy: function() {
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.label.attr( "for", this.ids.element );
	}
});

}( jQuery ));
<commit_msg>Selectmenu: use that.focusIndex != null instead of !== undefined when checking first focus event<commit_after>/*!
 * jQuery UI Selectmenu @VERSION
 * http://jqueryui.com
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectmenu
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 *	jquery.ui.menu.js
 */
(function( $, undefined ) {

$.widget( "ui.selectmenu", {
	version: "@VERSION",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();

		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_drawButton: function() {
		var tabindex = this.element.attr( "tabindex" );

		// Fix existing label
		this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
		this._on( this.label, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		});

		// Hide original select tag
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			"class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
			tabindex: tabindex || this.options.disabled ? -1 : 0,
			id: this.ids.button,
			width: this.element.outerWidth(),
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true"
		})
		.insertAfter( this.element );

		$( "<span>", {
			"class": "ui-icon " + this.options.icons.button
		}).prependTo( this.button );

		this.buttonText = $( "<span>", {
			"class": "ui-selectmenu-text"
		})
		.appendTo( this.button );
		this._setText( this.buttonText, this.element.find( "option:selected" ).text() );

		this._on( this.button, this._buttonEvents );
		this._hoverable( this.button );
		this._focusable( this.button );
	},

	_drawMenu: function() {
		var menuInstance,
			that = this;

		// Create menu portion, append to body
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		});

		// Wrap menu
		this.menuWrap = $( "<div>", {
				"class": "ui-selectmenu-menu",
				outerWidth: this.button.outerWidth()
			})
			.append( this.menu )
			.appendTo( this._appendTo() );

		// Init menu widget
		this.menuInstance = this.menu.menu({
			select: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				that._select( item, event );

				if ( that.isOpen ) {
					event.preventDefault();
					that.close( event );
				}
			},
			focus: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				// prevent inital focus from firing and checks if its a newly focused item
				if ( that.focusIndex != null && item.index !== that.focusIndex ) {
					that._trigger( "focus", event, { item: item } );
					if ( !that.isOpen ) {
						that._select( item, event );
					}
				}
				that.focusIndex = item.index;

				that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) );
			},
			role: "listbox"
		})
		.menu( "instance" );

		// adjust menu styles to dropdown
		this.menu.addClass( "ui-corner-bottom" ).removeClass( "ui-corner-all" );

		// Make sure focus stays on selected item
		this.menuInstance.delay = 999999999;
		// Unbind uneeded Menu events
		this.menuInstance._off( this.menu, "mouseleave" );
	},

	refresh: function() {
		this.menu.empty();

		var item,
			options = this.element.find( "option" );

		if ( !options.length ) {
			return;
		}

		this._readOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menu.menu( "refresh" );
		this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ).find( "a" );

		item = this._getSelectedItem();

		// Make sure menu is selected item aware
		this.menu.menu( "focus", null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", !!this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}
		// Support: IE6-IE9 click doesn't trigger focus on the button
		if ( !this.menuItems ) {
			this.refresh();
		}

		this.isOpen = true;
		this._toggleAttr();
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		// Check if we have an item to select
		if ( this.menuItems ) {
			this.menuInstance.active = this._getSelectedItem();
		}

		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			if ( item.optgroup !== currentOptgroup ) {
				$( "<li>", {
					"class": "ui-selectmenu-optgroup" + ( item.element.parent( "optgroup" ).attr( "disabled" ) ? " ui-state-disabled" : "" ),
					text: item.optgroup
				}).appendTo( ul );
				currentOptgroup = item.optgroup;
			}
			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ),
			a = $( "<a>", { href: "#" });

		if ( item.disabled ) {
			li.addClass( "ui-state-disabled" );
		}
		this._setText( a, item.label );

		return li.append( a ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( " " );
		}
	},

	_move: function( direction, event ) {
		if ( direction === "first" || direction === "last" ) {
			// Set focus manually for first or last item
			this.menu.menu( "focus", event, this.menuItems[ direction ]() );
		} else {
			// Move to and focus next or prev item
			this.menu.menu( direction, event );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		if ( this.isOpen ) {
			this.close( event );
		} else {
			this.open( event );
		}
	},

	_documentClick: {
		click: function( event ) {
			if ( this.isOpen && !$( event.target ).closest( "li.ui-state-disabled, li.ui-selectmenu-optgroup, #" + this.ids.button ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {
		focus: function() {
			// Init Menu on first focus
			this.refresh();
			// Reset focus class as its removed by ui.widget._setOption
			this.button.addClass( "ui-state-focus" );
			this._off( this.button, "focus" );
		},
		click: function( event ) {
			this._toggle( event );
			event.preventDefault();
		},
		keydown: function( event ) {
			var prevDef = true;
			switch ( event.keyCode ) {
				case $.ui.keyCode.TAB:
				case $.ui.keyCode.ESCAPE:
					if ( this.isOpen ) {
						this.close( event );
					}
					prevDef = false;
					break;
				case $.ui.keyCode.ENTER:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					}
					break;
				case $.ui.keyCode.UP:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "previous", event );
					}
					break;
				case $.ui.keyCode.DOWN:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "next", event );
					}
					break;
				case $.ui.keyCode.SPACE:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					} else {
						this._toggle( event );
					}
					break;
				case $.ui.keyCode.LEFT:
					this._move( "previous", event );
					break;
				case $.ui.keyCode.RIGHT:
					this._move( "next", event );
					break;
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.PAGE_UP:
					this._move( "first", event );
					break;
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_DOWN:
					this._move( "last", event );
					break;
				default:
					this.menu.trigger( event );
					prevDef = false;
			}
			if ( prevDef ) {
				event.preventDefault();
			}
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;
		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this._setText( this.buttonText, item.label );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}
	},

	_setAria: function( item ) {
		var link = this.menuItems.eq( item.index ),
			id = link.attr( "id" );

		this.button.attr({
			"aria-labelledby": id,
			"aria-activedescendant": id
		});
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.button.find( "span.ui-icon" )
				.removeClass( this.options.icons.button )
				.addClass( value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}
		if ( key === "disabled" ) {
			this.menu.menu( "option", "disabled", value );
			this.button
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );

			if ( value ) {
				this.element.attr( "disabled", "disabled" );
				this.button.attr( "tabindex", -1 );
				this.close();
			} else {
				this.element.removeAttr( "disabled" );
				this.button.attr( "tabindex", 0 );
			}
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_toggleAttr: function(){
		this.button.toggleClass( "ui-corner-top", this.isOpen ).toggleClass( "ui-corner-all", !this.isOpen );
		this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
		this.menu.attr( "aria-hidden", !this.isOpen);
		this.button.attr( "aria-expanded", this.isOpen);
	},

	_getCreateOptions: function() {
		return { disabled: !!this.element.prop( "disabled" ) };
	},

	_readOptions: function( options ) {
		var data = [];
		options.each( function( index, item ) {
			var option = $( item ),
				optgroup = option.parent( "optgroup" );
			data.push({
				element: option,
				index: index,
				value: option.attr( "value" ),
				label: option.text(),
				optgroup: optgroup.attr( "label" ) || "",
				disabled: optgroup.attr( "disabled" ) || option.attr( "disabled" )
			});
		});
		this.items = data;
	},

	_destroy: function() {
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.label.attr( "for", this.ids.element );
	}
});

}( jQuery ));
<|endoftext|>


<commit_before>(function($) {
  $(document).ready(function() {
    $("[title]").style_my_tooltips();
  });
})(jQuery);

$(function() {
  var $container = $('.content');
  $container.imagesLoaded(function() {
    $container.masonry({
      itemSelector: '.characterbox',
    });
  });
  $container.infinitescroll({
      itemSelector: ".characterbox",
      navSelector: "div.pagination",
      nextSelector: ".pagination a#next",
      loadingImg: "",
      loadingText: "",
      bufferPx: 10000,
      extraScrollPx: 12000,
    },
    // trigger Masonry as a callback
    function(newElements) {
      var $newElems = $(newElements).css({
        opacity: 0
      });
      // ensure that images load before adding to masonry layout
      $newElems.imagesLoaded(function() {
        $newElems.animate({
          opacity: 1
        });
        $container.masonry('appended', $newElems, true);
      });
    }
  );
});
<commit_msg>Update extra-script.js<commit_after>(function($) {
  $(document).ready(function() {
    $("[title]").style_my_tooltips();
  });
})(jQuery);

$(function() {
  var $container = $('#content');
  $container.imagesLoaded(function() {
    $container.masonry({
      itemSelector: '#characterbox',
    });
  });
  $container.infinitescroll({
      itemSelector: "#characterbox",
      navSelector: "div.pagination",
      nextSelector: ".pagination a#next",
      loadingImg: "",
      loadingText: "",
      bufferPx: 10000,
      extraScrollPx: 12000,
    },
    // trigger Masonry as a callback
    function(newElements) {
      var $newElems = $(newElements).css({
        opacity: 0
      });
      // ensure that images load before adding to masonry layout
      $newElems.imagesLoaded(function() {
        $newElems.animate({
          opacity: 1
        });
        $container.masonry('appended', $newElems, true);
      });
    }
  );
});
<|endoftext|>


<commit_before>/**
 * Slide menu plugin for App Framework UI
 * @copyright Intel
 *
 */
 /* global af*/
 /* global numOnly*/
(function($) {
    "use strict";
    var startX, startY, dx, dy,
        checking = false,
        doMenu = true,
        showHide = false;
    $.ui.slideSideMenu = true;
    $.ui.fixedSideMenuWidth = 20000;
    var isAside=false;
    var keepOpen=false;

    $.ui.ready(function() {

        if ($.os.ie) return; //ie has the menu at the bottom

        var elems = $("#content, #header, #navbar");
        var max = 0;
        var slideOver = max/3;
        var transTime = $.ui.transitionTime;
        var openState=0;
        var showHideThresh=false;
        var $menu = $.query("#menu");
        var $aside_menu = $.query("#aside_menu");
        var menu_width = $menu.width();
        var aside_width = $aside_menu.width();
        $("#afui").bind("touchstart", function(e) {
            openState=0;
            if (!$.ui.isSideMenuEnabled() && !$.ui.isAsideMenuEnabled()) return true;
            if(e.touches.length>1) return;
            startX = e.touches[0].pageX;
            startY = e.touches[0].pageY;

            checking = false;
            doMenu=false;
            keepOpen=false;
            isAside=false;
            if (window.innerWidth >= $.ui.fixedSideMenuWidth){
                doMenu = false;
                keepOpen=true;
            }
            else
                doMenu = true;

            var sidePos=$.ui.getSideMenuPosition();
            if(sidePos>0){
                openState=1;
                max = menu_width;
            } else if(sidePos<0){
                openState=2;
                max = aside_width;
            }
        });

        $("#afui").bind("touchmove", function(e) {
            if(e.touches.length>1) return;
            if (!$.ui.isSideMenuEnabled() && !$.ui.isAsideMenuEnabled()) return true;
            if (!$.ui.slideSideMenu||keepOpen) return true;

            dx = e.touches[0].pageX;
            dy = e.touches[0].pageY;

            //splitview stuff

            if($.ui.splitview&&window.innerWidth>=parseInt($.ui.handheldMinWidth,10)&& (dx > startX)&&openState===0) return true;
            if (!$.ui.isSideMenuEnabled() && (dx > startX) && openState===0) return true;
            if (!$.ui.isAsideMenuEnabled() && (dx < startX) && openState===0) return true;

            if (Math.abs(dy - startY) > Math.abs(dx - startX)) return true;

            if (!checking) {
                checking = true;
                doMenu=false;
                return true;
            }
            else
                doMenu=true;

            var thePlace = (dx - startX);
            if(openState===0){
                if(thePlace<0){
                    max = aside_width;
                    $aside_menu.show();
                    if(!$.ui.splitview)
                        $menu.hide();
                } else {
                    max = menu_width;
                    $menu.show();
                    $aside_menu.hide();
                }
            }

            if (Math.abs(thePlace) > max) return true;

            slideOver=max/3;
            showHideThresh=Math.abs(thePlace)<slideOver?showHide?showHide:false:2;

            if(openState===1) {
                thePlace+=max;
                showHideThresh=Math.abs(thePlace)<slideOver*2?showHide?showHide:false:2;
                if(thePlace>max)
                    thePlace=max;
            } else if(openState===2){
                thePlace=(-1*max)+thePlace;
                showHideThresh=Math.abs(thePlace)<slideOver*2?showHide?showHide:false:2;
                if(thePlace<(-1*max))
                    thePlace=-1*max;
            }
            else if(thePlace<0&&thePlace<(-1*max))
                thePlace=-1*max;

            if (!showHide) {
                transTime = (thePlace / max) * numOnly($.ui.transitionTime);
            } else {
                transTime = ((max - thePlace) / max) * numOnly($.ui.transitionTime);
            }
            transTime=Math.abs(transTime);
            if(thePlace<0){
                isAside=true;
            } else {
                isAside=false;
            }
            elems.cssTranslate(thePlace + "px,0");
            e.preventDefault();
            e.stopPropagation();
        });
        $("#afui").bind("touchend", function(e) {
            if (!$.ui.isSideMenuEnabled() && !$.ui.isAsideMenuEnabled()) return true;

            if (doMenu && checking&&!keepOpen) {
                $.ui.toggleSideMenu(showHideThresh, function(){
                }, transTime,isAside);
            }
            checking = false;
            doMenu = false;
            keepOpen=false;
        });
    });
})(af);
<commit_msg>make af.slidemenu.js pass jshint.<commit_after>/**
 * Slide menu plugin for App Framework UI
 * @copyright Intel
 *
 */
 /* global af*/
 /* global numOnly*/
(function($) {
    "use strict";
    var startX, startY, dx, dy,
        checking = false,
        doMenu = true,
        showHide = false;
    $.ui.slideSideMenu = true;
    $.ui.fixedSideMenuWidth = 20000;
    var isAside=false;
    var keepOpen=false;

    $.ui.ready(function() {

        if ($.os.ie) return; //ie has the menu at the bottom

        var elems = $("#content, #header, #navbar");
        var max = 0;
        var slideOver = max/3;
        var transTime = $.ui.transitionTime;
        var openState=0;
        var showHideThresh=false;
        var $menu = $.query("#menu");
        var $asideMenu = $.query("#aside_menu");
        var menuWidth = $menu.width();
        var asideWidth = $asideMenu.width();
        $("#afui").bind("touchstart", function(e) {
            openState=0;
            if (!$.ui.isSideMenuEnabled() && !$.ui.isAsideMenuEnabled()) return true;
            if(e.touches.length>1) return;
            startX = e.touches[0].pageX;
            startY = e.touches[0].pageY;

            checking = false;
            doMenu=false;
            keepOpen=false;
            isAside=false;
            if (window.innerWidth >= $.ui.fixedSideMenuWidth){
                doMenu = false;
                keepOpen=true;
            }
            else
                doMenu = true;

            var sidePos=$.ui.getSideMenuPosition();
            if(sidePos>0){
                openState=1;
                max = menuWidth;
            } else if(sidePos<0){
                openState=2;
                max = asideWidth;
            }
        });

        $("#afui").bind("touchmove", function(e) {
            if(e.touches.length>1) return;
            if (!$.ui.isSideMenuEnabled() && !$.ui.isAsideMenuEnabled()) return true;
            if (!$.ui.slideSideMenu||keepOpen) return true;

            dx = e.touches[0].pageX;
            dy = e.touches[0].pageY;

            //splitview stuff

            if($.ui.splitview&&window.innerWidth>=parseInt($.ui.handheldMinWidth,10)&& (dx > startX)&&openState===0) return true;
            if (!$.ui.isSideMenuEnabled() && (dx > startX) && openState===0) return true;
            if (!$.ui.isAsideMenuEnabled() && (dx < startX) && openState===0) return true;

            if (Math.abs(dy - startY) > Math.abs(dx - startX)) return true;

            if (!checking) {
                checking = true;
                doMenu=false;
                return true;
            }
            else
                doMenu=true;

            var thePlace = (dx - startX);
            if(openState===0){
                if(thePlace<0){
                    max = asideWidth;
                    $asideMenu.show();
                    if(!$.ui.splitview)
                        $menu.hide();
                } else {
                    max = menuWidth;
                    $menu.show();
                    $asideMenu.hide();
                }
            }

            if (Math.abs(thePlace) > max) return true;

            slideOver=max/3;
            showHideThresh=Math.abs(thePlace)<slideOver?showHide?showHide:false:2;

            if(openState===1) {
                thePlace+=max;
                showHideThresh=Math.abs(thePlace)<slideOver*2?showHide?showHide:false:2;
                if(thePlace>max)
                    thePlace=max;
            } else if(openState===2){
                thePlace=(-1*max)+thePlace;
                showHideThresh=Math.abs(thePlace)<slideOver*2?showHide?showHide:false:2;
                if(thePlace<(-1*max))
                    thePlace=-1*max;
            }
            else if(thePlace<0&&thePlace<(-1*max))
                thePlace=-1*max;

            if (!showHide) {
                transTime = (thePlace / max) * numOnly($.ui.transitionTime);
            } else {
                transTime = ((max - thePlace) / max) * numOnly($.ui.transitionTime);
            }
            transTime=Math.abs(transTime);
            if(thePlace<0){
                isAside=true;
            } else {
                isAside=false;
            }
            elems.cssTranslate(thePlace + "px,0");
            e.preventDefault();
            e.stopPropagation();
        });
        $("#afui").bind("touchend", function(e) {
            if (!$.ui.isSideMenuEnabled() && !$.ui.isAsideMenuEnabled()) return true;

            if (doMenu && checking&&!keepOpen) {
                $.ui.toggleSideMenu(showHideThresh, function(){
                }, transTime,isAside);
            }
            checking = false;
            doMenu = false;
            keepOpen=false;
        });
    });
})(af);
<|endoftext|>