<commit_before>// UI and App logic
import MainWindow from './main-window';
import WindowManager from './window-manager';
import Skin from './skin';
import Media from './media';
import MyFile from './my-file';

import '../css/winamp.css';

module.exports = {
  init: function(options) {
    this.fileInput = document.createElement('input');
    this.fileInput.type = 'file';
    this.fileInput.style.display = 'none';

    this.windowManager = WindowManager;
    this.media = Media.init();
    this.skin = Skin.init(document.getElementById('visualizer'), this.media._analyser);
    this.state = '';

    this.mainWindow = MainWindow.init(this);

    this.events = {
      timeUpdated: new Event('timeUpdated'),
      startWaiting: new Event('startWaiting'),
      stopWaiting: new Event('stopWaiting'),
      startLoading: new Event('startLoading'),
      stopLoading: new Event('stopLoading'),
      changeState: new Event('changeState'),
      titleUpdated: new Event('titleUpdated'),
      channelCountUpdated: new Event('channelCountUpdated'),
      balanceChanged: new Event('balanceChanged'),
      doubledModeToggled: new Event('doubledModeToggled'),
      repeatToggled: new Event('repeatToggled'),
      llamaToggled: new Event('llamaToggled'),
      close: new Event('close')
    };

    this.dispatch({type: 'SET_VOLUME', volume: options.volume});
    this.setBalance(options.balance);
    this.loadFromUrl(options.mediaFile.url, options.mediaFile.name);
    var skinFile = new MyFile();
    skinFile.setUrl(options.skinUrl);
    this.setSkin(skinFile);

    this._registerListeners();
    return this;
  },

  _registerListeners: function() {
    var self = this;

    this.windowManager.registerWindow(this.mainWindow);

    this.media.addEventListener('timeupdate', function() {
      self.dispatch({type: 'UPDATE_TIME_ELAPSED', elapsed: self.media.timeElapsed()});
      // Legacy
      window.dispatchEvent(self.events.timeUpdated);
    });

    this.media.addEventListener('visualizerupdate', function(analyser) {
      self.skin.visualizer.paintFrame(self.visualizerStyle, analyser);
    });

    this.media.addEventListener('ended', function() {
      self.skin.visualizer.clear();
      self.setState('stop');
    });

    this.media.addEventListener('waiting', function() {
      window.dispatchEvent(self.events.startWaiting);
    });

    this.media.addEventListener('stopWaiting', function() {
      window.dispatchEvent(self.events.stopWaiting);
    });

    this.media.addEventListener('playing', function() {
      self.setState('play');
    });

    this.fileInput.onchange = function(e){
      self.loadFromFileReference(e.target.files[0]);
    };
  },

  /* Functions */
  setState: function(state) {
    this.state = state;
    window.dispatchEvent(this.events.changeState);
  },

  getState: function() {
    return this.state;
  },

  getDuration: function() {
    return this.media.duration();
  },

  getTimeRemaining: function() {
    return this.media.timeRemaining();
  },

  getTimeElapsed: function() {
    return this.media.timeElapsed();
  },

  getPercentComplete: function() {
    return this.media.percentComplete();
  },

  getChannelCount: function() {
    return this.media.channels();
  },

  getVolume: function() {
    return Math.round(this.media.getVolume());
  },

  seekToPercentComplete: function(percent) {
    this.media.seekToPercentComplete(percent);
  },

  play: function() {
    if (this.getState() === 'play'){
      this.media.stop();
    }
    this.media.play();
    this.setState('play');
  },

  pause: function() {
    if (this.getState() === 'pause'){
      this.media.play();
    } else if (this.getState() === 'play') {
      this.media.pause();
      this.setState('pause');
    }
  },
  stop: function() {
    this.media.stop();
    this.setState('stop');
  },

  // From 0-100
  setVolume: function(volume) {
    // Ensure volume does not go out of bounds
    volume = Math.max(volume, 0);
    volume = Math.min(volume, 100);

    this.media.setVolume(volume);
  },

  incrementVolumeBy: function(ammount) {
    this.setVolume((this.media.getVolume()) + ammount);
  },

  toggleDoubledMode: function() {
    window.dispatchEvent(this.events.doubledModeToggled);
  },

  // From -100 to 100
  setBalance: function(balance) {
    this.media.setBalance(balance);
    window.dispatchEvent(this.events.balanceChanged);
  },

  getBalance: function() {
    return this.media.getBalance();
  },

  seekForwardBy: function(seconds) {
    this.media.seekToTime(this.media.timeElapsed() + seconds);
    window.dispatchEvent(self.events.timeUpdated);
  },

  toggleRepeat: function() {
    this.media.toggleRepeat();
    window.dispatchEvent(this.events.repeatToggled);
  },

  toggleShuffle: function() {
    this.media.toggleShuffle();
    this.mainWindow.toggleShuffle();
  },

  toggleLlama: function() {
    window.dispatchEvent(this.events.llamaToggled);
  },

  close: function() {
    window.dispatchEvent(this.events.close);
    this.media.stop();
    this.setState('stop'); // Currently unneeded
  },

  openFileDialog: function() {
    this.fileInput.click();
  },

  loadFromFileReference: function(fileReference) {
    var file = new MyFile();
    file.setFileReference(fileReference);
    if (new RegExp('(wsz|zip)$', 'i').test(fileReference.name)) {
      this.skin.setSkinByFile(file);
    } else {
      this.media.autoPlay = true;
      this.fileName = fileReference.name;
      file.processBuffer(this._loadBuffer.bind(this));
    }
  },

  // Used only for the initial load, since it must have a CORS header
  loadFromUrl: function(url, fileName) {
    if (!fileName) {
      this.fileName = url.split('/').pop();
    } else {
      this.fileName = fileName;
    }
    var file = new MyFile();
    file.setUrl(url);
    file.processBuffer(this._loadBuffer.bind(this));
  },

  setSkin: function(file) {
    this.setLoadingState();
    this.skin.setSkinByFile(file, this.unsetLoadingState.bind(this));
  },

  setLoadingState: function() {
    window.dispatchEvent(this.events.startLoading);
  },

  unsetLoadingState: function() {
    window.dispatchEvent(this.events.stopLoading);
  },

  toggleVisualizer: function() {
    if (this.skin.visualizer.style === this.skin.visualizer.NONE) {
      this.skin.visualizer.setStyle(this.skin.visualizer.BAR);
    } else if (this.skin.visualizer.style === this.skin.visualizer.BAR) {
      this.skin.visualizer.setStyle(this.skin.visualizer.OSCILLOSCOPE);
    } else if (this.skin.visualizer.style === this.skin.visualizer.OSCILLOSCOPE) {
      this.skin.visualizer.setStyle(this.skin.visualizer.NONE);
    }
    this.skin.visualizer.clear();
  },

  /* Listeners */
  _loadBuffer: function(buffer) {
    function setMetaData() {
      var kbps = '128';
      var khz = Math.round(this.media.sampleRate() / 1000).toString();
      this.dispatch({type: 'SET_MEDIA_KBPS', kbps: kbps});
      this.dispatch({type: 'SET_MEDIA_KHZ', khz: khz});
      window.dispatchEvent(this.events.channelCountUpdated);
      window.dispatchEvent(this.events.titleUpdated);
      window.dispatchEvent(this.events.timeUpdated);
      this.dispatch({type: 'SET_MEDIA_LENGTH', length: this.media.duration()});
    }

    // Note, this will not happen right away
    this.media.loadBuffer(buffer, setMetaData.bind(this));
  },

  /* Helpers */
  _timeObject: function(time) {
    var minutes = Math.floor(time / 60);
    var seconds = time - (minutes * 60);

    return [
      Math.floor(minutes / 10),
      Math.floor(minutes % 10),
      Math.floor(seconds / 10),
      Math.floor(seconds % 10)
    ];
  }
};
<commit_msg>Remove unused volume code<commit_after>// UI and App logic
import MainWindow from './main-window';
import WindowManager from './window-manager';
import Skin from './skin';
import Media from './media';
import MyFile from './my-file';

import '../css/winamp.css';

