<commit_before>/**
 * @author Allejo Chris G. Velarde
 */
var InstitutionMedicalCenter = {

    removePropertyUri: '',

    _modals: {
        'name': null,
        'description': null
    },

    tabbedContent: {
        container: null,
        tabs: {
            'specializations' : {'url': '', 'container': null},
            'services' : {'url': '', 'container': null},
            'awards' : {'url': '', 'container': null},
            'medical_specialists' : {'url': '', 'container': null}
        }
    },

    _commonDialogOptions: {
        position: ['center', 100],
        autoOpen: false,
        width: 'auto',
        modal: true,
        resizable: false,
        close: function() {}
    },

    _callbacks: {},

    /**
     * Set the jQuery element for tabbed content container InstitutionMedicalCenter.tabbedContent.container
     */
    setTabbedContentContainerElement: function (_el) {
        InstitutionMedicalCenter.tabbedContent.container = _el;

        return this;
    },

    /**
     * Set the options for tabs, InstitutionMedicalCenter.tabbedContent.tabs
     */
    initializeTabs: function(_tabOptions) {
        InstitutionMedicalCenter.tabbedContent.tabs = _tabOptions;

        return this;
    },

    initializeTabbedContentContainerElement: function (_el) {
        InstitutionMedicalCenter.tabbedContent.container = _el;

        return this;
    },

    loadTabbedContents: function(){
        $.each(InstitutionMedicalCenter.tabbedContent.tabs, function(_key, _val){
            $.ajax({
               url: _val.url,
               type: 'GET',
               dataType: 'json',
               success: function(response){
                   _val.container.html(response[_key].html);
                   if (_key == 'specializations') {
                       //InstitutionMedicalCenter.switchTab(_key);
                   }

               }
            });
        }) ;

        return this;
    },

    switchTab: function(_tabType) {
        this.tabbedContent.container.html(this.tabbedContent.tabs[_tabType].container.html());

        return this;
    },

    initializeModals: function(_modalOptions){
        if (_modalOptions.name) {
            this._modals.name = _modalOptions.name;
            this._modals.name.dialog(this._commonDialogOptions);
        }

        if (_modalOptions.description) {
            this._modals.description = _modalOptions.description;
            this._modals.description.dialog(this._commonDialogOptions);
        }

        return this;
    },

    openModal: function(_name) {
        this._modals[_name].dialog("open");

    },

    closeModal: function(_name) {
        this._modals[_name].dialog("close");
    },

    // jQuery element for link opener
    openAjaxBootstrapModal: function(_opener) {
        _modal = $(_opener.attr('data-target'));
        _modal.modal();
        if (_modal.length > 0) {
            $.ajax({
                url: _opener.attr('href'),
                type: 'get',
                dataType: 'json',
                success: function(response) {
                    _modal.html(response.html);
                },
                error: function(response) {
                    console.log(response);
                }
            });
        }

        return false;
    },

    submitModalForm: function(_formElement, _successCallback){
        $.ajax({
            url: _formElement.attr('action'),
            data: _formElement.serialize(),
            type: 'POST',
            success: _successCallback
         });
    },

    /**
     * Clicking on submit button of modal MedicalCenter Sidebar forms
     *
     * @param DOMElement button
     */
    submitMedicalCenterSidebarForms: function(domButtonElement) {
        _button = $(domButtonElement);
        _buttonHtml = _button.html();
        _button.html("Processing...").attr('disabled', true);
        _form = _button.parents('.modal-content').find('form');
        _data = _form.serialize();
        $.ajax({
            url: _form.attr('action'),
            data: _data,
            type: 'POST',
            dataType: 'json',
            success: function(response) {

                switch(_form.attr('id')){
                case 'addressModalForm':
                    var address = response.institutionMedicalCenter.address;
                    $('#profileAddressText').html(address.room_number + ', ' + address.building + ', '+ address.street);
                    $('#profileCityText').html(response.institutionMedicalCenter.city ? response.institutionMedicalCenter.city + ', ' : '');
                    $('#profileStateText').html(response.institutionMedicalCenter.state ? response.institutionMedicalCenter.state + ', ' : '');
                    $('#profileCountryText').html(response.institutionMedicalCenter.country);
                    break;

                case 'numberModalForm':
                	var number = response.institutionMedicalCenter.contactNumber;
                    $('#profileNumberText').html(number.country_code + '-' + number.area_code + '-' + number.number);
                    break;

                case 'emailModalForm':
                	$('#profileEmailText').html(response.institutionMedicalCenter.contactEmail);
                    break;

                case 'websitesModalForm':
                    var websites = response.institutionMedicalCenter.websites, websitesString = '';
                    for(name in websites) {
                        websitesString += name + ': ' + websites[name] + "
";
                    }
                    $('#profileWebsitesText').html(websitesString);
                    break;
                }
                _form.modal('hide');
                _button.html(_buttonHtml).attr('disabled', false);
            },
            error: function(response) {
                _button.html(_buttonHtml).attr('disabled', false);
            }
        });
        return false;
    },

    // this function is closely coupled to element structure in client admin
    //
    submitRemoveSpecializationForm: function(_formElement) {
        _button = _formElement.find('button.delete-button');
        _button.attr('disabled', true)
            .html('Processing...');
        $.ajax({
            url: _formElement.attr('action'),
            data: _formElement.serialize(),
            type: 'POST',
            success: function(response){
                _formElement.parents('div.modal').modal('hide');
                $('#specialization_block_'+response.id).remove();
            }
         });
    },

    submitRemoveMedicalSpecialistForm: function(_formElement) {
        _button = _formElement.find('button.delete-button');
        _button.attr('disabled', true)
            .html('Processing...');
        $.ajax({
            url: _formElement.attr('action'),
            data: _formElement.serialize(),
            type: 'POST',
            success: function(response){
            	$('#dialog-container').dialog("close");
            	$('#doctor_block_'+response.id).remove();
            }
         });
    },

    removeProperty: function(_propertyId, _container) {
        _container.find('a.delete').attr('disabled',true);
        $.ajax({
            type: 'POST',
            url: InstitutionMedicalCenter.removePropertyUri,
            data: {'id': _propertyId},
            success: function(response) {
                _container.remove();
            }
        });

    },

    addAncillaryService: function(_linkElement) {
        return this._doAncillaryServiceAction(_linkElement);
    },

    removeAncillaryService: function(_linkElement) {
        return this._doAncillaryServiceAction(_linkElement);
    },

    _doAncillaryServiceAction: function (_linkElement) {
        if (_linkElement.hasClass('disabled')) {
            return false;
        }
        _href = _linkElement.attr('href');
        _html = _linkElement.html();
        _linkElement.html('Processing...').addClass('disabled');

        $.ajax({
            url: _href,
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                _linkElement.parents('tr.ancillaryancillaryServices_row').html($(response.html).html());
            },
            error: function(response) {
                console.log(response);
            }
        });

        return false;
    }
}

var InstitutionGlobalAwardAutocomplete = {
    _loadHtmlContentUri: '',

    autocompleteOptions: {
        'award':{
            source: '',
            target: null, // autocomplete target jQuery DOM element
            selectedDataContainer: null, // jQuery DOM element container of selected data
            loader: null
        },
        'certificate': {
            source: '',
            target: null, // autocomplete target jQuery DOM element
            selectedDataContainer: null, // jQuery DOM element container of selected data
            loader: null
        },
        'affiliation': {
            source: '',
            target: null, // autocomplete target jQuery DOM element
            selectedDataContainer: null, // jQuery DOM element container of selected data
            loader: null
        }
    },

    setAutocompleteOptions: function (_type, _options) {
        this.autocompleteOptions[_type] = _options;

        return this;
    },

    setLoadHtmlContentUri: function (_val) {
        this._loadHtmlContentUri = _val;

        return this;
    },

    autocomplete: function() {
        $.each(InstitutionGlobalAwardAutocomplete.autocompleteOptions, function(_key, _val){
            if (_val.target) {
                _val.target.autocomplete({
                    minLength: 0,
                    source: _val.source,
                    select: function( event, ui) {
                        InstitutionGlobalAwardAutocomplete._loadContent(ui.item.id, _val);
                        return false;
                    }
                });
            }
        });
    },

    _loadContent: function(_val, _option) {
        _option.loader.show();
        $.ajax({
            url: InstitutionGlobalAwardAutocomplete._loadHtmlContentUri,
            data: {'id':_val},
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                _option.selectedDataContainer.append(response.html);
                _option.target.find('option[value='+_val+']').hide();
                _option.loader.hide();
            },
            error: function(response) {
                _option.loader.hide();
            }
        });
    }
}

<commit_msg>hide modal after saved<commit_after>/**
 * @author Allejo Chris G. Velarde
 */