module.exports = {
  init: function(options) {
    this.fileInput = document.createElement('input');
    this.fileInput.type = 'file';
    this.fileInput.style.display = 'none';

    this.windowManager = WindowManager;
    this.media = Media.init();
    this.skin = Skin.init(document.getElementById('visualizer'), this.media._analyser);
    this.state = '';

    this.mainWindow = MainWindow.init(this);

    this.events = {
      timeUpdated: new Event('timeUpdated'),
      startWaiting: new Event('startWaiting'),
      stopWaiting: new Event('stopWaiting'),
      startLoading: new Event('startLoading'),
      stopLoading: new Event('stopLoading'),
      changeState: new Event('changeState'),
      titleUpdated: new Event('titleUpdated'),
      channelCountUpdated: new Event('channelCountUpdated'),
      balanceChanged: new Event('balanceChanged'),
      doubledModeToggled: new Event('doubledModeToggled'),
      repeatToggled: new Event('repeatToggled'),
      llamaToggled: new Event('llamaToggled'),
      close: new Event('close')
    };

    this.dispatch({type: 'SET_VOLUME', volume: options.volume});
    this.setBalance(options.balance);
    this.loadFromUrl(options.mediaFile.url, options.mediaFile.name);
    var skinFile = new MyFile();
    skinFile.setUrl(options.skinUrl);
    this.setSkin(skinFile);

    this._registerListeners();
    return this;
  },

  _registerListeners: function() {
    var self = this;

    this.windowManager.registerWindow(this.mainWindow);

    this.media.addEventListener('timeupdate', function() {
      self.dispatch({type: 'UPDATE_TIME_ELAPSED', elapsed: self.media.timeElapsed()});
      // Legacy
      window.dispatchEvent(self.events.timeUpdated);
    });

    this.media.addEventListener('visualizerupdate', function(analyser) {
      self.skin.visualizer.paintFrame(self.visualizerStyle, analyser);
    });

    this.media.addEventListener('ended', function() {
      self.skin.visualizer.clear();
      self.setState('stop');
    });

    this.media.addEventListener('waiting', function() {
      window.dispatchEvent(self.events.startWaiting);
    });

    this.media.addEventListener('stopWaiting', function() {
      window.dispatchEvent(self.events.stopWaiting);
    });

    this.media.addEventListener('playing', function() {
      self.setState('play');
    });

    this.fileInput.onchange = function(e){
      self.loadFromFileReference(e.target.files[0]);
    };
  },

  /* Functions */
  setState: function(state) {
    this.state = state;
    window.dispatchEvent(this.events.changeState);
  },

  getState: function() {
    return this.state;
  },

  getDuration: function() {
    return this.media.duration();
  },

  getTimeRemaining: function() {
    return this.media.timeRemaining();
  },

  getTimeElapsed: function() {
    return this.media.timeElapsed();
  },

  getPercentComplete: function() {
    return this.media.percentComplete();
  },

  getChannelCount: function() {
    return this.media.channels();
  },

  seekToPercentComplete: function(percent) {
    this.media.seekToPercentComplete(percent);
  },

  play: function() {
    if (this.getState() === 'play'){
      this.media.stop();
    }
    this.media.play();
    this.setState('play');
  },

  pause: function() {
    if (this.getState() === 'pause'){
      this.media.play();
    } else if (this.getState() === 'play') {
      this.media.pause();
      this.setState('pause');
    }
  },
  stop: function() {
    this.media.stop();
    this.setState('stop');
  },

  // From 0-100
  setVolume: function(volume) {
    // Ensure volume does not go out of bounds
    volume = Math.max(volume, 0);
    volume = Math.min(volume, 100);

    this.media.setVolume(volume);
  },

  toggleDoubledMode: function() {
    window.dispatchEvent(this.events.doubledModeToggled);
  },

  // From -100 to 100
  setBalance: function(balance) {
    this.media.setBalance(balance);
    window.dispatchEvent(this.events.balanceChanged);
  },

  getBalance: function() {
    return this.media.getBalance();
  },

  seekForwardBy: function(seconds) {
    this.media.seekToTime(this.media.timeElapsed() + seconds);
    window.dispatchEvent(self.events.timeUpdated);
  },

  toggleRepeat: function() {
    this.media.toggleRepeat();
    window.dispatchEvent(this.events.repeatToggled);
  },

  toggleShuffle: function() {
    this.media.toggleShuffle();
    this.mainWindow.toggleShuffle();
  },

  toggleLlama: function() {
    window.dispatchEvent(this.events.llamaToggled);
  },

  close: function() {
    window.dispatchEvent(this.events.close);
    this.media.stop();
    this.setState('stop'); // Currently unneeded
  },

  openFileDialog: function() {
    this.fileInput.click();
  },

  loadFromFileReference: function(fileReference) {
    var file = new MyFile();
    file.setFileReference(fileReference);
    if (new RegExp('(wsz|zip)$', 'i').test(fileReference.name)) {
      this.skin.setSkinByFile(file);
    } else {
      this.media.autoPlay = true;
      this.fileName = fileReference.name;
      file.processBuffer(this._loadBuffer.bind(this));
    }
  },

  // Used only for the initial load, since it must have a CORS header
  loadFromUrl: function(url, fileName) {
    if (!fileName) {
      this.fileName = url.split('/').pop();
    } else {
      this.fileName = fileName;
    }
    var file = new MyFile();
    file.setUrl(url);
    file.processBuffer(this._loadBuffer.bind(this));
  },

  setSkin: function(file) {
    this.setLoadingState();
    this.skin.setSkinByFile(file, this.unsetLoadingState.bind(this));
  },

  setLoadingState: function() {
    window.dispatchEvent(this.events.startLoading);
  },

  unsetLoadingState: function() {
    window.dispatchEvent(this.events.stopLoading);
  },

  toggleVisualizer: function() {
    if (this.skin.visualizer.style === this.skin.visualizer.NONE) {
      this.skin.visualizer.setStyle(this.skin.visualizer.BAR);
    } else if (this.skin.visualizer.style === this.skin.visualizer.BAR) {
      this.skin.visualizer.setStyle(this.skin.visualizer.OSCILLOSCOPE);
    } else if (this.skin.visualizer.style === this.skin.visualizer.OSCILLOSCOPE) {
      this.skin.visualizer.setStyle(this.skin.visualizer.NONE);
    }
    this.skin.visualizer.clear();
  },

  /* Listeners */
  _loadBuffer: function(buffer) {
    function setMetaData() {
      var kbps = '128';
      var khz = Math.round(this.media.sampleRate() / 1000).toString();
      this.dispatch({type: 'SET_MEDIA_KBPS', kbps: kbps});
      this.dispatch({type: 'SET_MEDIA_KHZ', khz: khz});
      window.dispatchEvent(this.events.channelCountUpdated);
      window.dispatchEvent(this.events.titleUpdated);
      window.dispatchEvent(this.events.timeUpdated);
      this.dispatch({type: 'SET_MEDIA_LENGTH', length: this.media.duration()});
    }

    // Note, this will not happen right away
    this.media.loadBuffer(buffer, setMetaData.bind(this));
  },

  /* Helpers */
  _timeObject: function(time) {
    var minutes = Math.floor(time / 60);
    var seconds = time - (minutes * 60);

    return [
      Math.floor(minutes / 10),
      Math.floor(minutes % 10),
      Math.floor(seconds / 10),
      Math.floor(seconds % 10)
    ];
  }
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    var systemForm = null;

    function enable_system_form( data ) {
        systemForm = (function(){
            // avoid duplicate fields id's
            var staticForm = $('
')
                .html(data.static_form);
            var dynamicForm = $('
')
                .html(data.dynamic_form);
            var initialType = data.initial_type;
            var intrType = "input[name=interface_type]";
            return {
                getInitialType: function() {
                    return initialType;
                },
                showStaticForm: function( delay, speed ) {
                    setTimeout( function() {
                        $('#hidden-inner-form').append( staticForm );
                        $('#static-form').slideDown( speed );
                    }, delay);
                    $('#dynamic-form').slideUp( function() {
                        $('#dynamic-form').remove();
                    });
                },
                showDynamicForm: function( delay, speed ) {
                    setTimeout( function() {
                        $('#hidden-inner-form').append( dynamicForm );
                        $('#dynamic-form').slideDown( speed );
                    }, delay);
                    $('#static-form').slideUp( function() {
                        $('#static-form').remove();
                    });
                },
                submitForm: function() {
                    var fields;
                    var form = $('#obj-form form');
                    form.find('.error').remove();
                    if ( $(intrType).attr( 'type' ) != "hidden"
                            && $(intrType + ":checked").val() === undefined) {
                        $("label[for=id_interface_type_0]:first").after(
                            '
This field is required.
');
                        return false;
                    } else {
                        fields = form.find(':input:visible').serializeArray();
                    }
                    if ( initialType && initialType.length ) {
                        field = form.find(intrType).serializeArray()[0]
                        fields.push(field);
                    }

                    var url = '/core/system/create/';
                    var csrfToken = $('#view-metadata').attr( 'data-csrfToken' );
                    $.when( ajax_form_submit( url, fields, csrfToken ) ).done(
                            function( ret_data ) {
                        location.href = '/core/system/' + ret_data.system_id.toString();
                    });
                }
            };
        }());
    }

    function changeSystemForm( value, delay, speed ) {
        if ( value == 'static_interface' ) {
            systemForm.showStaticForm( delay, speed );
        } else {
            systemForm.showDynamicForm( delay, speed );
        }
    }

    $( document ).on( 'change', 'input[name="interface_type"]', function() {
        $('#form-metadata').attr( 'interfaceType', this.value );
        // dont delay on initial page load
        if( $('#dynamic-form').length || $('#static-form').length ) {
            changeSystemForm( this.value, 500, 'slow' );
        } else {
            changeSystemForm( this.value, 0, 'fast' );
        }
    });

    $( document ).on('click', '.system-submit', function( e ) {
        e.preventDefault();
        systemForm.submitForm();
    });

    $( document ).on( 'click', '.system_form', function( e ) {
        e.preventDefault();
        slideUp( $('#obj-form') );
        if( !$(this).hasClass( 'selected' ) ) {
            return false;
        }
        url = this.href;
        button_to_ajax( this, null, { 'mode': 'GET', 'dataType': 'json' } )
        .done( function( data ) {
            $('#form-title').html( data.form_title );
            $('.form-btns .btn').not('.cancel')
                .text( data.submit_btn_label );
            $('.form-btns .btn').not('.cancel')
                .attr( 'class', 'btn c system-submit');
            $('#hidden-inner-form').empty().append( data.system_form );
            slideDown( $('#obj-form') );
            enable_system_form( data );
            metaData = $('
')
                .attr( 'interfaceType', data.initial_type )
                .attr( 'objType', 'system' )
                .attr( 'style', 'display:none' );
            $('#hidden-inner-form').append( metaData );
            if ( data.initial_type ) {
                changeSystemForm( data.initial_type, 0, 'fast' );
                $('#form-metadata').attr( 'interfaceType', data.initial_type );
            }
        });
    });

    // If landing on an empty system list page, bring up create form
    if( $('.table').length === 0 ) {
        $('.system_form').click();
    }
});
<commit_msg>Move metadata change to parent function<commit_after>$(document).ready(function() {
    var systemForm = null;

    function enable_system_form( data ) {
        systemForm = (function(){
            // avoid duplicate fields id's
            var staticForm = $('
')
                .html(data.static_form);
            var dynamicForm = $('
')
                .html(data.dynamic_form);
            var initialType = data.initial_type;
            var intrType = "input[name=interface_type]";
            return {
                getInitialType: function() {
                    return initialType;
                },
                showStaticForm: function( delay, speed ) {
                    setTimeout( function() {
                        $('#hidden-inner-form').append( staticForm );
                        $('#static-form').slideDown( speed );
                    }, delay);
                    $('#dynamic-form').slideUp( function() {
                        $('#dynamic-form').remove();
                    });
                },
                showDynamicForm: function( delay, speed ) {
                    setTimeout( function() {
                        $('#hidden-inner-form').append( dynamicForm );
                        $('#dynamic-form').slideDown( speed );
                    }, delay);
                    $('#static-form').slideUp( function() {
                        $('#static-form').remove();
                    });
                },
                submitForm: function() {
                    var fields;
                    var form = $('#obj-form form');
                    form.find('.error').remove();
                    if ( $(intrType).attr( 'type' ) != "hidden"
                            && $(intrType + ":checked").val() === undefined) {
                        $("label[for=id_interface_type_0]:first").after(
                            '
This field is required.
');
                        return false;
                    } else {
                        fields = form.find(':input:visible').serializeArray();
                    }
                    if ( initialType && initialType.length ) {
                        field = form.find(intrType).serializeArray()[0]
                        fields.push(field);
                    }

                    var url = '/core/system/create/';
                    var csrfToken = $('#view-metadata').attr( 'data-csrfToken' );
                    $.when( ajax_form_submit( url, fields, csrfToken ) ).done(
                            function( ret_data ) {
                        location.href = '/core/system/' + ret_data.system_id.toString();
                    });
                }
            };
        }());
    }

    function changeSystemForm( value, delay, speed ) {
        $('#form-metadata').attr( 'interfaceType', value );
        if ( value == 'static_interface' ) {
            systemForm.showStaticForm( delay, speed );
        } else {
            systemForm.showDynamicForm( delay, speed );
        }
    }

    $( document ).on( 'change', 'input[name="interface_type"]', function() {
        // dont delay on initial page load
        if( $('#dynamic-form').length || $('#static-form').length ) {
            changeSystemForm( this.value, 500, 'slow' );
        } else {
            changeSystemForm( this.value, 0, 'fast' );
        }
    });

    $( document ).on('click', '.system-submit', function( e ) {
        e.preventDefault();
        systemForm.submitForm();
    });

    $( document ).on( 'click', '.system_form', function( e ) {
        e.preventDefault();
        slideUp( $('#obj-form') );
        if( !$(this).hasClass( 'selected' ) ) {
            return false;
        }
        url = this.href;
        button_to_ajax( this, null, { 'mode': 'GET', 'dataType': 'json' } )
        .done( function( data ) {
            $('#form-title').html( data.form_title );
            $('.form-btns .btn').not('.cancel')
                .text( data.submit_btn_label );
            $('.form-btns .btn').not('.cancel')
                .attr( 'class', 'btn c system-submit');
            $('#hidden-inner-form').empty().append( data.system_form );
            slideDown( $('#obj-form') );
            enable_system_form( data );
            metaData = $('
')
                .attr( 'interfaceType', data.initial_type )
                .attr( 'objType', 'system' )
                .attr( 'style', 'display:none' );
            $('#hidden-inner-form').append( metaData );
            if ( data.initial_type ) {
                changeSystemForm( data.initial_type, 0, 'fast' );
            }
        });
    });

    // If landing on an empty system list page, bring up create form
    if( $('.table').length === 0 ) {
        $('.system_form').click();
    }
});
<|endoftext|>


<commit_before>
const EXPORT = ['Manager'];

var Manager = {};
let PS = Cc["@mozilla.org/embedcomp/prompt-service;1"].
         getService(Ci.nsIPromptService);

Manager.sketch = {
    sketches: [],
    hasSketch: function(sid) {
        if (!sid) return false;
        let sketches = this.sketches;
        for (let i = 0;  i < sketches.length; i++) {
            if (sketches[i].sid == sid) {
                return sketches[i];
            }
        }
        return false;
    },
    removeSketch: function(sid) {
        if (!sid) return false;
        let sketches = this.sketches;
        for (let i = 0;  i < sketches.length; i++) {
            if (sketches[i].sid == sid) {
                sketches.splice(i, 1);
                return true;
            }
        }
        return false;
    },
    addSketch: function(sketch) {
        if (!this.hasSketch(sketch.sid)) {
            this.sketches.push(sketch);
            return true;
        } else {
            return false;
        }
    },
    getSketckById: function(sid) {
        if (!sid) return;
        return this.hasSketch(sid);
    },
};

Manager.draw = function() {
    let win = getTopWin().content;
    if (!win || !win.document) return;

    p('draw!: sid: '  + win.__sketch_switch_sid__);
    let eventType = 'ShowSketch';
    let sketch;
    if (sketch = Manager.sketch.getSketckById(win.__sketch_switch_sid__)) {
        p('has sketch!');
        //
    } else {
        let options = {};
        if (!Prefs.screenshot.drawingHardMode) {
            options.buttons = ['Close', 'RedPen', 'BlackPen', 'Eraser', 'Clear'];
            options.noCreatePalette = true;
        }
        sketch = new SketchSwitch(win, options);
        Manager.sketch.addSketch(sketch);
        win.__sketch_switch_sid__ = sketch.sid;
        var unloader = function(event) {
            p('remove sketch obj: ' + Manager.sketch.removeSketch(win.__sketch_switch_sid__));
            sketch.destroy();
            win.removeEventListener('unload', unloader, false);
        };
        win.addEventListener('unload', unloader, false);
    }
    sketch.hideMenuMoving = Prefs.screenshot.get('hideMenuMoving');
    sketch.show();
    // var random = Math.random().toString().slice(2);
};

Manager.showPopup = function(event) {
    if (event.ctrlKey) {
        return Manager.draw();
    }
    let icon = document.getElementById('hScreenshot-statusIcon');
    let menu = document.getElementById('hScreenshot-menu-popup');
    menu = menu.cloneNode(true);
    icon.parentNode.appendChild(menu);
    menu.openPopup(icon, 'before_end', 0, 0, false, true);
};

Manager.Base = {
    createFinish: function() {
        let sketch;
        if (window.content &&
            (sketch = Manager.sketch.getSketckById(window.content.__sketch_switch_sid__))) {
            if (sketch.shownMenu) {
                sketch.hideMenu();

                return function() {
                    sketch.showMenu();
                    p('capture finish (show menu)');
                }
            }
        }
        return function() {
            p('capture finish');
        };
    },
    all: function() {
        this.capture('all', this.createFinish());
    },
    rect: function() {
        this.capture('rect', this.createFinish());
    },
    inner: function() {
        this.capture('inner', this.createFinish());
    }
};

Manager.Upload = extend({}, Manager.Base);
extend(Manager.Upload, {
    capture: function(method, finish) {
        p('upload capture: ' + method);
        // method: all, rect, inner
        if (!User.user) {
            let PS = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
            if (PS.confirm(window.top, convertStringEncoding('はてなスクリーンショット'), convertStringEncoding('フォトライフにアップロードするには、はてなへのログインが必要です。'))) {
                openUILinkIn("https://www.hatena.ne.jp/login?location=http%3A%2F%2Fwww.hatena.ne.jp%2Ftoolbar%2Ffirefo%23HatenaScreenshot&ref=hatena-screenshot", 'tab');
            }
            finish();
            return;
        }

        if (method == 'rect') {
            let self = this;
            Capture.rect(true, function(data) {
                self._capture(method, data, finish);
            });
        } else {
            this._capture(method, null, finish);
        }
    },

    _capture: function(method, data, finish) {
        let config = this.configDialog();
        if (config.accept) {
            p('capture accept (config):' + uneval(config));
            let user = User.user;

            let options = {
                callback: this.callback,
                errorback: this.errorback,
            };

            if (config.folder) options.folder = config.folder;
            if (config.fotosize) {
                options.fotosize= config.fotosize;
            } else {
                options.fotosize= 100000;
            }

            document.getElementById('hScreenshot-statusIcon').setAttribute('loading', 'true');

            if (!data) {
                Capture[method](true, function(data) {
                    user.uploadData(data, options);
                    finish();
                });
            } else {
                // rect
                user.uploadData(data, options);
                finish();
            }
        } else {
            finish();
        }
    },

    configDialog: function() {
        let config = {};
        window.openDialog(
            'chrome://hatenascreenshot/content/uploadConfig.xul',
            'アップロードの設定',
            'chrome,modal,resizable=yes,centerscreen',
            config
        ).focus();
        return config;
    },

    callback: function(res) {
        let m;
        p('upload success: ' + res.responseText);
        document.getElementById('hScreenshot-statusIcon').removeAttribute('loading');
        if (m = res.responseText.match(/:(\d{14})/)) {
            let timestamp = m[1];
            let permalink = User.user.getPermalink(timestamp) + '?ref=hatena-screenshot';
            setTimeout(function() {
                // タイミングによって fotolife の slave に反映されてないため、ちょっと間をおく
                p('open link: ' + permalink);
                openUILinkIn(permalink, 'tab');
            }, 100);
        }
    },

    errorback: function(res) {
        document.getElementById('hScreenshot-statusIcon').removeAttribute('loading');
        window.alert(convertStringEncoding('フォトライフへののアップロードに失敗しました'));
    },
});

Manager.Copy = extend({}, Manager.Base, false);
extend(Manager.Copy, {
    capture: function(method, finish) {
        p('copy capture: ' + method);
        Capture[method](false, function(data) {
            if (data) {
                ExCanvas.prototype.dataURItoClipboard(data);
            }
            finish();
        });
    },
});

Manager.Base64 = extend({}, Manager.Base, false);
extend(Manager.Base64, {
    capture: function(method, finish) {
        p('copy capture: ' + method);
        Capture[method](false, function(data) {
            if (data) {
                openUILinkIn(data, 'tab');
            }
            finish();
        });
    },
});

Manager.Save = extend({}, Manager.Base);
extend(Manager.Save, {
    capture: function(method, finish) {
        p('save capture: ' + method);
        Capture[method](false, function(data) {
            if (data) {
                let uri = IOService.newURI(data, null, null);
                let filePicker = Cc['@mozilla.org/filepicker;1'].createInstance(Ci.nsIFilePicker);
                filePicker.init(window, UIEncodeText('ファイルに保存'), filePicker.modeSave);
                filePicker.appendFilters(filePicker.filterImages);
                // filePicker.appendFilters(UIEncodeText('png 画像ファイル'), "*.png;");
                filePicker.defaultString = (window.content.document.title || 'screenshot') + '.png';
                if ((filePicker.show() == filePicker.returnCancel) || !filePicker.file) return;

                let wbp = Cc['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
                  .createInstance(Ci.nsIWebBrowserPersist);
                wbp.saveURI(uri, null, null, null, null, filePicker.file);
            }
            finish();
        });
    },
});

<commit_msg>URL fix<commit_after>
const EXPORT = ['Manager'];

var Manager = {};
let PS = Cc["@mozilla.org/embedcomp/prompt-service;1"].
         getService(Ci.nsIPromptService);

Manager.sketch = {
    sketches: [],
    hasSketch: function(sid) {
        if (!sid) return false;
        let sketches = this.sketches;
        for (let i = 0;  i < sketches.length; i++) {
            if (sketches[i].sid == sid) {
                return sketches[i];
            }
        }
        return false;
    },
    removeSketch: function(sid) {
        if (!sid) return false;
        let sketches = this.sketches;
        for (let i = 0;  i < sketches.length; i++) {
            if (sketches[i].sid == sid) {
                sketches.splice(i, 1);
                return true;
            }
        }
        return false;
    },
    addSketch: function(sketch) {
        if (!this.hasSketch(sketch.sid)) {
            this.sketches.push(sketch);
            return true;
        } else {
            return false;
        }
    },
    getSketckById: function(sid) {
        if (!sid) return;
        return this.hasSketch(sid);
    },
};

Manager.draw = function() {
    let win = getTopWin().content;
    if (!win || !win.document) return;

    p('draw!: sid: '  + win.__sketch_switch_sid__);
    let eventType = 'ShowSketch';
    let sketch;
    if (sketch = Manager.sketch.getSketckById(win.__sketch_switch_sid__)) {
        p('has sketch!');
        //
    } else {
        let options = {};
        if (!Prefs.screenshot.drawingHardMode) {
            options.buttons = ['Close', 'RedPen', 'BlackPen', 'Eraser', 'Clear'];
            options.noCreatePalette = true;
        }
        sketch = new SketchSwitch(win, options);
        Manager.sketch.addSketch(sketch);
        win.__sketch_switch_sid__ = sketch.sid;
        var unloader = function(event) {
            p('remove sketch obj: ' + Manager.sketch.removeSketch(win.__sketch_switch_sid__));
            sketch.destroy();
            win.removeEventListener('unload', unloader, false);
        };
        win.addEventListener('unload', unloader, false);
    }
    sketch.hideMenuMoving = Prefs.screenshot.get('hideMenuMoving');
    sketch.show();
    // var random = Math.random().toString().slice(2);
};

Manager.showPopup = function(event) {
    if (event.ctrlKey) {
        return Manager.draw();
    }
    let icon = document.getElementById('hScreenshot-statusIcon');
    let menu = document.getElementById('hScreenshot-menu-popup');
    menu = menu.cloneNode(true);
    icon.parentNode.appendChild(menu);
    menu.openPopup(icon, 'before_end', 0, 0, false, true);
};

Manager.Base = {
    createFinish: function() {
        let sketch;
        if (window.content &&
            (sketch = Manager.sketch.getSketckById(window.content.__sketch_switch_sid__))) {
            if (sketch.shownMenu) {
                sketch.hideMenu();

                return function() {
                    sketch.showMenu();
                    p('capture finish (show menu)');
                }
            }
        }
        return function() {
            p('capture finish');
        };
    },
    all: function() {
        this.capture('all', this.createFinish());
    },
    rect: function() {
        this.capture('rect', this.createFinish());
    },
    inner: function() {
        this.capture('inner', this.createFinish());
    }
};

Manager.Upload = extend({}, Manager.Base);
extend(Manager.Upload, {
    capture: function(method, finish) {
        p('upload capture: ' + method);
        // method: all, rect, inner
        if (!User.user) {
            let PS = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
            if (PS.confirm(window.top, convertStringEncoding('はてなスクリーンショット'), convertStringEncoding('フォトライフにアップロードするには、はてなへのログインが必要です。'))) {
                openUILinkIn("https://www.hatena.ne.jp/login?location=http%3A%2F%2Fwww.hatena.ne.jp%2Ftool%2Ffirefox%23HatenaScreenshot&ref=hatena-screenshot", 'tab');
            }
            finish();
            return;
        }

        if (method == 'rect') {
            let self = this;
            Capture.rect(true, function(data) {
                self._capture(method, data, finish);
            });
        } else {
            this._capture(method, null, finish);
        }
    },

    _capture: function(method, data, finish) {
        let config = this.configDialog();
        if (config.accept) {
            p('capture accept (config):' + uneval(config));
            let user = User.user;

            let options = {
                callback: this.callback,
                errorback: this.errorback,
            };

            if (config.folder) options.folder = config.folder;
            if (config.fotosize) {
                options.fotosize= config.fotosize;
            } else {
                options.fotosize= 100000;
            }

            document.getElementById('hScreenshot-statusIcon').setAttribute('loading', 'true');

            if (!data) {
                Capture[method](true, function(data) {
                    user.uploadData(data, options);
                    finish();
                });
            } else {
                // rect
                user.uploadData(data, options);
                finish();
            }
        } else {
            finish();
        }
    },

    configDialog: function() {
        let config = {};
        window.openDialog(
            'chrome://hatenascreenshot/content/uploadConfig.xul',
            'アップロードの設定',
            'chrome,modal,resizable=yes,centerscreen',
            config
        ).focus();
        return config;
    },

    callback: function(res) {
        let m;
        p('upload success: ' + res.responseText);
        document.getElementById('hScreenshot-statusIcon').removeAttribute('loading');
        if (m = res.responseText.match(/:(\d{14})/)) {
            let timestamp = m[1];
            let permalink = User.user.getPermalink(timestamp) + '?ref=hatena-screenshot';
            setTimeout(function() {
                // タイミングによって fotolife の slave に反映されてないため、ちょっと間をおく
                p('open link: ' + permalink);
                openUILinkIn(permalink, 'tab');
            }, 100);
        }
    },

    errorback: function(res) {
        document.getElementById('hScreenshot-statusIcon').removeAttribute('loading');
        window.alert(convertStringEncoding('フォトライフへののアップロードに失敗しました'));
    },
});

Manager.Copy = extend({}, Manager.Base, false);
extend(Manager.Copy, {
    capture: function(method, finish) {
        p('copy capture: ' + method);
        Capture[method](false, function(data) {
            if (data) {
                ExCanvas.prototype.dataURItoClipboard(data);
            }
            finish();
        });
    },
});

Manager.Base64 = extend({}, Manager.Base, false);
extend(Manager.Base64, {
    capture: function(method, finish) {
        p('copy capture: ' + method);
        Capture[method](false, function(data) {
            if (data) {
                openUILinkIn(data, 'tab');
            }
            finish();
        });
    },
});

Manager.Save = extend({}, Manager.Base);
extend(Manager.Save, {
    capture: function(method, finish) {
        p('save capture: ' + method);
        Capture[method](false, function(data) {
            if (data) {
                let uri = IOService.newURI(data, null, null);
                let filePicker = Cc['@mozilla.org/filepicker;1'].createInstance(Ci.nsIFilePicker);
                filePicker.init(window, UIEncodeText('ファイルに保存'), filePicker.modeSave);
                filePicker.appendFilters(filePicker.filterImages);
                // filePicker.appendFilters(UIEncodeText('png 画像ファイル'), "*.png;");
                filePicker.defaultString = (window.content.document.title || 'screenshot') + '.png';
                if ((filePicker.show() == filePicker.returnCancel) || !filePicker.file) return;

                let wbp = Cc['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
                  .createInstance(Ci.nsIWebBrowserPersist);
                wbp.saveURI(uri, null, null, null, null, filePicker.file);
            }
            finish();
        });
    },
});

<|endoftext|>


<commit_before>const Lang   = imports.lang;
const Main   = imports.ui.main;
const UPower = imports.ui.status.power.UPower;

// Main extension API
function init() {
};
function enable() {
    battery.bind().update();
};
function disable() {
    battery.unbind().show();
};

// Namespace for extension logic
let battery = {
    // Watcher ID to disable listening
    watching: null,

    // Start listen to battery status changes
    bind: function () {
        this.getBattery(function (proxy) {
            let update = Lang.bind(this, this.update);
            this.watching = proxy.connect('g-properties-changed', update);
        });
        return this;
    },

    // Stop listen to battery status changes
    unbind: function () {
        this.getBattery(function (proxy) {
            proxy.disconnect(this.watching);
        });
        return this;
    },

    // Show battery icon in status area
    show: function () {
        this.getBattery(function (proxy, icon) {
            icon.show();
        });
        return this;
    },

    // Hide battery icon in status area
    hide: function () {
        this.getBattery(function (proxy, icon) {
            icon.hide();
        });
        return this;
    },

    // Check current battery state and hide or show icon
    update: function () {
        this.getDevice(function (device) {
            if ( device.state == UPower.DeviceState.FULLY_CHARGED ) {
                this.hide();
            } else {
                this.show();
            }
        });
        return this;
    },

    // Execute `callback` on every battery device
    getDevice: function (callback) {
        this.getBattery(function (proxy) {
            let devices = proxy.GetDevicesSync()[0];

            for ( let i = 0; i < devices.length; i++ ) {
                let device = {
                    id:      devices[i][0],
                    type:    devices[i][1],
                    icon:    devices[i][2],
                    percent: devices[i][3],
                    state:   devices[i][4],
                    time:    devices[i][5]
                };

                if ( device.type == UPower.DeviceKind.BATTERY ) {
                    callback.call(this, device);
                    break;
                }
            }
        });
    },

    // Run `callback`, only if battery is avaiable. First argument will be icon,
    // second will be it proxy.
    getBattery: function (callback) {
        let menu = Main.panel.statusArea.aggregateMenu;
        if ( menu && menu._power ) {
            callback.call(this, menu._power._proxy, menu._power.indicators);
        }
    }
};
<commit_msg>Use async method to get devices<commit_after>const Lang   = imports.lang;
const Main   = imports.ui.main;
const UPower = imports.ui.status.power.UPower;

// Main extension API
function init() {
};
function enable() {
    battery.bind().update();
};
function disable() {
    battery.unbind().show();
};

// Namespace for extension logic
let battery = {
    // Watcher ID to disable listening
    watching: null,

    // Start listen to battery status changes
    bind: function () {
        this.getBattery(function (proxy) {
            let update = Lang.bind(this, this.update);
            this.watching = proxy.connect('g-properties-changed', update);
        });
        return this;
    },

    // Stop listen to battery status changes
    unbind: function () {
        this.getBattery(function (proxy) {
            proxy.disconnect(this.watching);
        });
        return this;
    },

    // Show battery icon in status area
    show: function () {
        this.getBattery(function (proxy, icon) {
            icon.show();
        });
        return this;
    },

    // Hide battery icon in status area
    hide: function () {
        this.getBattery(function (proxy, icon) {
            icon.hide();
        });
        return this;
    },

    // Check current battery state and hide or show icon
    update: function () {
        this.getDevice(function (device) {
            if ( device.state == UPower.DeviceState.FULLY_CHARGED ) {
                this.hide();
            } else {
                this.show();
            }
        });
        return this;
    },

    // Execute `callback` on every battery device
    getDevice: function (callback) {
        this.getBattery(function (proxy) {
            proxy.GetDevicesRemote(Lang.bind(this, function(result, error) {
                if ( error ) {
                    return;
                }

                let devices = result[0];
                for ( let i = 0; i < devices.length; i++ ) {
                    let device = {
                        id:      devices[i][0],
                        type:    devices[i][1],
                        icon:    devices[i][2],
                        percent: devices[i][3],
                        state:   devices[i][4],
                        time:    devices[i][5]
                    };

                    if ( device.type == UPower.DeviceKind.BATTERY ) {
                        callback.call(this, device);
                        break;
                    }
                }
            }));
        });
    },

    // Run `callback`, only if battery is avaiable. First argument will be icon,
    // second will be it proxy.
    getBattery: function (callback) {
        let menu = Main.panel.statusArea.aggregateMenu;
        if ( menu && menu._power ) {
            callback.call(this, menu._power._proxy, menu._power.indicators);
        }
    }
};
<|endoftext|>


<commit_before>/** @module deliteful/StarRating */
define([
	"requirejs-dplugins/has",
	"dpointer/events",
	"delite/keys",
	"requirejs-dplugins/jquery!attributes/classes",
	"delite/register",
	"delite/FormValueWidget",
	"requirejs-dplugins/has!bidi?./StarRating/bidi/StarRating",
	"requirejs-dplugins/i18n!./StarRating/nls/StarRating",
	"delite/uacss", // to use dedicated CSS styles in IE9
	"delite/theme!./StarRating/themes/{{theme}}/StarRating.css",
	"requirejs-dplugins/has!bidi?delite/theme!./StarRating/themes/{{theme}}/StarRating_rtl.css"
], function (has, pointer, keys, $,
			register, FormValueWidget, BidiStarRating, messages) {

	/**
	 * A widget that displays a rating, usually with stars, and that allows setting a different rating value
	 * by touching the stars.
	 * Its custom element tag is `d-star-rating`.
	 *
	 * @class module:deliteful/StarRating
	 * @augments delite/FormValueWidget
	 */
	var StarRating = register.dcl([FormValueWidget], /** @lends module:deliteful/StarRating# */ {
		/**
		 * The name of the CSS class of this widget.
		 * @member {string}
		 * @default "d-star-rating"
		 */
		baseClass: "d-star-rating",

		/**
		 * The maximum rating, that is also the number of stars to show.
		 * @member {number}
		 * @default 5
		 */
		max: 5,

		/**
		 * The current value of the Rating.
		 * @member {number}
		 * @default 0
		 */
		value: 0,

		/**
		 * Indicates whether the user is allowed to edit half values (0.5, 1.5, ...) or not.
		 * Ignored if readOnly is set to false.
		 * @member {boolean}
		 * @default false
		 */
		editHalfValues: false,

		/**
		 * Indicates whether the user is allowed to set the value to zero or not.
		 * @member {boolean}
		 * @default true
		 */
		allowZero: true,

		/* internal properties */

		/*=====
		_hoveredValue: null,
		_startHandles: null,
		_keyDownHandle: null,
		=====*/
		_hovering: false,
		_otherEventsHandles: [],
		_incrementKeyCodes: [keys.RIGHT_ARROW, keys.UP_ARROW, keys.NUMPAD_PLUS], // keys to press to increment value
		_decrementKeyCodes: [keys.LEFT_ARROW, keys.DOWN_ARROW, keys.NUMPAD_MINUS], // keys to press to decrement value

		render: function () {
			this.focusNode = this.ownerDocument.createElement("div");
			this.appendChild(this.focusNode);
			pointer.setTouchAction(this, "none");
			// init WAI-ARIA attributes
			this.focusNode.setAttribute("role", "slider");
			this.focusNode.setAttribute("aria-valuemin", 0);
		},

		createdCallback: register.after(function () {
			var inputs = this.getElementsByTagName("INPUT");
			if (inputs.length) {
				this.valueNode = inputs[0];
				if (!isNaN(parseFloat(this.valueNode.value))) {
					this.value = this.valueNode.value;
				}
				this.valueNode.style.display = "none";
			} else {
				this.valueNode = this.ownerDocument.createElement("input");
				this.valueNode.style.display = "none";
				this.appendChild(this.valueNode);
			}
			this.notifyCurrentValue("disabled", "max", "value", "readOnly", "allowZero");
		}),

		/* jshint maxcomplexity: 13 */
		refreshRendering: function (props) {
			if ("disabled" in props) {
				$(this).toggleClass(this.baseClass + "-disabled", this.disabled);
			}
			if ("max" in props) {
				this.focusNode.setAttribute("aria-valuemax", this.max);
			}
			if ("max" in props || "value" in props) {
				this._refreshStarsRendering();
			}
			if ("value" in props) {
				this.focusNode.setAttribute("aria-valuenow", this.value);
				this.focusNode.setAttribute("aria-valuetext",
						messages["aria-valuetext"].replace("${value}", this.value));
				this.valueNode.value = this.value;
			}
			if ("readOnly" in props || "disabled" in props) {
				this._refreshEditionEventHandlers();
			}
			if ("readOnly" in props || "disabled" in props || "allowZero" in props) {
				this._updateZeroArea();
			}
		},
		/* jshint maxcomplexity: 10 */

		_refreshStarsRendering: function () {
			var createChildren = this.focusNode.children.length - 1 !== 2 * this.max;
			if (createChildren) {
				this.focusNode.innerHTML = "";
			}
			this._updateStars(this.value, createChildren);
		},

		_refreshEditionEventHandlers: function () {
			var passive = this.disabled || this.readOnly;
			if (!passive && !this._keyDownHandle) {
				this._keyDownHandle = this.on("keydown", this._keyDownHandler.bind(this));
			} else if (passive && this._keyDownHandle) {
				this._keyDownHandle.remove();
				this._keyDownHandle = null;
			}
			if (!passive && !this._startHandles) {
				this._startHandles = [this.on("pointerover", this._pointerOverHandler.bind(this)),
									  this.on("pointerdown", this._wireHandlers.bind(this))];
			} else if (passive && this._startHandles) {
				while (this._startHandles.length) {
					this._startHandles.pop().remove();
				}
				this._startHandles = null;
			}
		},

		_removeEventsHandlers: function () {
			while (this._otherEventsHandles.length) {
				this._otherEventsHandles.pop().remove();
			}
		},

		_wireHandlers: function () {
			if (!this._otherEventsHandles.length) {
				this._otherEventsHandles.push(this.on("pointerup", this._pointerUpHandler.bind(this)));
				this._otherEventsHandles.push(this.on("pointerleave", this._pointerLeaveHandler.bind(this)));
				this._otherEventsHandles.push(this.on("pointercancel", this._pointerLeaveHandler.bind(this)));
			}
		},

		_pointerOverHandler: function (/*Event*/ event) {
			this._wireHandlers();
			if (!this._hovering && event.pointerType === "mouse") {
				this._hovering = true;
				$(this).addClass(this.baseClass + "-hovered");
			}
			var newValue = event.target.value;
			if (newValue !== undefined) {
				if (this._hovering) {
					if (newValue !== this._hoveredValue) {
						$(this).addClass(this.baseClass + "-hovered");
						this._updateStars(newValue, false);
						this._hoveredValue = newValue;
					}
				} else {
					// Set the previous value here, as this handler is called before _onFocus
					this._previousOnChangeValue = this.value;
					this.handleOnChange(newValue);
				}
			}
		},

		_pointerUpHandler: function (/*Event*/ event) {
			var value = event.target.value;
			if (value !== undefined) {
				this.handleOnChange(value);
			}
			if (!this._hovering) {
				this._removeEventsHandlers();
			} else {
				$(this).removeClass(this.baseClass + "-hovered");
			}
		},

		_pointerLeaveHandler: function () {
			if (this._hovering) {
				this._hovering = false;
				this._hoveredValue = null;
				$(this).removeClass(this.baseClass + "-hovered");
				this._updateStars(this.value, false);
			}
			this._removeEventsHandlers();
		},

		_keyDownHandler: function () {
			if (this._incrementKeyCodes.indexOf(event.keyCode) !== -1) {
				event.preventDefault();
				this._incrementValue();
			} else if (this._decrementKeyCodes.indexOf(event.keyCode) !== -1) {
				event.preventDefault();
				this._decrementValue();
			}
		},

		_incrementValue: function () {
			if (this.value < this.max) {
				this.value = this.value + (this.editHalfValues ? 0.5 : 1);
			}
		},

		_decrementValue: function () {
			if (this.value > (this.allowZero ? 0 : (this.editHalfValues ? 0.5 : 1))) {
				this.value = this.value - (this.editHalfValues ? 0.5 : 1);
			}
		},

		_updateStars: function (/*Number*/value, /*Boolean*/create) {
			var stars = this.focusNode.querySelectorAll("div");
			if (create) {
				this._zeroSettingArea = this.ownerDocument.createElement("div");
				this._zeroSettingArea.className = this.baseClass + "-zero";
				this._zeroSettingArea.value = 0;
				this.focusNode.appendChild(this._zeroSettingArea);
				this._updateZeroArea();
			}
			for (var i = 0; i < 2 * this.max; i++) {
				var starClass = this.baseClass + (i % 2 ? "-end " : "-start ");
				if ((i + 1) * 0.5 <= value) {
					starClass += this.baseClass + "-full";
				} else {
					starClass += this.baseClass + "-empty";
				}
				if (create) {
					var parent = this.ownerDocument.createElement("div");
					parent.value = this.editHalfValues ? (i + 1) / 2 : Math.ceil((i + 1) / 2);
					this.focusNode.appendChild(parent);
				} else {
					parent = stars[i + 1];
				}
				parent.className = this.baseClass + "-star-icon " + starClass;
			}
		},

		_updateZeroArea: function () {
			if (this.readOnly || !this.allowZero) {
				$(this._zeroSettingArea).addClass("d-hidden");
				delete this.focusNode.value;
			} else {
				$(this._zeroSettingArea).removeClass("d-hidden");
				// _zeroSettingArea might not fill the whole widget height
				// so pointer events can land in the underlying focus node
				this.focusNode.value = 0;
			}
		}
	});

	return register("d-star-rating",
			has("bidi") ? [HTMLElement, StarRating, BidiStarRating] : [HTMLElement, StarRating]);
});
<commit_msg>StarRating should not import uscss, it is not being used. fixes #461.<commit_after>/** @module deliteful/StarRating */
define([
	"requirejs-dplugins/has",
	"dpointer/events",
	"delite/keys",
	"requirejs-dplugins/jquery!attributes/classes",
	"delite/register",
	"delite/FormValueWidget",
	"requirejs-dplugins/has!bidi?./StarRating/bidi/StarRating",
	"requirejs-dplugins/i18n!./StarRating/nls/StarRating",
	"delite/theme!./StarRating/themes/{{theme}}/StarRating.css",
	"requirejs-dplugins/has!bidi?delite/theme!./StarRating/themes/{{theme}}/StarRating_rtl.css"
], function (has, pointer, keys, $,
			register, FormValueWidget, BidiStarRating, messages) {

	/**
	 * A widget that displays a rating, usually with stars, and that allows setting a different rating value
	 * by touching the stars.
	 * Its custom element tag is `d-star-rating`.
	 *
	 * @class module:deliteful/StarRating
	 * @augments delite/FormValueWidget
	 */
	var StarRating = register.dcl([FormValueWidget], /** @lends module:deliteful/StarRating# */ {
		/**
		 * The name of the CSS class of this widget.
		 * @member {string}
		 * @default "d-star-rating"
		 */
		baseClass: "d-star-rating",

		/**
		 * The maximum rating, that is also the number of stars to show.
		 * @member {number}
		 * @default 5
		 */
		max: 5,

		/**
		 * The current value of the Rating.
		 * @member {number}
		 * @default 0
		 */
		value: 0,

		/**
		 * Indicates whether the user is allowed to edit half values (0.5, 1.5, ...) or not.
		 * Ignored if readOnly is set to false.
		 * @member {boolean}
		 * @default false
		 */
		editHalfValues: false,

		/**
		 * Indicates whether the user is allowed to set the value to zero or not.
		 * @member {boolean}
		 * @default true
		 */
		allowZero: true,

		/* internal properties */

		/*=====
		_hoveredValue: null,
		_startHandles: null,
		_keyDownHandle: null,
		=====*/
		_hovering: false,
		_otherEventsHandles: [],
		_incrementKeyCodes: [keys.RIGHT_ARROW, keys.UP_ARROW, keys.NUMPAD_PLUS], // keys to press to increment value
		_decrementKeyCodes: [keys.LEFT_ARROW, keys.DOWN_ARROW, keys.NUMPAD_MINUS], // keys to press to decrement value

		render: function () {
			this.focusNode = this.ownerDocument.createElement("div");
			this.appendChild(this.focusNode);
			pointer.setTouchAction(this, "none");
			// init WAI-ARIA attributes
			this.focusNode.setAttribute("role", "slider");
			this.focusNode.setAttribute("aria-valuemin", 0);
		},

		createdCallback: register.after(function () {
			var inputs = this.getElementsByTagName("INPUT");
			if (inputs.length) {
				this.valueNode = inputs[0];
				if (!isNaN(parseFloat(this.valueNode.value))) {
					this.value = this.valueNode.value;
				}
				this.valueNode.style.display = "none";
			} else {
				this.valueNode = this.ownerDocument.createElement("input");
				this.valueNode.style.display = "none";
				this.appendChild(this.valueNode);
			}
			this.notifyCurrentValue("disabled", "max", "value", "readOnly", "allowZero");
		}),

		/* jshint maxcomplexity: 13 */
		refreshRendering: function (props) {
			if ("disabled" in props) {
				$(this).toggleClass(this.baseClass + "-disabled", this.disabled);
			}
			if ("max" in props) {
				this.focusNode.setAttribute("aria-valuemax", this.max);
			}
			if ("max" in props || "value" in props) {
				this._refreshStarsRendering();
			}
			if ("value" in props) {
				this.focusNode.setAttribute("aria-valuenow", this.value);
				this.focusNode.setAttribute("aria-valuetext",
						messages["aria-valuetext"].replace("${value}", this.value));
				this.valueNode.value = this.value;
			}
			if ("readOnly" in props || "disabled" in props) {
				this._refreshEditionEventHandlers();
			}
			if ("readOnly" in props || "disabled" in props || "allowZero" in props) {
				this._updateZeroArea();
			}
		},
		/* jshint maxcomplexity: 10 */

		_refreshStarsRendering: function () {
			var createChildren = this.focusNode.children.length - 1 !== 2 * this.max;
			if (createChildren) {
				this.focusNode.innerHTML = "";
			}
			this._updateStars(this.value, createChildren);
		},

		_refreshEditionEventHandlers: function () {
			var passive = this.disabled || this.readOnly;
			if (!passive && !this._keyDownHandle) {
				this._keyDownHandle = this.on("keydown", this._keyDownHandler.bind(this));
			} else if (passive && this._keyDownHandle) {
				this._keyDownHandle.remove();
				this._keyDownHandle = null;
			}
			if (!passive && !this._startHandles) {
				this._startHandles = [this.on("pointerover", this._pointerOverHandler.bind(this)),
									  this.on("pointerdown", this._wireHandlers.bind(this))];
			} else if (passive && this._startHandles) {
				while (this._startHandles.length) {
					this._startHandles.pop().remove();
				}
				this._startHandles = null;
			}
		},

		_removeEventsHandlers: function () {
			while (this._otherEventsHandles.length) {
				this._otherEventsHandles.pop().remove();
			}
		},

		_wireHandlers: function () {
			if (!this._otherEventsHandles.length) {
				this._otherEventsHandles.push(this.on("pointerup", this._pointerUpHandler.bind(this)));
				this._otherEventsHandles.push(this.on("pointerleave", this._pointerLeaveHandler.bind(this)));
				this._otherEventsHandles.push(this.on("pointercancel", this._pointerLeaveHandler.bind(this)));
			}
		},

		_pointerOverHandler: function (/*Event*/ event) {
			this._wireHandlers();
			if (!this._hovering && event.pointerType === "mouse") {
				this._hovering = true;
				$(this).addClass(this.baseClass + "-hovered");
			}
			var newValue = event.target.value;
			if (newValue !== undefined) {
				if (this._hovering) {
					if (newValue !== this._hoveredValue) {
						$(this).addClass(this.baseClass + "-hovered");
						this._updateStars(newValue, false);
						this._hoveredValue = newValue;
					}
				} else {
					// Set the previous value here, as this handler is called before _onFocus
					this._previousOnChangeValue = this.value;
					this.handleOnChange(newValue);
				}
			}
		},

		_pointerUpHandler: function (/*Event*/ event) {
			var value = event.target.value;
			if (value !== undefined) {
				this.handleOnChange(value);
			}
			if (!this._hovering) {
				this._removeEventsHandlers();
			} else {
				$(this).removeClass(this.baseClass + "-hovered");
			}
		},

		_pointerLeaveHandler: function () {
			if (this._hovering) {
				this._hovering = false;
				this._hoveredValue = null;
				$(this).removeClass(this.baseClass + "-hovered");
				this._updateStars(this.value, false);
			}
			this._removeEventsHandlers();
		},

		_keyDownHandler: function () {
			if (this._incrementKeyCodes.indexOf(event.keyCode) !== -1) {
				event.preventDefault();
				this._incrementValue();
			} else if (this._decrementKeyCodes.indexOf(event.keyCode) !== -1) {
				event.preventDefault();
				this._decrementValue();
			}
		},

		_incrementValue: function () {
			if (this.value < this.max) {
				this.value = this.value + (this.editHalfValues ? 0.5 : 1);
			}
		},

		_decrementValue: function () {
			if (this.value > (this.allowZero ? 0 : (this.editHalfValues ? 0.5 : 1))) {
				this.value = this.value - (this.editHalfValues ? 0.5 : 1);
			}
		},

		_updateStars: function (/*Number*/value, /*Boolean*/create) {
			var stars = this.focusNode.querySelectorAll("div");
			if (create) {
				this._zeroSettingArea = this.ownerDocument.createElement("div");
				this._zeroSettingArea.className = this.baseClass + "-zero";
				this._zeroSettingArea.value = 0;
				this.focusNode.appendChild(this._zeroSettingArea);
				this._updateZeroArea();
			}
			for (var i = 0; i < 2 * this.max; i++) {
				var starClass = this.baseClass + (i % 2 ? "-end " : "-start ");
				if ((i + 1) * 0.5 <= value) {
					starClass += this.baseClass + "-full";
				} else {
					starClass += this.baseClass + "-empty";
				}
				if (create) {
					var parent = this.ownerDocument.createElement("div");
					parent.value = this.editHalfValues ? (i + 1) / 2 : Math.ceil((i + 1) / 2);
					this.focusNode.appendChild(parent);
				} else {
					parent = stars[i + 1];
				}
				parent.className = this.baseClass + "-star-icon " + starClass;
			}
		},

		_updateZeroArea: function () {
			if (this.readOnly || !this.allowZero) {
				$(this._zeroSettingArea).addClass("d-hidden");
				delete this.focusNode.value;
			} else {
				$(this._zeroSettingArea).removeClass("d-hidden");
				// _zeroSettingArea might not fill the whole widget height
				// so pointer events can land in the underlying focus node
				this.focusNode.value = 0;
			}
		}
	});

	return register("d-star-rating",
			has("bidi") ? [HTMLElement, StarRating, BidiStarRating] : [HTMLElement, StarRating]);
});
<|endoftext|>


<commit_before>var self = module.exports = {

	init: function() {

		if(!CivicSeed.initialized) {

			// self.registerModulesAndGlobals();
			window.$HTML = $('html');
			window.$BODY = $(document.body);
			window.$CONTAINER = $('#container');

			self.setupRouter();

			var $account = require('/account');
			$account.accountHandlers();

			CivicSeed.initialized = true;

		}

	},

	setupRouter: function() {

		var $app;

		Davis(function() {

			$app = this;

			require('/routes-middleware.js').loadMiddleware($app);
			require('/routes-main').loadRoutes($app);
			require('/routes-account').loadRoutes($app);
			require('/routes-admin').loadRoutes($app);
			require('/routes-profile').loadRoutes($app);
			// should always be last
			require('/routes-errors').loadRoutes($app);

			$app.configure(function(config) {
				// config.linkSelector = 'a.davis';
				// config.formSelector = 'form.davis';
				// config.throwErrors = true;
				// config.handleRouteNotFound = false;
				config.generateRequestOnPageLoad = true;
			});

			$app.start();

		});

		require('/routes-middleware.js').loadMiddleware($app);
		require('/routes-main').loadRoutes($app);
		require('/routes-account').loadRoutes($app);
		require('/routes-admin').loadRoutes($app);
		require('/routes-profile').loadRoutes($app);
		// should always be last
		require('/routes-errors').loadRoutes($app);

		// config.generateRequestOnPageLoad = true;

	}

};<commit_msg>Fixed mongo bug caused by double loading of routing assets.<commit_after>var self = module.exports = {

	init: function() {

		if(!CivicSeed.initialized) {

			// self.registerModulesAndGlobals();
			window.$HTML = $('html');
			window.$BODY = $(document.body);
			window.$CONTAINER = $('#container');

			self.setupRouter();

			var $account = require('/account');
			$account.accountHandlers();

			CivicSeed.initialized = true;

		}

	},

	setupRouter: function() {

		var $app;

		Davis(function() {

			$app = this;

			require('/routes-middleware.js').loadMiddleware($app);
			require('/routes-main').loadRoutes($app);
			require('/routes-account').loadRoutes($app);
			require('/routes-admin').loadRoutes($app);
			require('/routes-profile').loadRoutes($app);
			// should always be last
			require('/routes-errors').loadRoutes($app);

			$app.configure(function(config) {
				// config.linkSelector = 'a.davis';
				// config.formSelector = 'form.davis';
				// config.throwErrors = true;
				// config.handleRouteNotFound = false;
				config.generateRequestOnPageLoad = true;
			});

			$app.start();

		});

	}

};<|endoftext|>


<commit_before>import React from 'react';
import '../scss/_recipeContainer.scss';

import RecipeEntry from '../../client/components/RecipeEntry.js';

const RecipeContainer = (props) => {
  let childRecipes;
  if (props.recipes) {
    childRecipes =
No history available for this recipe.
;
  } else {
    childRecipes = props.recipes.map((recipe) => <RecipeEntry recipe={recipe} />);
  }
  return (

{props.type}

      {childRecipes}

  );
};

export default RecipeContainer;
<commit_msg>Fix empty state rendering<commit_after>import React from 'react';
import '../scss/_recipeContainer.scss';

import RecipeEntry from '../../client/components/RecipeEntry.js';

const RecipeContainer = (props) => {
  let childRecipes;
  if (!props.recipes) {
    childRecipes =
No history available for this recipe yet.
;
  } else {
    childRecipes = props.recipes.map((recipe) => <RecipeEntry recipe={recipe} />);
  }
  return (

{props.type}

      {childRecipes}

  );
};

export default RecipeContainer;
<|endoftext|>


<commit_before>angular.module('myApp')
.controller('exampleController', function ($scope, $rootScope, $timeout, $window) {

  angular.element($window).bind('resize', function(){
    setMarkerWidth();
  });

  $scope.textChanged = function(event) {

    removeInvalidContent();

    checkSentencesComplexity();

    if ($scope.text) {
      calculateData($scope.text);

      fleschKincaidEase();
    }
  };

  var setMarkerWidth = function() {
    // Set marker width based on text width
    document.getElementById("text").style.width = document.getElementById("marker").offsetWidth + "px";
    document.getElementById("marker").style.height = document.getElementById("text").offsetHeight + "px";
  };

  var removeInvalidContent = function() {

    // Remove multiple spaces
    //$scope.text = $scope.text.replace(/  +/g, ' ');
    // TODO: Breaks when "       Lorem"

    // Remove tags
    $scope.text = $scope.text.replace(/(<([^>]+)>)/ig, '');
    // TODO: Breaks when "<aaaaaaaaaaa"

  };

  var checkSentencesComplexity = function() {
    $scope.highlight = "";

    var SENT_REGEX = /[^\r\n.!?]+(:?(:?\r\n|[\r\n]|[.!?])+|$)/gi;
    var sentences = $scope.text.match(SENT_REGEX);

    $scope.hardSentencesCount = 0;
    $scope.veryHardSentencesCount = 0;

    if (sentences) {
      for (var i = 0; i < sentences.length; i++) {
        if (sentences[i].length >= 140) {
          $scope.veryHardSentencesCount += 1;
          $scope.highlight += "" + sentences[i] + "";
        } else if (sentences[i].length >= 100) {
          $scope.hardSentencesCount += 1;
          $scope.highlight += "" + sentences[i] + "";
        } else {
          $scope.highlight += sentences[i];
        }
    	}
    }

    setMarkerWidth();
  };

  var calculateData = function(text) {
    $scope.wordsCount = 0;
    $scope.syllablesCount = 0;
    $scope.sentencesCount = 0;

    // Count sentences
    var SENT_REGEX = /[^\r\n.!?]+(:?(:?\r\n|[\r\n]|[.!?])+|$)/gi;
    $scope.sentencesCount = text.match(SENT_REGEX).length;

    // Count words
    var words = text.replace(/[^\w\s]/ig, "").split(" ");
    $scope.wordsCount = words.length;

    // Count syllables
    for (var i = 0; i < words.length; i++) {
  		$scope.syllablesCount += countSyllables(words[i].toLowerCase());
  	}
  };

  var countSyllables = function(word) {
    if(word.length <= 3) {
      return 1;
    }

    word = word.replace(/\d/gi, '');
    word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
    word = word.replace(/^y/, '');

    var result =  word.match(/[aeiouy]{1,2}/g);

    if (result) {
      return result.length;
    }

  	return 0;
  };

  var fleschKincaidEase = function() {
    $scope.readabilityIndex = 206.835 - 1.015 * ($scope.wordsCount / $scope.sentencesCount) - 84.6 * ($scope.syllablesCount / $scope.wordsCount);
  	// console.log("Flesch Kincaid Reading Ease: " + $scope.readabilityIndex);

    calculateLevel($scope.readabilityIndex);
  };

  var calculateLevel = function(index) {
    if (index < 25) {
      $scope.level = 'Muito difícil';
      $scope.grade = 'Ensino Superior';
  		// document.getElementById('navbar').style.background = '#CD5C5C';
  	} else if (index < 50) {
      $scope.level = 'Difícil';
      $scope.grade = 'Ensino Médio';
  		// document.getElementById('navbar').style.background = '#DB7093';
  	} else if (index < 75) {
      $scope.level = 'Fácil';
      $scope.grade = '5º ao 9º ano do Ensino Fundamental';
  		// document.getElementById('navbar').style.background = '#FFA500';
  	} else {
      $scope.level = 'Muito fácil';
      $scope.grade = '1º ao 4º ano do Ensino Fundamental';
  		// document.getElementById('navbar').style.background = '#66CDAA';
  	}
  };

  $scope.title = "Capitães da Areia";
  $scope.text = "A voz o chama. Uma voz que o alegra, que faz bater seu coração. Ajuda a mudar o destino de todos os pobres. Uma voz que atravessa a cidade, que parece vir dos atabaques que ressoam nas macumbas da religião ilegal dos negros. Uma voz que vem com o ruído dos bondes onde vão os condutores e motoneiros grevistas. Uma voz que vem do cais, do peito dos estivadores, de João de Adão, de seu pai morrendo num comício, dos marinheiros dos navios, dos saveiristas e dos canoeiros. Uma voz que vem do grupo que joga a luta da capoeira, que vem dos golpes que o Querido de Deus aplica. Uma voz que vem mesmo do Padre José Pedro, padre pobre de olhos espantados diante do destino terrível dos Capitães de Areia. Uma voz que vem das  lhas de santo do candomblé de Don'Aninha, na noite que a polícia levou Ogum. Voz que vem do Trapiche dos Capitães de Areia. Que vem do reformatório e do orfanato. Que vem do ódio do Sem-Pernas se atirando do elevador para não se entregar. Que vem no trem da Leste Brasileira, através do sertão, do grupo de Lampião pedindo justiça para os sertanejos. Que vem de Alberto, o estudante pedindo escolas e liberdade para a cultura. Que vem dos quadros de Professor, onde meninos esfarrapados lutam naquela exposição da rua Chile. Que vem de Boa-Vida e dos malandros da cidade, do bojo dos seus violões, dos sambas tristes que eles cantam. Uma voz que diz uma palavra bonita de solidariedade, de amizade: companheiros. Uma voz que convida para a festa da luta. Que é como um samba alegre de negro, como ressoar dos atabaques nas macumbas. Voz que vem da lembrança de Dora, valente lutadora. Voz que chama Pedro Bala. Como a voz de Deus chamava Pirulito, a voz do ódio o Sem-Pernas, como a voz dos sertanejos chamava Volta-Seca para o grupo de Lampião. Voz poderosa como nenhuma outra. Porque é uma voz que chama para lutar por todos, pelo destino de todos, sem exceção. Voz poderosa como nenhuma outra. Voz que atravessa a cidade e vem de todos os lados. Voz que traz com ela uma festa, que faz o inverno acabar lá fora e ser primavera. A primavera da luta. Voz que chama Pedro Bala, que o leva para a luta. Voz que vem de todos os peitos esfomeados da cidade, de todos os peitos explorados da cidade. Voz que traz o bem maior do mundo, bem que é igual ao sol, mesmo maior que o sol: a liberdade. A cidade no dia de primavera é deslumbradoramente bela. Uma voz de mulher canta a canção da Bahia. Cidade negra e velha, sinos de igreja, ruas calçadas de pedra. Canção da Bahia que uma mulher canta. Dentro de Pedro Bala uma voz o chama: voz que traz para a canção da Bahia, a canção da liberdade. Voz poderosa que o chama. Voz de toda a cidade pobre da Bahia, voz da liberdade. A revolução chama Pedro Bala.";

  checkSentencesComplexity();

});
<commit_msg>Fix for content example<commit_after>angular.module('myApp')
.controller('exampleController', function ($scope, $rootScope, $timeout, $window) {

  angular.element($window).bind('resize', function(){
    setMarkerWidth();
  });

  $scope.textChanged = function(event) {

    removeInvalidContent();

    checkSentencesComplexity();

    if ($scope.text) {
      calculateData($scope.text);

      fleschKincaidEase();
    }
  };

  var setMarkerWidth = function() {
    // Set marker width based on text width
    document.getElementById("text").style.width = document.getElementById("marker").offsetWidth + "px";
    document.getElementById("marker").style.height = document.getElementById("text").offsetHeight + "px";
  };

  var removeInvalidContent = function() {

    // Remove multiple spaces
    //$scope.text = $scope.text.replace(/  +/g, ' ');
    // TODO: Breaks when "       Lorem"

    // Remove tags
    $scope.text = $scope.text.replace(/(<([^>]+)>)/ig, '');
    // TODO: Breaks when "<aaaaaaaaaaa"

  };

  var checkSentencesComplexity = function() {
    $scope.highlight = "";

    var SENT_REGEX = /[^\r\n.!?]+(:?(:?\r\n|[\r\n]|[.!?])+|$)/gi;
    var sentences = $scope.text.match(SENT_REGEX);

    $scope.hardSentencesCount = 0;
    $scope.veryHardSentencesCount = 0;

    if (sentences) {
      for (var i = 0; i < sentences.length; i++) {
        if (sentences[i].length >= 140) {
          $scope.veryHardSentencesCount += 1;
          $scope.highlight += "" + sentences[i] + "";
        } else if (sentences[i].length >= 100) {
          $scope.hardSentencesCount += 1;
          $scope.highlight += "" + sentences[i] + "";
        } else {
          $scope.highlight += sentences[i];
        }
    	}
    }

    setMarkerWidth();
  };

  var calculateData = function(text) {
    $scope.wordsCount = 0;
    $scope.syllablesCount = 0;
    $scope.sentencesCount = 0;

    // Count sentences
    var SENT_REGEX = /[^\r\n.!?]+(:?(:?\r\n|[\r\n]|[.!?])+|$)/gi;
    $scope.sentencesCount = text.match(SENT_REGEX).length;

    // Count words
    var words = text.replace(/[^\w\s]/ig, "").split(" ");
    $scope.wordsCount = words.length;

    // Count syllables
    for (var i = 0; i < words.length; i++) {
  		$scope.syllablesCount += countSyllables(words[i].toLowerCase());
  	}
  };

  var countSyllables = function(word) {
    if(word.length <= 3) {
      return 1;
    }

    word = word.replace(/\d/gi, '');
    word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
    word = word.replace(/^y/, '');

    var result =  word.match(/[aeiouy]{1,2}/g);

    if (result) {
      return result.length;
    }

  	return 0;
  };

  var fleschKincaidEase = function() {
    $scope.readabilityIndex = 206.835 - 1.015 * ($scope.wordsCount / $scope.sentencesCount) - 84.6 * ($scope.syllablesCount / $scope.wordsCount);
  	// console.log("Flesch Kincaid Reading Ease: " + $scope.readabilityIndex);

    calculateLevel($scope.readabilityIndex);
  };

  var calculateLevel = function(index) {
    if (index < 25) {
      $scope.level = 'Muito difícil';
      $scope.grade = 'Ensino Superior';
  		// document.getElementById('navbar').style.background = '#CD5C5C';
  	} else if (index < 50) {
      $scope.level = 'Difícil';
      $scope.grade = 'Ensino Médio';
  		// document.getElementById('navbar').style.background = '#DB7093';
  	} else if (index < 75) {
      $scope.level = 'Fácil';
      $scope.grade = '5º ao 9º ano do Ensino Fundamental';
  		// document.getElementById('navbar').style.background = '#FFA500';
  	} else {
      $scope.level = 'Muito fácil';
      $scope.grade = '1º ao 4º ano do Ensino Fundamental';
  		// document.getElementById('navbar').style.background = '#66CDAA';
  	}
  };

  $scope.title = "Capitães da Areia";
  $scope.text = "A voz o chama. Uma voz que o alegra, que faz bater seu coração. Ajuda a mudar o destino de todos os pobres. Uma voz que atravessa a cidade, que parece vir dos atabaques que ressoam nas macumbas da religião ilegal dos negros. Uma voz que vem com o ruído dos bondes onde vão os condutores e motoneiros grevistas. Uma voz que vem do cais, do peito dos estivadores, de João de Adão, de seu pai morrendo num comício, dos marinheiros dos navios, dos saveiristas e dos canoeiros. Uma voz que vem do grupo que joga a luta da capoeira, que vem dos golpes que o Querido de Deus aplica. Uma voz que vem mesmo do Padre José Pedro, padre pobre de olhos espantados diante do destino terrível dos Capitães de Areia. Uma voz que vem das  lhas de santo do candomblé de Don'Aninha, na noite que a polícia levou Ogum. Voz que vem do Trapiche dos Capitães de Areia. Que vem do reformatório e do orfanato. Que vem do ódio do Sem-Pernas se atirando do elevador para não se entregar. Que vem no trem da Leste Brasileira, através do sertão, do grupo de Lampião pedindo justiça para os sertanejos. Que vem de Alberto, o estudante pedindo escolas e liberdade para a cultura. Que vem dos quadros de Professor, onde meninos esfarrapados lutam naquela exposição da rua Chile. Que vem de Boa-Vida e dos malandros da cidade, do bojo dos seus violões, dos sambas tristes que eles cantam. Uma voz que diz uma palavra bonita de solidariedade, de amizade: companheiros. Uma voz que convida para a festa da luta. Que é como um samba alegre de negro, como ressoar dos atabaques nas macumbas. Voz que vem da lembrança de Dora, valente lutadora. Voz que chama Pedro Bala. Como a voz de Deus chamava Pirulito, a voz do ódio o Sem-Pernas, como a voz dos sertanejos chamava Volta-Seca para o grupo de Lampião. Voz poderosa como nenhuma outra. Porque é uma voz que chama para lutar por todos, pelo destino de todos, sem exceção. Voz poderosa como nenhuma outra. Voz que atravessa a cidade e vem de todos os lados. Voz que traz com ela uma festa, que faz o inverno acabar lá fora e ser primavera. A primavera da luta. Voz que chama Pedro Bala, que o leva para a luta. Voz que vem de todos os peitos esfomeados da cidade, de todos os peitos explorados da cidade. Voz que traz o bem maior do mundo, bem que é igual ao sol, mesmo maior que o sol: a liberdade. A cidade no dia de primavera é deslumbradoramente bela. Uma voz de mulher canta a canção da Bahia. Cidade negra e velha, sinos de igreja, ruas calçadas de pedra. Canção da Bahia que uma mulher canta. Dentro de Pedro Bala uma voz o chama: voz que traz para a canção da Bahia, a canção da liberdade. Voz poderosa que o chama. Voz de toda a cidade pobre da Bahia, voz da liberdade. A revolução chama Pedro Bala.";

  checkSentencesComplexity();

  calculateData($scope.text);

  fleschKincaidEase();

});
<|endoftext|>