var InstitutionMedicalCenter = {

    removePropertyUri: '',

    _modals: {
        'name': null,
        'description': null
    },

    tabbedContent: {
        container: null,
        tabs: {
            'specializations' : {'url': '', 'container': null},
            'services' : {'url': '', 'container': null},
            'awards' : {'url': '', 'container': null},
            'medical_specialists' : {'url': '', 'container': null}
        }
    },

    _commonDialogOptions: {
        position: ['center', 100],
        autoOpen: false,
        width: 'auto',
        modal: true,
        resizable: false,
        close: function() {}
    },

    _callbacks: {},

    /**
     * Set the jQuery element for tabbed content container InstitutionMedicalCenter.tabbedContent.container
     */
    setTabbedContentContainerElement: function (_el) {
        InstitutionMedicalCenter.tabbedContent.container = _el;

        return this;
    },

    /**
     * Set the options for tabs, InstitutionMedicalCenter.tabbedContent.tabs
     */
    initializeTabs: function(_tabOptions) {
        InstitutionMedicalCenter.tabbedContent.tabs = _tabOptions;

        return this;
    },

    initializeTabbedContentContainerElement: function (_el) {
        InstitutionMedicalCenter.tabbedContent.container = _el;

        return this;
    },

    loadTabbedContents: function(){
        $.each(InstitutionMedicalCenter.tabbedContent.tabs, function(_key, _val){
            $.ajax({
               url: _val.url,
               type: 'GET',
               dataType: 'json',
               success: function(response){
                   _val.container.html(response[_key].html);
                   if (_key == 'specializations') {
                       //InstitutionMedicalCenter.switchTab(_key);
                   }

               }
            });
        }) ;

        return this;
    },

    switchTab: function(_tabType) {
        this.tabbedContent.container.html(this.tabbedContent.tabs[_tabType].container.html());

        return this;
    },

    initializeModals: function(_modalOptions){
        if (_modalOptions.name) {
            this._modals.name = _modalOptions.name;
            this._modals.name.dialog(this._commonDialogOptions);
        }

        if (_modalOptions.description) {
            this._modals.description = _modalOptions.description;
            this._modals.description.dialog(this._commonDialogOptions);
        }

        return this;
    },

    openModal: function(_name) {
        this._modals[_name].dialog("open");

    },

    closeModal: function(_name) {
        this._modals[_name].dialog("close");
    },

    // jQuery element for link opener
    openAjaxBootstrapModal: function(_opener) {
        _modal = $(_opener.attr('data-target'));
        _modal.modal();
        if (_modal.length > 0) {
            $.ajax({
                url: _opener.attr('href'),
                type: 'get',
                dataType: 'json',
                success: function(response) {
                    _modal.html(response.html);
                },
                error: function(response) {
                    console.log(response);
                }
            });
        }

        return false;
    },

    submitModalForm: function(_formElement, _successCallback){
        $.ajax({
            url: _formElement.attr('action'),
            data: _formElement.serialize(),
            type: 'POST',
            success: _successCallback
         });
    },

    /**
     * Clicking on submit button of modal MedicalCenter Sidebar forms
     *
     * @param DOMElement button
     */
    submitMedicalCenterSidebarForms: function(domButtonElement) {
        _button = $(domButtonElement);
        _buttonHtml = _button.html();
        _button.html("Processing...").attr('disabled', true);
        _form = _button.parents('.modal-content').find('form');
        _data = _form.serialize();
        $.ajax({
            url: _form.attr('action'),
            data: _data,
            type: 'POST',
            dataType: 'json',
            success: function(response) {

                switch(_form.attr('id')){
                case 'addressModalForm':
                    var address = response.institutionMedicalCenter.address;
                    $('#profileAddressText').html(address.room_number + ', ' + address.building + ', '+ address.street);
                    $('#profileCityText').html(response.institutionMedicalCenter.city ? response.institutionMedicalCenter.city + ', ' : '');
                    $('#profileStateText').html(response.institutionMedicalCenter.state ? response.institutionMedicalCenter.state + ', ' : '');
                    $('#profileCountryText').html(response.institutionMedicalCenter.country);
                    break;

                case 'numberModalForm':
                	var number = response.institutionMedicalCenter.contactNumber;
                    $('#profileNumberText').html(number.country_code + '-' + number.area_code + '-' + number.number);
                    break;

                case 'emailModalForm':
                	$('#profileEmailText').html(response.institutionMedicalCenter.contactEmail);
                    break;

                case 'websitesModalForm':
                    var websites = response.institutionMedicalCenter.websites, websitesString = '';
                    for(name in websites) {
                        websitesString += name + ': ' + websites[name] + "
";
                    }
                    $('#profileWebsitesText').html(websitesString);
                    break;
                }
                _form.parents('.modal').modal('hide');
                _button.html(_buttonHtml).attr('disabled', false);
            },
            error: function(response) {
                _button.html(_buttonHtml).attr('disabled', false);
            }
        });
        return false;
    },

    // this function is closely coupled to element structure in client admin
    //
    submitRemoveSpecializationForm: function(_formElement) {
        _button = _formElement.find('button.delete-button');
        _button.attr('disabled', true)
            .html('Processing...');
        $.ajax({
            url: _formElement.attr('action'),
            data: _formElement.serialize(),
            type: 'POST',
            success: function(response){
                _formElement.parents('div.modal').modal('hide');
                $('#specialization_block_'+response.id).remove();
            }
         });
    },

    submitRemoveMedicalSpecialistForm: function(_formElement) {
        _button = _formElement.find('button.delete-button');
        _button.attr('disabled', true)
            .html('Processing...');
        $.ajax({
            url: _formElement.attr('action'),
            data: _formElement.serialize(),
            type: 'POST',
            success: function(response){
            	$('#dialog-container').dialog("close");
            	$('#doctor_block_'+response.id).remove();
            }
         });
    },

    removeProperty: function(_propertyId, _container) {
        _container.find('a.delete').attr('disabled',true);
        $.ajax({
            type: 'POST',
            url: InstitutionMedicalCenter.removePropertyUri,
            data: {'id': _propertyId},
            success: function(response) {
                _container.remove();
            }
        });

    },

    addAncillaryService: function(_linkElement) {
        return this._doAncillaryServiceAction(_linkElement);
    },

    removeAncillaryService: function(_linkElement) {
        return this._doAncillaryServiceAction(_linkElement);
    },

    _doAncillaryServiceAction: function (_linkElement) {
        if (_linkElement.hasClass('disabled')) {
            return false;
        }
        _href = _linkElement.attr('href');
        _html = _linkElement.html();
        _linkElement.html('Processing...').addClass('disabled');

        $.ajax({
            url: _href,
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                _linkElement.parents('tr.ancillaryancillaryServices_row').html($(response.html).html());
            },
            error: function(response) {
                console.log(response);
            }
        });

        return false;
    }
}

var InstitutionGlobalAwardAutocomplete = {
    _loadHtmlContentUri: '',

    autocompleteOptions: {
        'award':{
            source: '',
            target: null, // autocomplete target jQuery DOM element
            selectedDataContainer: null, // jQuery DOM element container of selected data
            loader: null
        },
        'certificate': {
            source: '',
            target: null, // autocomplete target jQuery DOM element
            selectedDataContainer: null, // jQuery DOM element container of selected data
            loader: null
        },
        'affiliation': {
            source: '',
            target: null, // autocomplete target jQuery DOM element
            selectedDataContainer: null, // jQuery DOM element container of selected data
            loader: null
        }
    },

    setAutocompleteOptions: function (_type, _options) {
        this.autocompleteOptions[_type] = _options;

        return this;
    },

    setLoadHtmlContentUri: function (_val) {
        this._loadHtmlContentUri = _val;

        return this;
    },

    autocomplete: function() {
        $.each(InstitutionGlobalAwardAutocomplete.autocompleteOptions, function(_key, _val){
            if (_val.target) {
                _val.target.autocomplete({
                    minLength: 0,
                    source: _val.source,
                    select: function( event, ui) {
                        InstitutionGlobalAwardAutocomplete._loadContent(ui.item.id, _val);
                        return false;
                    }
                });
            }
        });
    },

    _loadContent: function(_val, _option) {
        _option.loader.show();
        $.ajax({
            url: InstitutionGlobalAwardAutocomplete._loadHtmlContentUri,
            data: {'id':_val},
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                _option.selectedDataContainer.append(response.html);
                _option.target.find('option[value='+_val+']').hide();
                _option.loader.hide();
            },
            error: function(response) {
                _option.loader.hide();
            }
        });
    }
}

<|endoftext|>


<commit_before>/* global MutationObserver */

import diff from 'fast-diff'

export default function extendYXmlText (Y) {
  Y.requestModules(['Array']).then(function () {
    class YXmlText extends Y.Array.typeDefinition['class'] {
      constructor (os, _model, _content, args) {
        super(os, _model, _content)
        if (args != null && args.content != null && _model[0] !== '_') {
          this.insert(0, args.content)
        }
        this.dom = null
        this._domObserver = null
        this._domObserverListener = null
        if (args != null && args.dom != null) {
          this._setDom(args.dom)
        }
      }

      _setDom (dom) {
        if (this.dom != null || dom.__yxml != null) {
          throw new Error('Already bound to a yxml type!')
        }
        var token = true
        function mutualExcluse (f) {
          if (token) {
            token = false
            try {
              f()
            } catch (e) {
              token = true
              throw new Error(e)
            }
            token = true
          }
        }
        this.observe(event => {
          mutualExcluse(() => {
            this.dom.nodeValue = this.toString()
          })
        })
        this.dom = dom
        dom.__yxml = this
        this._domObserverListener = () => {
          mutualExcluse(() => {
            var diffs = diff(this.toString(), this.dom.nodeValue)
            var pos = 0
            for (var i = 0; i < diffs.length; i++) {
              var d = diffs[i]
              if (d[0] === 0) { // EQUAL
                pos += d[1].length
              } else if (d[0] === -1) { // DELETE
                this.delete(pos, d[1].length)
              } else { // INSERT
                this.insert(pos, d[1])
                pos += d[1].length
              }
            }
          })
        }
        this._domObserver = new MutationObserver(this._domObserverListener)
        this._domObserver.observe(this.dom, { characterData: true })
      }

      getDom () {
        if (this.dom == null) {
          let dom = document.createTextNode(this.toString())
          this._setDom(dom)
        }
        return this.dom
      }

      toString () {
        return this._content.map(function (c) {
          return c.val
        }).join('')
      }

      insert (pos, content) {
        super.insert(pos, content.split(''))
      }

      * _changed (transaction, op) {
        if (this._domObserver != null) {
          this._domObserverListener(this._domObserver.takeRecords())
        }
        yield * super._changed(transaction, op)
      }

      _unbindFromDom () {
        if (this._domObserver != null) {
          this._domObserver.disconnect()
          this._domObserver = null
        }
        if (this.dom != null) {
          this.dom.__yxml = null
          this.dom = null
        }
      }

      _destroy () {
        if (this._eventListenerHandler != null) {
          this._eventListenerHandler.destroy()
        }
        this._unbindFromDom()
        super._destroy()
      }
    }
    Y.extend('XmlText', new Y.utils.CustomTypeDefinition({
      name: 'XmlText',
      class: YXmlText,
      struct: 'List',
      parseArguments: function (arg) {
        if (typeof arg === 'string') {
          return [this, { content: arg }]
        } else if (arg.nodeType === document.TEXT_NODE) {
          return [this, { content: arg.nodeValue, dom: arg }]
        } else {
          return [this, {}]
        }
      },
      initType: function * YXmlTextInitializer (os, model, init) {
        var _content = []
        yield * Y.Struct.List.map.call(this, model, function (op) {
          if (op.hasOwnProperty('opContent')) {
            throw new Error('Text must not contain types!')
          } else {
            op.content.forEach(function (c, i) {
              _content.push({
                id: [op.id[0], op.id[1] + i],
                val: op.content[i]
              })
            })
          }
        })
        return new YXmlText(os, model.id, _content, {}, init || {})
      },
      createType: function YXmlTextCreator (os, model, args) {
        return new YXmlText(os, model.id, [], args || {})
      }
    }))
  })
}
<commit_msg>implement cursor fixes<commit_after>/* global MutationObserver, getSelection */

import diff from 'fast-diff'

export default function extendYXmlText (Y) {
  Y.requestModules(['Array']).then(function () {
    class YXmlText extends Y.Array.typeDefinition['class'] {
      constructor (os, _model, _content, args) {
        super(os, _model, _content)
        if (args != null && args.content != null && _model[0] !== '_') {
          this.insert(0, args.content)
        }
        this.dom = null
        this._domObserver = null
        this._domObserverListener = null
        if (args != null && args.dom != null) {
          this._setDom(args.dom)
        }
      }

      _setDom (dom) {
        if (this.dom != null || dom.__yxml != null) {
          throw new Error('Already bound to a yxml type!')
        }
        var token = true
        function mutualExcluse (f) {
          if (token) {
            token = false
            try {
              f()
            } catch (e) {
              token = true
              throw new Error(e)
            }
            token = true
          }
        }
        function fixPosition (event, pos) {
          if (event.index <= pos) {
            if (event.type === 'delete') {
              return pos - Math.min(pos - event.index, event.length)
            } else {
              return pos + 1
            }
          } else {
            return pos
          }
        }
        this.observe(event => {
          mutualExcluse(() => {
            let selection = null
            let shouldUpdateSelection = false
            let anchorNode = null
            let anchorOffset = null
            let focusNode = null
            let focusOffset = null
            if (typeof getSelection !== 'undefined') {
              selection = getSelection()
              if (selection.anchorNode === this.dom) {
                anchorNode = selection.anchorNode
                anchorOffset = fixPosition(event, selection.anchorOffset)
                shouldUpdateSelection = true
              }
              if (selection.focusNode === this.dom) {
                focusNode = selection.focusNode
                focusOffset = fixPosition(event, selection.focusOffset)
                shouldUpdateSelection = true
              }
            }
            this.dom.nodeValue = this.toString()
            if (shouldUpdateSelection) {
              selection.setBaseAndExtent(
                anchorNode || selection.anchorNode,
                anchorOffset || selection.anchorOffset,
                focusNode || selection.focusNode,
                focusOffset || selection.focusOffset
              )
            }
          })
        })
        this.dom = dom
        dom.__yxml = this
        this._domObserverListener = () => {
          mutualExcluse(() => {
            var diffs = diff(this.toString(), this.dom.nodeValue)
            var pos = 0
            for (var i = 0; i < diffs.length; i++) {
              var d = diffs[i]
              if (d[0] === 0) { // EQUAL
                pos += d[1].length
              } else if (d[0] === -1) { // DELETE
                this.delete(pos, d[1].length)
              } else { // INSERT
                this.insert(pos, d[1])
                pos += d[1].length
              }
            }
          })
        }
        this._domObserver = new MutationObserver(this._domObserverListener)
        this._domObserver.observe(this.dom, { characterData: true })
      }

      getDom () {
        if (this.dom == null) {
          let dom = document.createTextNode(this.toString())
          this._setDom(dom)
        }
        return this.dom
      }

      toString () {
        return this._content.map(function (c) {
          return c.val
        }).join('')
      }

      insert (pos, content) {
        super.insert(pos, content.split(''))
      }

      * _changed (transaction, op) {
        if (this._domObserver != null) {
          this._domObserverListener(this._domObserver.takeRecords())
        }
        yield * super._changed(transaction, op)
      }

      _unbindFromDom () {
        if (this._domObserver != null) {
          this._domObserver.disconnect()
          this._domObserver = null
        }
        if (this.dom != null) {
          this.dom.__yxml = null
          this.dom = null
        }
      }

      _destroy () {
        if (this._eventListenerHandler != null) {
          this._eventListenerHandler.destroy()
        }
        this._unbindFromDom()
        super._destroy()
      }
    }
    Y.extend('XmlText', new Y.utils.CustomTypeDefinition({
      name: 'XmlText',
      class: YXmlText,
      struct: 'List',
      parseArguments: function (arg) {
        if (typeof arg === 'string') {
          return [this, { content: arg }]
        } else if (arg.nodeType === document.TEXT_NODE) {
          return [this, { content: arg.nodeValue, dom: arg }]
        } else {
          return [this, {}]
        }
      },
      initType: function * YXmlTextInitializer (os, model, init) {
        var _content = []
        yield * Y.Struct.List.map.call(this, model, function (op) {
          if (op.hasOwnProperty('opContent')) {
            throw new Error('Text must not contain types!')
          } else {
            op.content.forEach(function (c, i) {
              _content.push({
                id: [op.id[0], op.id[1] + i],
                val: op.content[i]
              })
            })
          }
        })
        return new YXmlText(os, model.id, _content, {}, init || {})
      },
      createType: function YXmlTextCreator (os, model, args) {
        return new YXmlText(os, model.id, [], args || {})
      }
    }))
  })
}
<|endoftext|>


<commit_before>/**
@ngdoc directive
@name umbraco.directives.directive:umbNodePreview
@restrict E
@scope

@description
Added in Umbraco v. 7.6: Use this directive to render a node preview.

Markup example

            <umb-node-preview
                ng-repeat="node in vm.nodes"
                icon="node.icon"
                name="node.name"
                published="node.published"
                description="node.description"
                sortable="vm.sortable"
                allow-remove="vm.allowRemove"
                allow-open="vm.allowOpen"
                on-remove="vm.remove($index, vm.nodes)"
                on-open="vm.open(node)">
            </umb-node-preview>

Controller example

    (function () {
        "use strict";

        function Controller() {

            var vm = this;

            vm.allowRemove = true;
            vm.allowOpen = true;
            vm.sortable = true;

            vm.nodes = [
                {
                    "icon": "icon-document",
                    "name": "My node 1",
                    "published": true,
                    "description": "A short description of my node"
                },
                {
                    "icon": "icon-document",
                    "name": "My node 2",
                    "published": true,
                    "description": "A short description of my node"
                }
            ];

            vm.remove = remove;
            vm.open = open;

            function remove(index, nodes) {
                alert("remove node");
            }

            function open(node) {
                alert("open node");
            }

        }

        angular.module("umbraco").controller("My.NodePreviewController", Controller);

    })();

@param {string} icon (binding): The node icon.
@param {string} name (binding): The node name.
@param {boolean} published (binding): The node pusblished state.
@param {string} description (binding): A short description.
@param {boolean} sortable (binding): Will add a move cursor on the node preview. Can used in combination with ui-sortable.
@param {boolean} allowRemove (binding): Show/Hide the remove button.
@param {boolean} allowOpen (binding): Show/Hide the open button.
@param {boolean} allowEdit (binding): Show/Hide the edit button (Added in version 7.7.0).
@param {function} onRemove (expression): Callback function when the remove button is clicked.
@param {function} onOpen (expression): Callback function when the open button is clicked.
@param {function} onEdit (expression): Callback function when the edit button is clicked (Added in version 7.7.0).
**/

(function () {
    'use strict';

    function NodePreviewDirective() {

        function link(scope, el, attr, ctrl) {
            if (!scope.editLabelKey) {
                scope.editLabelKey = "general_edit";
            }
        }

        var directive = {
            restrict: 'E',
            replace: true,
            templateUrl: 'views/components/umb-node-preview.html',
            scope: {
                icon: "=?",
                name: "=",
                description: "=?",
                permissions: "=?",
                published: "=?",
                sortable: "=?",
                allowOpen: "=?",
                allowRemove: "=?",
                allowEdit: "=?",
                onOpen: "&?",
                onRemove: "&?",
                onEdit: "&?"
            },
            link: link
        };

        return directive;

    }

    angular.module('umbraco.directives').directive('umbNodePreview', NodePreviewDirective);

})();<commit_msg>Fix typo<commit_after>/**
@ngdoc directive
@name umbraco.directives.directive:umbNodePreview
@restrict E
@scope

@description
Added in Umbraco v. 7.6: Use this directive to render a node preview.

Markup example

            <umb-node-preview
                ng-repeat="node in vm.nodes"
                icon="node.icon"
                name="node.name"
                published="node.published"
                description="node.description"
                sortable="vm.sortable"
                allow-remove="vm.allowRemove"
                allow-open="vm.allowOpen"
                on-remove="vm.remove($index, vm.nodes)"
                on-open="vm.open(node)">
            </umb-node-preview>

Controller example

    (function () {
        "use strict";

        function Controller() {

            var vm = this;

            vm.allowRemove = true;
            vm.allowOpen = true;
            vm.sortable = true;

            vm.nodes = [
                {
                    "icon": "icon-document",
                    "name": "My node 1",
                    "published": true,
                    "description": "A short description of my node"
                },
                {
                    "icon": "icon-document",
                    "name": "My node 2",
                    "published": true,
                    "description": "A short description of my node"
                }
            ];

            vm.remove = remove;
            vm.open = open;

            function remove(index, nodes) {
                alert("remove node");
            }

            function open(node) {
                alert("open node");
            }

        }

        angular.module("umbraco").controller("My.NodePreviewController", Controller);

    })();

@param {string} icon (binding): The node icon.
@param {string} name (binding): The node name.
@param {boolean} published (binding): The node published state.
@param {string} description (binding): A short description.
@param {boolean} sortable (binding): Will add a move cursor on the node preview. Can used in combination with ui-sortable.
@param {boolean} allowRemove (binding): Show/Hide the remove button.
@param {boolean} allowOpen (binding): Show/Hide the open button.
@param {boolean} allowEdit (binding): Show/Hide the edit button (Added in version 7.7.0).
@param {function} onRemove (expression): Callback function when the remove button is clicked.
@param {function} onOpen (expression): Callback function when the open button is clicked.
@param {function} onEdit (expression): Callback function when the edit button is clicked (Added in version 7.7.0).
**/

(function () {
    'use strict';

    function NodePreviewDirective() {

        function link(scope, el, attr, ctrl) {
            if (!scope.editLabelKey) {
                scope.editLabelKey = "general_edit";
            }
        }

        var directive = {
            restrict: 'E',
            replace: true,
            templateUrl: 'views/components/umb-node-preview.html',
            scope: {
                icon: "=?",
                name: "=",
                description: "=?",
                permissions: "=?",
                published: "=?",
                sortable: "=?",
                allowOpen: "=?",
                allowRemove: "=?",
                allowEdit: "=?",
                onOpen: "&?",
                onRemove: "&?",
                onEdit: "&?"
            },
            link: link
        };

        return directive;

    }

    angular.module('umbraco.directives').directive('umbNodePreview', NodePreviewDirective);

})();<|endoftext|>


<commit_before>var main = require("./main");

exports["test main"] = function(assert) {
  assert.pass("Unit test running!");
};

exports["test main async"] = function(assert, done) {
  assert.pass("async Unit test running!");
  done();
};

require("sdk/test").run(exports);
<commit_msg>Remove unused test file.<commit_after><|endoftext|>


<commit_before>// jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, onevar:true, plusplus:true, quotmark:double, strict:true, undef:true, unused:strict, node:true

"use strict";

/// Usage: node test-node.js [unmin]
///
/// Add "unmin" to test the unminified code.
///

var all_tests_pass = true,
    fs = require("fs"),
    p = require("path"),
    my_lzma,
    lzma_norm = require("../src/lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA,
    lzma_sep = {
        decompress: require("../src/lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.decompress,
        compress:   require("../src/lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.compress,
    },
    path_to_files = "files",
    isTTY = process.stdout.isTTY;

function announce(str)
{
    var stars = "****",
        i;

    for (i = str.length - 1; i >= 0; i -= 1) {
        stars += "*";
    }

    note(stars);
    note("* "+ str + " *");
    note(stars);
}

function color(color_code, str)
{
    if (isTTY) {
        str = "\u001B[" + color_code + "m" + str + "\u001B[0m";
    }

    console.log(str);
}

function note(str)
{
    color(36, str);
}

function good(str)
{
    color(32, str);
}

function warn(str)
{
    color(33, str);
}

function error(str)
{
    color(31, str);
}

function display_result(str, pass)
{
    if (pass) {
        good(str)
    } else {
        error(str)
    }
}

function progress(percent)
{
    if (isTTY) {
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        if (percent > 0 && percent < 1) {
            process.stdout.write((percent * 100).toFixed(2) + "%");
        }
    }
}

function decompression_test(compressed_file, correct_filename, next)
{
    fs.readFile(correct_filename, function (err, correct_result)
    {

        if (err) {
            console.log("Cannot open " + correct_filename);
            throw new Error(err);
        }

        fs.readFile(compressed_file, function (err, buffer)
        {
            var deco_start;

            if (err) {
                throw err;
            }

            deco_start = (new Date()).getTime();
            try {
                my_lzma.decompress(buffer, function (result)
                {
                    var deco_speed = (new Date()).getTime() - deco_start;

                    console.log("Decompressed size:", result.length);

                    if (typeof result === "string") {
                        correct_result = correct_result.toString();
                    }

                    if (compare(correct_result, result)) {
                        display_result("Test passed", true);
                    } else {
                        display_result("ERROR: files do not match!", false);
                        console.log();
                        all_tests_pass = false;
                    }

                    console.log("Decompression time:", deco_speed);

                    console.log();
                    next();
                }, progress);
            } catch (e) {
                if (p.basename(correct_filename) === "error-" + e.message) {
                    display_result("Test passed", true);
                    console.log("threw correct error: " + e.message);
                } else {
                    display_result("ERROR: " + e.message, false);
                    all_tests_pass = false;
                }
                console.log();
                next();
            }
        });
    });
}

function compression_test(file, next)
{
    fs.readFile(file, function (err, content)
    {
        var comp_start = (new Date()).getTime(),
            compression_mode = 1,
            match,
            buf;

        if (err) {
            throw err;
        }

        if (typeof content === "object") {
            buf = new Buffer(content.length);
            content.copy(buf);
        }

        //console.log(content)
        match = p.basename(file, p.extname(file)).match(/^level[ _](\d)/i);

        if (match) {
            compression_mode = Number(match[1]) || 1;
        }
        console.log("     Initial size:", content.length);
        my_lzma.compress(buf || content, compression_mode, function ondone(compressed_result)
        {
            var comp_speed = (new Date()).getTime() - comp_start,
                deco_start;

            console.log("  Compressed size:", compressed_result.length);
            fs.writeFileSync("file.lzma", new Buffer(compressed_result))
            deco_start = (new Date()).getTime();
            my_lzma.decompress(compressed_result, function (decompressed_result)
            {
                var deco_speed = (new Date()).getTime() - deco_start;
                console.log("Decompressed size:", decompressed_result.length);

                if (typeof decompressed_result === "string") {
                    content = content.toString();
                }

                if (compare(content, decompressed_result)) {
                //if (content === result) {
                    display_result("Test passed", true);
                } else {
                    display_result("ERROR: files do not match!", false);
                    //console.log();
                    all_tests_pass = false;
                    //console.log(JSON.stringify(content.toJSON()))
                    //console.log(content.toString())
                    //console.log(" --- ");
                    //console.log(dbuf.toString())
                    //console.log(JSON.stringify(dbuf.toJSON()))
                    //process.exit();
                }

                console.log("  Compression time:", comp_speed);
                console.log("Decompression time:", deco_speed);

                console.log();
                next();
            }, progress);
        }, progress);
    });
}

function run_tests(cb)
{
    fs.readdir(path_to_files, function (err, files)
    {
        var file_count = files.length;

        if (err) {
            throw err;
        }

        (function run_test(i)
        {
            var file;

            if (i >= file_count) {
                if (all_tests_pass) {
                    display_result("All tests completed sucessfully", true);
                } else {
                    display_result("An error was detected!", false);
                }

                return cb ? cb(all_tests_pass) : 0;
            }
            file = files[i];

            console.log(file);

            if (file.slice(-5) === ".lzma") {
                /// Preform a decompress test on *.lzma files.
                decompression_test(p.join(path_to_files, file), p.join(path_to_files, file.slice(0, -5)), function next()
                {
                    run_test(i + 1);
                });
            } else {
                /// Preform a compression/decompression test.
                compression_test(p.join(path_to_files, file), function next()
                {
                    run_test(i + 1);
                });
            }
        }(0));
    });
}

function compare(a, b)
{
    var i;
    //console.log("comparing")
    //console.log(this)
    //console.log(b)
    //console.log(this.toJSON())
    //console.log(b.toJSON())

    if (typeof a !== typeof b) {
        console.log("BAD TYPES:", typeof a, "!==", typeof b)
        return false;
    }

    if (a.length !== b.length) {
        console.log("BAD LENGTH:", a.length, "!==", b.length)
        return false;
    }

    if (typeof a === "string") {
        return a === b;
    }

    if (Buffer.isBuffer(a) && !Buffer.isBuffer(b) && Array.isArray(b)) {
        b = new Buffer(b);
    } else if (Buffer.isBuffer(b) && !Buffer.isBuffer(a) && Array.isArray(a)) {
        a = new Buffer(a);
    }

    for (i = a.length - 1; i >= 0; --i) {
        if (a[i] !== b[i]) {
            console.log("BAD VAL (" + i + "):",  a[i], "!==", b[i])
            return false;
        }
    }

    return true;
}

path_to_files = p.join(__dirname, path_to_files);

my_lzma = lzma_norm;

announce("Testing lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js");
run_tests(function (tests_passed_norm)
{
    if (!tests_passed_norm) {
        /// Fail.
        process.exit(1);
    }

    if (process.argv[2] === "nosep" || process.argv[3] === "nosep") {
        process.exit();
    }

    console.log("");
    announce("Testing lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js and lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js");
    my_lzma = lzma_sep;

    run_tests(function (tests_passed_sep)
    {
        if (!tests_passed_sep) {
            /// Fail.
            process.exit(1);
        }
    });
});
<commit_msg>Some testing stuff.<commit_after>// jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, onevar:true, plusplus:true, quotmark:double, strict:true, undef:true, unused:strict, node:true

"use strict";

/// Usage: node test-node.js [unmin]
///
/// Add "unmin" to test the unminified code.
///

var all_tests_pass = true,
    fs = require("fs"),
    p = require("path"),
    my_lzma,
    lzma_norm = require("../src/lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA,
    lzma_sep = {
        decompress: require("../src/lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.decompress,
        compress:   require("../src/lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.compress,
    },
    path_to_files = "files",
    isTTY = process.stdout.isTTY;

function announce(str)
{
    var stars = "****",
        i;

    for (i = str.length - 1; i >= 0; i -= 1) {
        stars += "*";
    }

    note(stars);
    note("* "+ str + " *");
    note(stars);
}

function color(color_code, str)
{
    if (isTTY) {
        str = "\u001B[" + color_code + "m" + str + "\u001B[0m";
    }

    console.log(str);
}

function note(str)
{
    color(36, str);
}

function good(str)
{
    color(32, str);
}

function warn(str)
{
    color(33, str);
}

function error(str)
{
    color(31, str);
}

function display_result(str, pass)
{
    if (pass) {
        good(str)
    } else {
        error(str)
    }
}

function progress(percent)
{
    if (isTTY) {
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        if (percent > 0 && percent < 1) {
            process.stdout.write((percent * 100).toFixed(2) + "%");
        }
    }
}

function decompression_test(compressed_file, correct_filename, next)
{
    fs.readFile(correct_filename, function (err, correct_result)
    {

        if (err) {
            console.log("Cannot open " + correct_filename);
            throw new Error(err);
        }

        fs.readFile(compressed_file, function (err, buffer)
        {
            var deco_start;

            if (err) {
                throw err;
            }

            deco_start = (new Date()).getTime();
            try {
                my_lzma.decompress(buffer, function (result)
                {
                    var deco_speed = (new Date()).getTime() - deco_start;

                    console.log("Decompressed size:", result.length);

                    if (typeof result === "string") {
                        correct_result = correct_result.toString();
                    }

                    if (compare(correct_result, result)) {
                        display_result("Test passed", true);
                    } else {
                        display_result("ERROR: files do not match!", false);
                        console.log();
                        all_tests_pass = false;
                    }

                    console.log("Decompression time:", deco_speed);

                    console.log();
                    next();
                }, progress);
            } catch (e) {
                if (p.basename(correct_filename) === "error-" + e.message) {
                    display_result("Test passed", true);
                    console.log("threw correct error: " + e.message);
                } else {
                    display_result("ERROR: " + e.message, false);
                    all_tests_pass = false;
                }
                console.log();
                next();
            }
        });
    });
}

function compression_test(file, next)
{
    fs.readFile(file, "utf8", function (err, content)
    {
        var comp_start = (new Date()).getTime(),
            compression_mode = 1,
            match,
            buf;

        if (err) {
            throw err;
        }

        if (typeof content === "object") {
            buf = new Buffer(content.length);
            content.copy(buf);
        }

        //console.log(content)
        match = p.basename(file, p.extname(file)).match(/^level[ _](\d)/i);

        if (match) {
            compression_mode = Number(match[1]) || 1;
        }
        console.log("     Initial size:", content.length);
        my_lzma.compress(buf || content, compression_mode, function ondone(compressed_result)
        {
            var comp_speed = (new Date()).getTime() - comp_start,
                deco_start;

            console.log("  Compressed size:", compressed_result.length);
            fs.writeFileSync("file.lzma", new Buffer(compressed_result))
            deco_start = (new Date()).getTime();
            my_lzma.decompress(compressed_result, function (decompressed_result)
            {
                var deco_speed = (new Date()).getTime() - deco_start;
                console.log("Decompressed size:", decompressed_result.length);

                if (typeof decompressed_result === "string") {
                    content = content.toString();
                }

                if (compare(content, decompressed_result)) {
                //if (content === result) {
                    display_result("Test passed", true);
                } else {
                    display_result("ERROR: files do not match!", false);
                    //console.log();
                    all_tests_pass = false;
                    //console.log(JSON.stringify(content.toJSON()))
                    //console.log(content.toString())
                    //console.log(" --- ");
                    //console.log(dbuf.toString())
                    //console.log(JSON.stringify(dbuf.toJSON()))
                    //process.exit();
                }

                console.log("  Compression time:", comp_speed);
                console.log("Decompression time:", deco_speed);

                console.log();
                next();
            }, progress);
        }, progress);
    });
}

function run_tests(cb)
{
    fs.readdir(path_to_files, function (err, files)
    {
        var file_count = files.length;

        if (err) {
            throw err;
        }

        (function run_test(i)
        {
            var file;

            if (i >= file_count) {
                if (all_tests_pass) {
                    display_result("All tests completed sucessfully", true);
                } else {
                    display_result("An error was detected!", false);
                }

                return cb ? cb(all_tests_pass) : 0;
            }
            file = files[i];

            console.log(file);

            if (file.slice(-5) === ".lzma") {
                /// Preform a decompress test on *.lzma files.
                decompression_test(p.join(path_to_files, file), p.join(path_to_files, file.slice(0, -5)), function next()
                {
                    run_test(i + 1);
                });
            } else {
                /// Preform a compression/decompression test.
                compression_test(p.join(path_to_files, file), function next()
                {
                    run_test(i + 1);
                });
            }
        }(0));
    });
}

function compare(a, b)
{
    var i;
    //console.log("comparing")
    //console.log(this)
    //console.log(b)
    //console.log(this.toJSON())
    //console.log(b.toJSON())

    if (typeof a !== typeof b) {
        console.log("BAD TYPES:", typeof a, "!==", typeof b)
        return false;
    }

    if (a.length !== b.length) {
        console.log("BAD LENGTH:", a.length, "!==", b.length)
        return false;
    }

    if (typeof a === "string") {
        if (a !== b) {
            var dump_file = Math.random();
            console.log("Dumping " + dump_file);
            fs.writeFileSync(dump_file + "-a", a);
            fs.writeFileSync(dump_file + "-b", b);
        }
        return a === b;
    }

    if (Buffer.isBuffer(a) && !Buffer.isBuffer(b) && Array.isArray(b)) {
        b = new Buffer(b);
    } else if (Buffer.isBuffer(b) && !Buffer.isBuffer(a) && Array.isArray(a)) {
        a = new Buffer(a);
    }

    for (i = a.length - 1; i >= 0; --i) {
        if (a[i] !== b[i]) {
            console.log("BAD VAL (" + i + "):",  a[i], "!==", b[i])
            return false;
        }
    }

    return true;
}

path_to_files = p.join(__dirname, path_to_files);

my_lzma = lzma_norm;

announce("Testing lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js");
run_tests(function (tests_passed_norm)
{
    if (!tests_passed_norm) {
        /// Fail.
        process.exit(1);
    }

    if (process.argv[2] === "nosep" || process.argv[3] === "nosep") {
        process.exit();
    }

    console.log("");
    announce("Testing lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js and lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js");
    my_lzma = lzma_sep;

    run_tests(function (tests_passed_sep)
    {
        if (!tests_passed_sep) {
            /// Fail.
            process.exit(1);
        }
    });
});
<|endoftext|>


<commit_before>var cldr = require('cldr');
var fs = require('fs-extra');
var path = require('path');
var Promise = require('ember-cli/lib/ext/promise');
var serialize = require('serialize-javascript');
var writeFile = Promise.denodeify(fs.outputFile);

module.exports = {
  description: 'Generate a locale',

  localeFor: function(options) {
    return options.entity.name;
  },

  locals: function(options) {
    var locale = this.localeFor(options);

    return {
      locale: locale
    };
  },

  afterInstall: function(options) {
    var locale = this.localeFor(options);
    var relativePath = path.join('app', 'locales', locale + '-cldr.js');
    var fullPath = path.join(this.project.root, relativePath);
    var data = {
      locale: locale,
      pluralRuleFunction: this.extractPluralRuleFunction(locale),
      fields: this.extractFields(locale)
    }
    var contents = 'export default ' + serialize(data) + ';';

    return writeFile(fullPath, contents);
  },

  /**
  https://github.com/yahoo/grunt-extract-cldr-data/blob/master/lib/extract.js
  Copyright (c) 2014 Yahoo Inc.
  Licensed under the Yahoo BSD license.
  */
  extractPluralRuleFunction: function(locale) {
    var fn = cldr.extractPluralRuleFunction(locale).toString();

    // Remove unnecessary function name.
    fn = fn.replace('function anonymous(', 'function (');

    // ParseInt() is expensive given that we already know the input is a number.
    fn = fn.replace('if(typeof n==="string")n=parseInt(n,10);', 'n=Math.floor(n);');

    // js-hint asi.
    fn = fn.replace('"\n}', '";\n}');
    // js-hint W018 "Confusing use of '!'" caused by stuff like "!(n===11)".
    fn = fn.replace(/!\((\w+)===(\d+)\)/g, '($1!==$2)');
    // js-hint W018 "Confusing use of '!'" caused by stuff like "!(n%100===11)".
    fn = fn.replace(/!\((\w+)%(\d+)===(\d+)\)/g, '($1%$2!==$3)');

    // Keep it neat.
    fn = fn.replace(/\n/g, '');

    // make sure the function
    if (fn === 'function (n) {}') {
      return null;
    }

    /* jshint evil:true */
    eval('fn = ' + fn);
    /* jshint evil:false */
    return fn;
  },

  extractFields: function(locale) {
    return cldr.extractFields(locale);
  }

};
<commit_msg>Extract CLDR data before install<commit_after>var cldr = require('cldr');
var fs = require('fs-extra');
var path = require('path');
var Promise = require('ember-cli/lib/ext/promise');
var serialize = require('serialize-javascript');
var SilentError = require('ember-cli/lib/errors/silent');
var writeFile = Promise.denodeify(fs.outputFile);

module.exports = {
  description: 'Generate a locale with CLDR data',

  normalizeEntityName: function(entityName) {
    if (!this.isKnownLocaleCode(entityName)) {
      throw new SilentError('The `ember generate locale` command does not ' +
      'know locale `' + entityName + '`.');
    }

    return this.normalizeLocaleCode(entityName);
  },

  locals: function(options) {
    var locale = this.localeCodeFor(options);

    return {
      locale: locale
    };
  },

  beforeInstall: function(options) {
    var code = this.localeCodeFor(options);
    var relativePath = path.join('app', 'locales', code + '-cldr.js');
    var fullPath = path.join(this.project.root, relativePath);

    var locale = {
      locale: code,
      pluralRuleFunction: this.extractPluralRuleFunction(code),
      fields: this.extractFields(code)
    }

    if (!this.isSupportedLocale(locale)) {
      return Promise.reject(new SilentError("The locale `" + code + "` is not supported."));
    }

    var contents = 'export default ' + serialize(locale) + ';';

    return writeFile(fullPath, contents);
  },

  localeCodeFor: function(options) {
    return this.normalizeLocaleCode(options.entity.name);
  },

  isKnownLocaleCode: function(code) {
    if (!code || code === 'root') {
      return false;
    }

    code = code.replace(/-/g, '_');
    code = code.toLowerCase();

    return cldr.localeIds.indexOf(code) >= 0;
  },

  isSupportedLocale: function(locale) {
    return !!locale.pluralRuleFunction && !!locale.fields
  },

  normalizeLocaleCode: function(code) {
    return code.replace(/_/g, '-');
  },

  /**
    https://github.com/yahoo/grunt-extract-cldr-data/blob/master/lib/extract.js
    Copyright (c) 2014 Yahoo Inc.
    Licensed under the Yahoo BSD license.
  */
  extractPluralRuleFunction: function(locale) {
    var fn = cldr.extractPluralRuleFunction(locale).toString();

    // Remove unnecessary function name.
    fn = fn.replace('function anonymous(', 'function (');

    // ParseInt() is expensive given that we already know the input is a number.
    fn = fn.replace('if(typeof n==="string")n=parseInt(n,10);', 'n=Math.floor(n);');

    // js-hint asi.
    fn = fn.replace('"\n}', '";\n}');
    // js-hint W018 "Confusing use of '!'" caused by stuff like "!(n===11)".
    fn = fn.replace(/!\((\w+)===(\d+)\)/g, '($1!==$2)');
    // js-hint W018 "Confusing use of '!'" caused by stuff like "!(n%100===11)".
    fn = fn.replace(/!\((\w+)%(\d+)===(\d+)\)/g, '($1%$2!==$3)');

    // Keep it neat.
    fn = fn.replace(/\n/g, '');

    // make sure the function
    if (fn === 'function (n) {}') {
      return null;
    }

    /* jshint evil:true */
    eval('fn = ' + fn);
    /* jshint evil:false */
    return fn;
  },

  extractFields: function(locale) {
    return cldr.extractFields(locale);
  }

};
<|endoftext|>


<commit_before><commit_msg>adding music<commit_after><|endoftext|>


<commit_before>var demand = require('must');
var LocationType = require('../LocationType');

exports.initList = function (List) {
	List.add({
		location: {
			basic: LocationType,
			customRequired: { type: LocationType, required: ['state', 'country'] },
		},
	});
};

exports.testFieldType = function (List) {
	var testItem = new List.model();

	var emptyLocationValues = {
		number: '',
		name: '',
		street1: '',
		street2: '',
		suburb: '',
		state: '',
		postcode: '',
		country: '',
		geo: [],
	};

	var resetLocationValues = function () {
		testItem.set('location.basic', emptyLocationValues);
		testItem.set('location.required', emptyLocationValues);
		testItem.set('location.customRequired', emptyLocationValues);
	};

	it('should update its value from flat paths', function (done) {
		resetLocationValues();
		List.fields['location.basic'].updateItem(testItem, {
			'location.basic.number': 'number',
			'location.basic.name': 'name',
			'location.basic.street1': 'street 1',
			'location.basic.street2': 'street 2',
			'location.basic.suburb': 'suburb',
			'location.basic.state': 'state',
			'location.basic.postcode': 'postcode',
			'location.basic.country': 'country',
			'location.basic.geo_lat': '-33.865143',
			'location.basic.geo_lng': '151.2099',
		}, function () {
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
			done();
		});
	});

	it('should update its value from nested paths', function (done) {
		resetLocationValues();
		List.fields['location.basic'].updateItem(testItem, {
			location: {
				basic: {
					number: 'number',
					name: 'name',
					street1: 'street 1',
					street2: 'street 2',
					suburb: 'suburb',
					state: 'state',
					postcode: 'postcode',
					country: 'country',
					geo: ['151.2099', '-33.865143'],
				},
			},
		}, function () {
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
			done();
		});
	});

	it('should remove the location.geo path without valid values', function (done) {
		resetLocationValues();
		List.fields['location.basic'].updateItem(testItem, {
			'location.basic.geo': ['151.2099', '-33.865143'],
		}, function () {
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);

			List.fields['location.basic'].updateItem(testItem, {
				'location.basic.geo_lat': '',
				'location.basic.geo_lng': '',
			}, function () {
				demand(testItem.location.basic.geo).be.undefined();
				done();
			});
		});
	});

	it('should validate required fields', function () {
		List.fields['location.basic'].inputIsValid({}, true, testItem).must.be.false();
		List.fields['location.basic'].inputIsValid({
			'location.basic.street1': 'street1',
			'location.basic.suburb': '',
		}, true, testItem).must.be.false();
		List.fields['location.basic'].inputIsValid({
			'location.basic.street1': 'street1',
			'location.basic.suburb': 'suburb',
		}, true, testItem).must.be.true();
		List.fields['location.basic'].inputIsValid({
			location: { basic: {
				street1: 'street1',
				suburb: 'suburb',
			} },
		}, true, testItem).must.be.true();
		List.fields['location.customRequired'].inputIsValid({
			'location.customRequired.street1': 'street1',
			'location.customRequired.suburb': 'suburb',
		}, true, testItem).must.be.false();
		List.fields['location.customRequired'].inputIsValid({
			'location.customRequired.state': 'state',
			'location.customRequired.country': 'country',
		}, true, testItem).must.be.true();
	});
};
<commit_msg>Add addFilterToQuery tests for location field<commit_after>var demand = require('must');
var LocationType = require('../LocationType');

exports.initList = function (List) {
	List.add({
		location: {
			basic: LocationType,
			customRequired: { type: LocationType, required: ['state', 'country'] },
		},
	});
};

exports.testFieldType = function (List) {
	var testItem = new List.model();

	var emptyLocationValues = {
		number: '',
		name: '',
		street1: '',
		street2: '',
		suburb: '',
		state: '',
		postcode: '',
		country: '',
		geo: [],
	};

	var resetLocationValues = function () {
		testItem.set('location.basic', emptyLocationValues);
		testItem.set('location.required', emptyLocationValues);
		testItem.set('location.customRequired', emptyLocationValues);
	};

	describe('addFilterToQuery', function () {
		it('should allow to filter by street', function () {
			var result = List.fields['location.basic'].addFilterToQuery({
				street: 'Broadway',
			});
			demand(result['location.basic.street1']).eql(/Broadway/i);
		});

		it('should allow to filter by city', function () {
			var result = List.fields['location.basic'].addFilterToQuery({
				city: 'NYC',
			});
			demand(result['location.basic.suburb']).eql(/NYC/i);
		});

		it('should allow to filter by state', function () {
			var result = List.fields['location.basic'].addFilterToQuery({
				state: 'New York',
			});
			demand(result['location.basic.state']).eql(/New York/i);
		});

		it('should allow to filter by code', function () {
			var result = List.fields['location.basic'].addFilterToQuery({
				code: 10023,
			});
			demand(result['location.basic.postcode']).eql(/10023/i);
		});

		it('should allow to filter by country', function () {
			var result = List.fields['location.basic'].addFilterToQuery({
				country: 'USA',
			});
			demand(result['location.basic.country']).eql(/USA/i);
		});

		it('should support inverted mode', function () {
			var result = List.fields['location.basic'].addFilterToQuery({
				country: 'USA',
				inverted: true,
			});
			demand(result['location.basic.country']).eql({
				$not: /USA/i,
			});
		});
	});

	it('should update its value from flat paths', function (done) {
		resetLocationValues();
		List.fields['location.basic'].updateItem(testItem, {
			'location.basic.number': 'number',
			'location.basic.name': 'name',
			'location.basic.street1': 'street 1',
			'location.basic.street2': 'street 2',
			'location.basic.suburb': 'suburb',
			'location.basic.state': 'state',
			'location.basic.postcode': 'postcode',
			'location.basic.country': 'country',
			'location.basic.geo_lat': '-33.865143',
			'location.basic.geo_lng': '151.2099',
		}, function () {
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
			done();
		});
	});

	it('should update its value from nested paths', function (done) {
		resetLocationValues();
		List.fields['location.basic'].updateItem(testItem, {
			location: {
				basic: {
					number: 'number',
					name: 'name',
					street1: 'street 1',
					street2: 'street 2',
					suburb: 'suburb',
					state: 'state',
					postcode: 'postcode',
					country: 'country',
					geo: ['151.2099', '-33.865143'],
				},
			},
		}, function () {
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
			done();
		});
	});

	it('should remove the location.geo path without valid values', function (done) {
		resetLocationValues();
		List.fields['location.basic'].updateItem(testItem, {
			'location.basic.geo': ['151.2099', '-33.865143'],
		}, function () {
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);

			List.fields['location.basic'].updateItem(testItem, {
				'location.basic.geo_lat': '',
				'location.basic.geo_lng': '',
			}, function () {
				demand(testItem.location.basic.geo).be.undefined();
				done();
			});
		});
	});

	it('should validate required fields', function () {
		List.fields['location.basic'].inputIsValid({}, true, testItem).must.be.false();
		List.fields['location.basic'].inputIsValid({
			'location.basic.street1': 'street1',
			'location.basic.suburb': '',
		}, true, testItem).must.be.false();
		List.fields['location.basic'].inputIsValid({
			'location.basic.street1': 'street1',
			'location.basic.suburb': 'suburb',
		}, true, testItem).must.be.true();
		List.fields['location.basic'].inputIsValid({
			location: { basic: {
				street1: 'street1',
				suburb: 'suburb',
			} },
		}, true, testItem).must.be.true();
		List.fields['location.customRequired'].inputIsValid({
			'location.customRequired.street1': 'street1',
			'location.customRequired.suburb': 'suburb',
		}, true, testItem).must.be.false();
		List.fields['location.customRequired'].inputIsValid({
			'location.customRequired.state': 'state',
			'location.customRequired.country': 'country',
		}, true, testItem).must.be.true();
	});
};
<|endoftext|>


<commit_before>/*
    The Group module provides dynamic interaction with User and Group
    objects in the database, through AJAX POST.
*/

var Group = (function ($, tools) {

    // Perform self check, display error if missing deps
    var performSelfCheck = function () {
        var errors = false
        if ($ == undefined) console.error('jQuery missing!')
        if (tools == undefined) console.error('Dashboard tools missing!')
        if (errors) return false
        return true
    }

    // Private helper method to draw the user table
    //
    // :param tbody: the ID of the
 element of the table
    // :param data: the JSON parsed data returned by the server
    var draw_table = function (tbody, data) {
        var tbody_html = ''
        $(data.users).each(function (i) {
            tbody_html += '
' + data.users[i].user + '' +
                          '' +
                          '' + '
'
        })
        $('#' + tbody).html(tbody_html)

        $(data.users).each(function (i) {
            var user = data.users[i]
            $('#user_' + user.id).on('click', function (e) {
                e.preventDefault()
                Group.user.remove(user.id)
            })
        })
    }

    // Private generic ajax handler.
    //
    // :param id: user ID in database
    // :param action: either 'remove_user' or 'add_user'
    var ajax_usermod = function (id, action) {
        var url = window.location.href.toString()
        var data = {
                "user_id": id,
                "action": action
        }
        var success = function (data) {
            if (action === 'remove_user') {
                data = JSON.parse(data)
                draw_table('userlist', data)
            }
            else if (action === 'add_user') {
                data = JSON.parse(data)
                draw_table('userlist', data)
            }
        }
        var error = function (xhr, txt, error) {
            tools.showStatusMessage(error, 'alert-danger')
        }

        // Make an AJAX request using the Dashboard tools module
        tools.ajax('POST', url, data, success, error, null)

    }

    return {

        // Bind them buttons here
        init: function () {

            if (!performSelfCheck()) return

            // Bind add users button
            $('#group_users_button').on('click', function (e) {
                e.preventDefault()
                $('#group_edit_users').slideToggle(200)
                $('#usersearch').focus()
            })

            // Bind remove user buttons
            $('.remove-user').each(function (i) {
                var cell = $(this).parent()
                var user_id = $(this).attr('id')
                $(this).on('click', function (e) {
                    e.preventDefault()
                    Group.user.remove(user_id)
                })
            })

            /* Typeahead for user search */

            // Smart toggle function
            $.fn.toggleDisabled = function() {
                return this.each(function() {
                    this.disabled = !this.disabled
                })
            }

            // Typeahead template
            var user_search_template =  [
                '
{{ name }}
'
            ].join('')

            // Bind the input field
            $('#usersearch').typeahead({
                remote: "/profile/api_user_search/?query=%QUERY",
                updater: function (item) {
                    return item
                },
                template: user_search_template,
                engine: Hogan
            }).on('typeahead:selected typeahead:autocompleted', function(e, datum) {
                ($(function() {
                    Group.user.add(datum.id)
                    $('#usersearch').val('')
                }))
            })
        },

        // User module, has add and remove functions
        user: {
            remove: function (user_id, cell) {
                ajax_usermod(user_id, 'remove_user')
            },

            add: function (user_id) {
                ajax_usermod(user_id, 'add_user')
            }
        }
    }

})(jQuery, Dashboard.tools)

$(document).ready(function () {
    Group.init()
})
<commit_msg>Add JS confirm dialog box<commit_after>/*
    The Group module provides dynamic interaction with User and Group
    objects in the database, through AJAX POST.
*/

var Group = (function ($, tools) {

    // Perform self check, display error if missing deps
    var performSelfCheck = function () {
        var errors = false
        if ($ == undefined) console.error('jQuery missing!')
        if (tools == undefined) console.error('Dashboard tools missing!')
        if (errors) return false
        return true
    }

    // Private helper method to draw the user table
    //
    // :param tbody: the ID of the
 element of the table
    // :param data: the JSON parsed data returned by the server
    var draw_table = function (tbody, data) {
        var tbody_html = ''
        $(data.users).each(function (i) {
            tbody_html += '
' + data.users[i].user + '' +
                          '' +
                          '' + '
'
        })
        $('#' + tbody).html(tbody_html)

        $(data.users).each(function (i) {
            var user = data.users[i]
            $('#user_' + user.id).on('click', function (e) {
                e.preventDefault()
                Group.user.remove(user.id)
            })
        })
    }

    // Private generic ajax handler.
    //
    // :param id: user ID in database
    // :param action: either 'remove_user' or 'add_user'
    var ajax_usermod = function (id, action) {
        var url = window.location.href.toString()
        var data = {
                "user_id": id,
                "action": action
        }
        var success = function (data) {
            if (action === 'remove_user') {
                data = JSON.parse(data)
                draw_table('userlist', data)
            }
            else if (action === 'add_user') {
                data = JSON.parse(data)
                draw_table('userlist', data)
            }
        }
        var error = function (xhr, txt, error) {
            tools.showStatusMessage(error, 'alert-danger')
        }

        // Make an AJAX request using the Dashboard tools module
        tools.ajax('POST', url, data, success, error, null)

    }

    return {

        // Bind them buttons here
        init: function () {

            if (!performSelfCheck()) return

            // Bind add users button
            $('#group_users_button').on('click', function (e) {
                e.preventDefault()
                $('#group_edit_users').slideToggle(200)
                $('#usersearch').focus()
            })

            // Bind remove user buttons
            $('.remove-user').each(function (i) {
                var cell = $(this).parent()
                var user_id = $(this).attr('id')
                $(this).on('click', function (e) {
                    e.preventDefault()
                    Group.user.remove(user_id)
                })
            })

            /* Typeahead for user search */

            // Smart toggle function
            $.fn.toggleDisabled = function() {
                return this.each(function() {
                    this.disabled = !this.disabled
                })
            }

            // Typeahead template
            var user_search_template =  [
                '
{{ name }}
'
            ].join('')

            // Bind the input field
            $('#usersearch').typeahead({
                remote: "/profile/api_user_search/?query=%QUERY",
                updater: function (item) {
                    return item
                },
                template: user_search_template,
                engine: Hogan
            }).on('typeahead:selected typeahead:autocompleted', function(e, datum) {
                ($(function() {
                    Group.user.add(datum.id)
                    $('#usersearch').val('')
                }))
            })
        },

        // User module, has add and remove functions
        user: {
            remove: function (user_id, cell) {
                if (confirm('Er du sikker på at du vil fjerne brukeren fra gruppen?')) {
                    ajax_usermod(user_id, 'remove_user')
                }
            },

            add: function (user_id) {
                ajax_usermod(user_id, 'add_user')
            }
        }
    }

})(jQuery, Dashboard.tools)

$(document).ready(function () {
    Group.init()
})
<|endoftext|>


<commit_before>$('document').ready(function() {
	require(['composer', 'composer/controls'], function(composer, controls) {
		composer.addButton('fa fa-eye-slash', function(textarea, selectionStart, selectionEnd) {
			if(selectionStart === selectionEnd){
				controls.insertIntoTextarea(textarea, '```/n',"Insert Language Name",'/n```');
				controls.updateTextareaSelection(textarea, selectionStart + 3, selectionStart + 26);
			} else {
				controls.wrapSelectionInTextareaWith(textarea, '```/n','/n```');
				controls.updateTextareaSelection(textarea, selectionStart + 3, selectionEnd + 3);
			}
		});
	});
});
<commit_msg>Update buttons.js<commit_after>$('document').ready(function() {
	require(['composer', 'composer/controls'], function(composer, controls) {
		composer.addButton('fa fa-eye-slash', function(textarea, selectionStart, selectionEnd) {
			if(selectionStart === selectionEnd){
				controls.insertIntoTextarea(textarea, '```\n"Insert Language Name"\n```');
				controls.updateTextareaSelection(textarea, selectionStart + 3, selectionStart + 26);
			} else {
				controls.wrapSelectionInTextareaWith(textarea, '```\n','\n```');
				controls.updateTextareaSelection(textarea, selectionStart + 3, selectionEnd + 3);
			}
		});
	});
});
<|endoftext|>


<commit_before>/*!

   VOD quality selector plugin for Flowplayer HTML5

   Copyright (c) 2016-2017, Flowplayer Drive Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Requires Flowplayer HTML5 version 7.x or greater
   $GIT_DESC$

*/
(function() {
  var extension = function(api) {
    var support = flowplayer.support;
    if (!support.inlineVideo) {
        return;
    }
    var hlsjs = false;
    if (api.conf.hlsjs !== false) {
      flowplayer.engines.forEach(function (engine) {
        if (engine.engineName === 'hlsjs' && engine.canPlay('application/x-mpegurl', api.conf)) {
          hlsjs = true;
        }
      });
    }
    api.on('load', function(_ev, _api, video) {
      if (_api.live) return;
      var c = _api.conf
        , vodQualities = video.vodQualities || c.vodQualities || {}
        , isDrive = (!!video.qualities || !!c.qualities) && (!!video.defaultQuality || !!c.defaultQuality);
      if (isDrive) {
        var originalQualities = video.originalQualities = video.originalQualities || video.qualities || c.qualities
          , defaultQuality = video.defaultQuality || c.defaultQuality
          , template = video.src.replace(/(-[0-9]+p)?\.(mp4|webm|m3u8|flv)$/, '-{q}.{ext}');
        if (typeof originalQualities === 'string') originalQualities = originalQualities.split(',');
        var qlities = ((typeof vodQualities.qualities === 'string' ? vodQualities.qualities.split(',') : vodQualities.qualities) || originalQualities || []).map(function(q) {
          if (q !== defaultQuality) return q;
          return {
            label: q,
            src: template.replace(/-{q}/, '')
          };
        });
        vodQualities = {
          template: template,
          qualities: qlities
        };
      }
      if (!vodQualities || !vodQualities.qualities || !vodQualities.qualities.length) return;
      video.hlsQualities = false;
      var vodQualitySources = {}
        , vodSource = video.sources.filter(function(s) { return !/mpegurl/i.test(s.type); })[0]
        , vodExt = vodSource && last(vodSource.src.split('.'))
        , hasHLSSource = video.sources.some(function(s) {
          if (!/mpegurl/i.test(s.type)) return false;
          vodQualitySources[-1] = {
            type: s.type,
            src: s.src
          };
          return true;
        })
        , flashSource;
        video.sources.forEach(function(s) {
          if (s.type.toLowerCase() === 'video/flash') flashSource = s.src;
        });
      if (!support.video && !flashSource ||
        flashSource && (!c.rtmp && !video.rtmp || /^(https?:)?\/\//.test(flashSource))) return;
      var qualities = hasHLSSource ? [{ value: -1, label: 'Auto' }] : []
        , fPrefix = flashSource && /^(mp4|flv):/.test(flashSource) && flashSource.slice(0, 4) || ''
        , fSuffix = flashSource && /\.(mp4|flv|f4v)$/i.test(flashSource) && flashSource.slice(flashSource.length - 3) || '';
      qualities = qualities.concat(vodQualities.qualities.map(function(q, i) {
        if (typeof q === 'string') {
          vodQualitySources[i] = {
            type: vodSource && vodSource.type,
            src: vodSource && vodSource.type && vodSource.type.toLowerCase() !== 'video/flash'
              ? vodQualities.template.replace('{q}', q).replace('{ext}', vodExt)
              : vodQualities.template.replace(/^(https?:)?\/\/[^/]+\//, fPrefix).replace('{q}', q).replace('{ext}', fSuffix)
          };
          return {
            value: i, label: q
          };
        }
        vodQualitySources[i] = {
          type: q.type || vodSource && vodSource.type,
          src: q.type || vodSource && vodSource.type && vodSource.type.toLowerCase() !== 'video/flash'
            ? q.src.replace('{ext}', vodExt)
            : q.src.replace(/^(https?:)?\/\/[^/]+\//, fPrefix).replace('{ext}', fSuffix)
        };
        return {
          value: i, label: q.label
        };
      }));
      video.qualities = qualities;
      if (/mpegurl/i.test(video.type)) video.quality = -1;
      else video.quality = Object.keys(vodQualitySources).filter(function(k) { return video.src.indexOf(vodQualitySources[k].src) > -1; })[0];
      video.vodQualitySources = vodQualitySources;
    });

    api.on('quality', function(_ev, _api, q) {
      var selectedQuality = api.video.vodQualitySources && api.video.vodQualitySources[q];
      if (!selectedQuality) return;
      var originalSources = api.video.originalSources || api.video.sources
        , extend = flowplayer.extend
        , video = extend({}, api.video, {
          originalSources: originalSources,
          sources: [{ type: selectedQuality.type, src: selectedQuality.src }].concat(originalSources),
          src: null,
          type: null
        });
      var time = video.time;
      if (hlsjs && video.hlsjs !== false && time && q < 0) {
        video.hlsjs = extend(video.hlsjs || {}, {startPosition: time});
      }
      api.load(video, function() {
        api.finished = false;
        if (time && !(video.hlsjs && video.hlsjs.startPosition)) {
          api.seek(time, function () {
            api.resume();
          });
        } else if (video.hlsjs) {
          video.hlsjs.startPosition = 0;
        }
      });
    });
  };

  if (typeof module === 'object' && module.exports) module.exports = extension;
  else if (typeof window.flowplayer === 'function') window.flowplayer(extension);

  function last(parts) { return parts[parts.length - 1]; }
})();
<commit_msg>Simplify passing api around<commit_after>/*!

   VOD quality selector plugin for Flowplayer HTML5

   Copyright (c) 2016-2017, Flowplayer Drive Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Requires Flowplayer HTML5 version 7.x or greater
   $GIT_DESC$

*/
(function() {
  var extension = function(api) {
    var support = flowplayer.support;
    if (!support.inlineVideo) {
        return;
    }
    var hlsjs = false;
    if (api.conf.hlsjs !== false) {
      flowplayer.engines.forEach(function (engine) {
        if (engine.engineName === 'hlsjs' && engine.canPlay('application/x-mpegurl', api.conf)) {
          hlsjs = true;
        }
      });
    }
    api.on('load', function(_ev, api, video) {
      if (api.live) return;
      var c = api.conf
        , vodQualities = video.vodQualities || c.vodQualities || {}
        , isDrive = (!!video.qualities || !!c.qualities) && (!!video.defaultQuality || !!c.defaultQuality);
      if (isDrive) {
        var originalQualities = video.originalQualities = video.originalQualities || video.qualities || c.qualities
          , defaultQuality = video.defaultQuality || c.defaultQuality
          , template = video.src.replace(/(-[0-9]+p)?\.(mp4|webm|m3u8|flv)$/, '-{q}.{ext}');
        if (typeof originalQualities === 'string') originalQualities = originalQualities.split(',');
        var qlities = ((typeof vodQualities.qualities === 'string' ? vodQualities.qualities.split(',') : vodQualities.qualities) || originalQualities || []).map(function(q) {
          if (q !== defaultQuality) return q;
          return {
            label: q,
            src: template.replace(/-{q}/, '')
          };
        });
        vodQualities = {
          template: template,
          qualities: qlities
        };
      }
      if (!vodQualities || !vodQualities.qualities || !vodQualities.qualities.length) return;
      video.hlsQualities = false;
      var vodQualitySources = {}
        , vodSource = video.sources.filter(function(s) { return !/mpegurl/i.test(s.type); })[0]
        , vodExt = vodSource && last(vodSource.src.split('.'))
        , hasHLSSource = video.sources.some(function(s) {
          if (!/mpegurl/i.test(s.type)) return false;
          vodQualitySources[-1] = {
            type: s.type,
            src: s.src
          };
          return true;
        })
        , flashSource;
        video.sources.forEach(function(s) {
          if (s.type.toLowerCase() === 'video/flash') flashSource = s.src;
        });
      if (!support.video && !flashSource ||
        flashSource && (!c.rtmp && !video.rtmp || /^(https?:)?\/\//.test(flashSource))) return;
      var qualities = hasHLSSource ? [{ value: -1, label: 'Auto' }] : []
        , fPrefix = flashSource && /^(mp4|flv):/.test(flashSource) && flashSource.slice(0, 4) || ''
        , fSuffix = flashSource && /\.(mp4|flv|f4v)$/i.test(flashSource) && flashSource.slice(flashSource.length - 3) || '';
      qualities = qualities.concat(vodQualities.qualities.map(function(q, i) {
        if (typeof q === 'string') {
          vodQualitySources[i] = {
            type: vodSource && vodSource.type,
            src: vodSource && vodSource.type && vodSource.type.toLowerCase() !== 'video/flash'
              ? vodQualities.template.replace('{q}', q).replace('{ext}', vodExt)
              : vodQualities.template.replace(/^(https?:)?\/\/[^/]+\//, fPrefix).replace('{q}', q).replace('{ext}', fSuffix)
          };
          return {
            value: i, label: q
          };
        }
        vodQualitySources[i] = {
          type: q.type || vodSource && vodSource.type,
          src: q.type || vodSource && vodSource.type && vodSource.type.toLowerCase() !== 'video/flash'
            ? q.src.replace('{ext}', vodExt)
            : q.src.replace(/^(https?:)?\/\/[^/]+\//, fPrefix).replace('{ext}', fSuffix)
        };
        return {
          value: i, label: q.label
        };
      }));
      video.qualities = qualities;
      if (/mpegurl/i.test(video.type)) video.quality = -1;
      else video.quality = Object.keys(vodQualitySources).filter(function(k) { return video.src.indexOf(vodQualitySources[k].src) > -1; })[0];
      video.vodQualitySources = vodQualitySources;
    });

    api.on('quality', function(_ev, api, q) {
      var selectedQuality = api.video.vodQualitySources && api.video.vodQualitySources[q];
      if (!selectedQuality) return;
      var originalSources = api.video.originalSources || api.video.sources
        , extend = flowplayer.extend
        , video = extend({}, api.video, {
          originalSources: originalSources,
          sources: [{ type: selectedQuality.type, src: selectedQuality.src }].concat(originalSources),
          src: null,
          type: null
        });
      var time = video.time;
      if (hlsjs && video.hlsjs !== false && time && q < 0) {
        video.hlsjs = extend(video.hlsjs || {}, {startPosition: time});
      }
      api.load(video, function(e, api) {
        api.finished = false;
        if (time && !(video.hlsjs && video.hlsjs.startPosition)) {
          api.seek(time, function () {
            api.resume();
          });
        } else if (video.hlsjs) {
          video.hlsjs.startPosition = 0;
        }
      });
    });
  };

  if (typeof module === 'object' && module.exports) module.exports = extension;
  else if (typeof window.flowplayer === 'function') window.flowplayer(extension);

  function last(parts) { return parts[parts.length - 1]; }
})();
<|endoftext|>


<commit_before>/* global angular */
'use strict'; // jshint ignore:line

angular.module('lumx.dialog', [])
    .service('LxDialogService', ['$timeout', function($timeout)
    {
        var self = this,
            dialogFilter,
            scopeMap = {};

        this.registerScope = function(dialogId, dialogScope)
        {
            scopeMap[dialogId] = dialogScope;
        };

        this.open = function(dialogId)
        {
            dialogFilter = angular.element('<div/>', {
                class: 'dialog-filter'
            });

            dialogFilter
                .appendTo('body')
                .bind('click', function()
                {
                    self.close(dialogId);
                });

            scopeMap[dialogId].element
                .appendTo('body')
                .show();

            $timeout(function()
            {
                dialogFilter.addClass('dialog-filter--is-shown');
                scopeMap[dialogId].element.addClass('dialog--is-shown');
            }, 100);
        };

        this.close = function(dialogId)
        {
            dialogFilter.removeClass('dialog-filter--is-shown');
            scopeMap[dialogId].element.removeClass('dialog--is-shown');

            $timeout(function()
            {
                dialogFilter.remove();

                scopeMap[dialogId].element
                    .hide()
                    .appendTo(scopeMap[dialogId].parent);
            }, 600);
        };
    }])
    .controller('LxDialogController', ['$scope', 'LxDialogService', function($scope, LxDialogService)
    {
        var dialogScope = $scope.$new();

        this.init = function(element, dialogId)
        {
            dialogScope.element = element;
            dialogScope.parent = element.parent();

            LxDialogService.registerScope(dialogId, dialogScope);
        };

        $scope.$on('$destroy', function()
        {
            dialogScope.$destroy();
        });
    }])
    .directive('lxDialog', function()
    {
        return {
            restrict: 'A',
            controller: 'LxDialogController',
            scope: {},
            link: function(scope, element, attrs, ctrl)
            {
                element.on('click', function(event)
                {
                    event.stopPropagation();
                });

                attrs.$observe('id', function(newId)
                {
                    if (newId)
                    {
                        ctrl.init(element, newId);
                    }
                });
            }
        };
    })
    .directive('lxDialogClose', ['LxDialogService', function(LxDialogService)
    {
        return {
            restrict: 'A',
            link: function(scope, element)
            {
                element.bind('click', function()
                {
                    LxDialogService.close(element.parents('.dialog').attr('id'));
                });
            }
        };
    }]);
<commit_msg>refactor dialog: remove useless destroy method<commit_after>/* global angular */
'use strict'; // jshint ignore:line

angular.module('lumx.dialog', [])
    .service('LxDialogService', ['$timeout', function($timeout)
    {
        var self = this,
            dialogFilter,
            scopeMap = {};

        this.registerScope = function(dialogId, dialogScope)
        {
            scopeMap[dialogId] = dialogScope;
        };

        this.open = function(dialogId)
        {
            dialogFilter = angular.element('<div/>', {
                class: 'dialog-filter'
            });

            dialogFilter
                .appendTo('body')
                .bind('click', function()
                {
                    self.close(dialogId);
                });

            scopeMap[dialogId].element
                .appendTo('body')
                .show();

            $timeout(function()
            {
                dialogFilter.addClass('dialog-filter--is-shown');
                scopeMap[dialogId].element.addClass('dialog--is-shown');
            }, 100);
        };

        this.close = function(dialogId)
        {
            dialogFilter.removeClass('dialog-filter--is-shown');
            scopeMap[dialogId].element.removeClass('dialog--is-shown');

            $timeout(function()
            {
                dialogFilter.remove();

                scopeMap[dialogId].element
                    .hide()
                    .appendTo(scopeMap[dialogId].parent);
            }, 600);
        };
    }])
    .controller('LxDialogController', ['$scope', 'LxDialogService', function($scope, LxDialogService)
    {
        var dialogScope = $scope.$new();

        this.init = function(element, dialogId)
        {
            dialogScope.element = element;
            dialogScope.parent = element.parent();

            LxDialogService.registerScope(dialogId, dialogScope);
        };
    }])
    .directive('lxDialog', function()
    {
        return {
            restrict: 'A',
            controller: 'LxDialogController',
            scope: {},
            link: function(scope, element, attrs, ctrl)
            {
                element.on('click', function(event)
                {
                    event.stopPropagation();
                });

                attrs.$observe('id', function(newId)
                {
                    if (newId)
                    {
                        ctrl.init(element, newId);
                    }
                });
            }
        };
    })
    .directive('lxDialogClose', ['LxDialogService', function(LxDialogService)
    {
        return {
            restrict: 'A',
            link: function(scope, element)
            {
                element.bind('click', function()
                {
                    LxDialogService.close(element.parents('.dialog').attr('id'));
                });
            }
        };
    }]);
<|endoftext|>