<commit_before>(function( Popcorn, window, document ) {

  var

  EMPTY_STRING = "",

  jwReady = false,
  jwLoaded = false,
  jwCallbacks = [];

  function onJWPlayerAPIReady() {
    jwReady = true;
    var i = jwCallbacks.length;
    while( i-- ) {
      jwCallbacks[ i ]();
      delete jwCallbacks[ i ];
    }
  };

  function jwplayerReadyCheck() {
    if ( window.jwplayer ) {
      onJWPlayerAPIReady();
    } else {
      setTimeout( jwplayerReadyCheck, 100 );
    }
  }

  function isJWPlayerReady() {
    // If the jwplayer API isn't injected, do it now.
    if ( !jwLoaded ) {
      if ( !window.jwplayer ) {
        var tag = document.createElement( "script" );

        tag.src = "https://jwpsrv.com/library/zaIF4JI9EeK2FSIACpYGxA.js";
        var firstScriptTag = document.getElementsByTagName( "script" )[ 0 ];
        firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
      }
      jwLoaded = true;
      jwplayerReadyCheck();
    }
    return jwReady;
  }

  function addJWPlayerCallback( callback ) {
    jwCallbacks.unshift( callback );
  }

  function HTMLJWPlayerVideoElement( id ) {

    if ( !window.postMessage ) {
      throw "ERROR: HTMLJWPlayerVideoElement requires window.postMessage";
    }

    var self = new Popcorn._MediaElementProto(),
      parent = typeof id === "string" ? document.querySelector( id ) : id,
      impl = {
        src: EMPTY_STRING,
        networkState: self.NETWORK_EMPTY,
        readyState: self.HAVE_NOTHING,
        seeking: false,
        autoplay: EMPTY_STRING,
        preload: EMPTY_STRING,
        controls: false,
        loop: false,
        poster: EMPTY_STRING,
        volume: 1,
        muted: false,
        currentTime: 0,
        duration: NaN,
        ended: false,
        paused: true,
        error: null
      },
      playerReady = false,
      catchRoguePauseEvent = false,
      catchRoguePlayEvent = false,
      mediaReady = false,
      loopedPlay = false,
      player,
      playerPaused = true,
      mediaReadyCallbacks = [],
      playerState = -1,
      lastLoadedFraction = 0,
      firstPlay = true,
      firstPause = false;

    // Namespace all events we'll produce
    self._eventNamespace = Popcorn.guid( "HTMLJWPlayerVideoElement::" );

    self.parentNode = parent;

    // Mark this as JWPlayer
    self._util.type = "JWPlayer";

    function addMediaReadyCallback( callback ) {
      mediaReadyCallbacks.unshift( callback );
    }

    //JWPlayer set the duration only after the video has started playing
    //http://support.jwplayer.com/customer/portal/questions/8145072-does-getduration-work-
    //Hence, in order to get the duration properly need to wait until duration is available
    function getCorrectDuration(){
      duration = player.getDuration();
      if(duration == -1){
        setTimeout(getCorrectDuration, 0);
      } else {
        impl.duration = duration
        self.dispatchEvent( "durationchange" );
      }
    }

    function onReady() {
      // JWPlayer needs a play/pause to force ready state.
      // However, the ready state does not happen until after the play/pause callbacks.
      // So we put this inside a setTimeout to ensure we do this afterwards,
      // thus, actually being ready.
      getCorrectDuration();
      setTimeout( function() {
        impl.readyState = self.HAVE_METADATA;
        self.dispatchEvent( "loadedmetadata" );
        self.dispatchEvent( "loadeddata" );

        impl.readyState = self.HAVE_FUTURE_DATA;
        self.dispatchEvent( "canplay" );

        mediaReady = true;

        var i = 0;
        while( mediaReadyCallbacks.length ) {
          mediaReadyCallbacks[ i ]();
          mediaReadyCallbacks.shift();
        }
        // We can't easily determine canplaythrough, but will send anyway.
        impl.readyState = self.HAVE_ENOUGH_DATA;
        self.dispatchEvent( "canplaythrough" );
      }, 0 );
    }

    // TODO: (maybe)
    // JWPlayer events cannot be removed, so we use functions inside the event.
    // This way we can change these functions to "remove" events.
    function onPauseEvent() {
      if ( catchRoguePauseEvent ) {
        catchRoguePauseEvent = false;
      } else if ( firstPause ) {
        firstPause = false;
        onReady();
      } else {
        onPause();
      }
    }
    function onPlayEvent() {
      if ( firstPlay ) {
        // fake ready event
        firstPlay = false;

        // Set initial paused state
        if ( impl.autoplay || !impl.paused ) {
          impl.paused = false;
          addMediaReadyCallback( onPlay );
          onReady();
        } else {
          firstPause = true;
          catchRoguePlayEvent = true;
          player.pause( true );
        }
      } else if ( catchRoguePlayEvent ) {
        catchRoguePlayEvent = false;
        catchRoguePauseEvent = true;
        // Repause without triggering any events.
        player.pause( true );
      } else {
        onPlay();
      }
    }

    function onSeekEvent() {
      if ( impl.seeking ) {
        onSeeked();
      }
    }

    function onPlayerReady() {
      player.onPause( onPauseEvent );
      player.onTime(function() {
        if ( !impl.ended && !impl.seeking ) {
          impl.currentTime = player.getPosition();
          self.dispatchEvent( "timeupdate" );
        }
      });
      player.onSeek( onSeekEvent );
      player.onPlay(function() {
        if ( !impl.ended ) {
          onPlayEvent();
        }
      });
      player.onBufferChange( onProgress );
      player.onComplete( onEnded );
      player.play( true );
    }

    function getDuration() {
      return player.getDuration();
    }

    function onPlayerError( e ) {
      var err = { name: "MediaError" };
      err.message = e.message;
      err.code = e.code || 5;

      impl.error = err;
      self.dispatchEvent( "error" );
    }

    function destroyPlayer() {
      if ( !( playerReady && player ) ) {
        return;
      }

      player.destroy();
    }

    function changeSrc( aSrc ) {
      if ( !self._canPlaySrc( aSrc ) ) {
        impl.error = {
          name: "MediaError",
          message: "Media Source Not Supported",
          code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
        };
        self.dispatchEvent( "error" );
        return;
      }

      // Use any player vars passed on the URL
      var playerVars = self._util.parseUri( aSrc ).queryKey;

      // Show/hide controls. Sync with impl.controls and prefer URL value.
      impl.controls = playerVars.controls = playerVars.controls || impl.controls;

      impl.src = aSrc;

      // Make sure JWPlayer is ready, and if not, register a callback
      if ( !isJWPlayerReady() ) {
        addJWPlayerCallback( function() { changeSrc( aSrc ); } );
        return;
      }

      if ( playerReady ) {
        destroyPlayer();
      }

      jwplayer( parent.id ).setup({
        file: aSrc,
        width: "100%",
        height: "100%",
        controls: impl.controls
      });

      player = jwplayer( parent.id );
      player.onReady( onPlayerReady );
      player.onError( onPlayerError );
      jwplayer.utils.log = function( msg, obj ) {
        if ( typeof console !== "undefined" && typeof console.log !== "undefined" ) {
          if ( obj ) {
            console.log( msg, obj );
          } else {
            console.log( msg );
          }
        }

        if ( msg === "No suitable players found and fallback enabled" ) {
          onPlayerError({
            message: msg,
            code: 4
          });
        }
      };

      impl.networkState = self.NETWORK_LOADING;
      self.dispatchEvent( "loadstart" );
      self.dispatchEvent( "progress" );
    }

    function getCurrentTime() {
      return impl.currentTime;
    }

    function changeCurrentTime( aTime ) {
      impl.currentTime = aTime;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() {
          onSeeking();
          player.seek( aTime );
        });
        return;
      }

      onSeeking();
      player.seek( aTime );
    }

    function onSeeking() {
      impl.seeking = true;
      // jwplayer plays right after a seek, we do not want this.
      if ( impl.paused ) {
        catchRoguePlayEvent = true;
      }
      self.dispatchEvent( "seeking" );
    }

    function onSeeked() {
      impl.ended = false;
      impl.seeking = false;
      self.dispatchEvent( "timeupdate" );
      self.dispatchEvent( "seeked" );
      self.dispatchEvent( "canplay" );
      self.dispatchEvent( "canplaythrough" );
    }

    function onPlay() {
      impl.paused = false;

      if ( playerPaused ) {
        playerPaused = false;

        // Only 1 play when video.loop=true
        if ( ( impl.loop && !loopedPlay ) || !impl.loop ) {
          loopedPlay = true;
          self.dispatchEvent( "play" );
        }
        self.dispatchEvent( "playing" );
      }
    }

    function onProgress() {
      self.dispatchEvent( "progress" );
    }

    self.play = function() {
      self.dispatchEvent( "play" );
      impl.paused = false;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() { self.play(); } );
        return;
      }
      if ( impl.ended ) {
        changeCurrentTime( 0 );
        impl.ended = false;
      }
      player.play( true );
    };

    function onPause() {
      impl.paused = true;
      if ( !playerPaused ) {
        playerPaused = true;
        self.dispatchEvent( "pause" );
      }
    }

    self.pause = function() {
      impl.paused = true;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() { self.pause(); } );
        return;
      }
      player.pause( true );
    };

    function onEnded() {
      if ( impl.loop ) {
        changeCurrentTime( 0 );
      } else {
        impl.ended = true;
        onPause();
        self.dispatchEvent( "timeupdate" );
        self.dispatchEvent( "ended" );
      }
    }

    function setVolume( aValue ) {
      impl.volume = aValue;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() {
          setVolume( impl.volume );
        });
        return;
      }
      player.setVolume( impl.volume * 100 );
      self.dispatchEvent( "volumechange" );
    }

    function setMuted( aValue ) {
      impl.muted = aValue;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() { setMuted( impl.muted ); } );
        return;
      }
      player.setMute( aValue );
      self.dispatchEvent( "volumechange" );
    }

    function getMuted() {
      return impl.muted;
    }

    Object.defineProperties( self, {

      src: {
        get: function() {
          return impl.src;
        },
        set: function( aSrc ) {
          if ( aSrc && aSrc !== impl.src ) {
            changeSrc( aSrc );
          }
        }
      },

      autoplay: {
        get: function() {
          return impl.autoplay;
        },
        set: function( aValue ) {
          impl.autoplay = self._util.isAttributeSet( aValue );
        }
      },

      loop: {
        get: function() {
          return impl.loop;
        },
        set: function( aValue ) {
          impl.loop = self._util.isAttributeSet( aValue );
        }
      },

      width: {
        get: function() {
          return self.parentNode.offsetWidth;
        }
      },

      height: {
        get: function() {
          return self.parentNode.offsetHeight;
        }
      },

      currentTime: {
        get: function() {
          return getCurrentTime();
        },
        set: function( aValue ) {
          changeCurrentTime( aValue );
        }
      },

      duration: {
        get: function() {
          return getDuration();
        }
      },

      ended: {
        get: function() {
          return impl.ended;
        }
      },

      paused: {
        get: function() {
          return impl.paused;
        }
      },

      seeking: {
        get: function() {
          return impl.seeking;
        }
      },

      readyState: {
        get: function() {
          return impl.readyState;
        }
      },

      networkState: {
        get: function() {
          return impl.networkState;
        }
      },

      volume: {
        get: function() {
          return impl.volume;
        },
        set: function( aValue ) {
          if ( aValue < 0 || aValue > 1 ) {
            throw "Volume value must be between 0.0 and 1.0";
          }

          setVolume( aValue );
        }
      },

      muted: {
        get: function() {
          return impl.muted;
        },
        set: function( aValue ) {
          setMuted( self._util.isAttributeSet( aValue ) );
        }
      },

      error: {
        get: function() {
          return impl.error;
        }
      },

      buffered: {
        get: function () {
          var timeRanges = {
            start: function( index ) {
              if ( index === 0 ) {
                return 0;
              }

              //throw fake DOMException/INDEX_SIZE_ERR
              throw "INDEX_SIZE_ERR: DOM Exception 1";
            },
            end: function( index ) {
              var duration;
              if ( index === 0 ) {
                duration = getDuration();
                if ( !duration ) {
                  return 0;
                }

                return duration * ( player.getBuffer() / 100 );
              }

              //throw fake DOMException/INDEX_SIZE_ERR
              throw "INDEX_SIZE_ERR: DOM Exception 1";
            },
            length: 1
          };

          return timeRanges;
        }
      }
    });

    self._canPlaySrc = Popcorn.HTMLJWPlayerVideoElement._canPlaySrc;
    self.canPlayType = Popcorn.HTMLJWPlayerVideoElement.canPlayType;

    return self;
  }

  Popcorn.HTMLJWPlayerVideoElement = function( id ) {
    return new HTMLJWPlayerVideoElement( id );
  };

  // Helper for identifying URLs we know how to play.
  Popcorn.HTMLJWPlayerVideoElement._canPlaySrc = function( url ) {
    // Because of the nature of JWPlayer playing all media types,
    // it can potentially play all url formats.
    return "probably";
  };

  // This could potentially support everything. It is a bit of a catch all player.
  Popcorn.HTMLJWPlayerVideoElement.canPlayType = function( type ) {
    return "probably";
  };

}( Popcorn, window, document ));
<commit_msg>Make duration a local variable<commit_after>(function( Popcorn, window, document ) {

  var

  EMPTY_STRING = "",

  jwReady = false,
  jwLoaded = false,
  jwCallbacks = [];

  function onJWPlayerAPIReady() {
    jwReady = true;
    var i = jwCallbacks.length;
    while( i-- ) {
      jwCallbacks[ i ]();
      delete jwCallbacks[ i ];
    }
  };

  function jwplayerReadyCheck() {
    if ( window.jwplayer ) {
      onJWPlayerAPIReady();
    } else {
      setTimeout( jwplayerReadyCheck, 100 );
    }
  }

  function isJWPlayerReady() {
    // If the jwplayer API isn't injected, do it now.
    if ( !jwLoaded ) {
      if ( !window.jwplayer ) {
        var tag = document.createElement( "script" );

        tag.src = "https://jwpsrv.com/library/zaIF4JI9EeK2FSIACpYGxA.js";
        var firstScriptTag = document.getElementsByTagName( "script" )[ 0 ];
        firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
      }
      jwLoaded = true;
      jwplayerReadyCheck();
    }
    return jwReady;
  }

  function addJWPlayerCallback( callback ) {
    jwCallbacks.unshift( callback );
  }

  function HTMLJWPlayerVideoElement( id ) {

    if ( !window.postMessage ) {
      throw "ERROR: HTMLJWPlayerVideoElement requires window.postMessage";
    }

    var self = new Popcorn._MediaElementProto(),
      parent = typeof id === "string" ? document.querySelector( id ) : id,
      impl = {
        src: EMPTY_STRING,
        networkState: self.NETWORK_EMPTY,
        readyState: self.HAVE_NOTHING,
        seeking: false,
        autoplay: EMPTY_STRING,
        preload: EMPTY_STRING,
        controls: false,
        loop: false,
        poster: EMPTY_STRING,
        volume: 1,
        muted: false,
        currentTime: 0,
        duration: NaN,
        ended: false,
        paused: true,
        error: null
      },
      playerReady = false,
      catchRoguePauseEvent = false,
      catchRoguePlayEvent = false,
      mediaReady = false,
      loopedPlay = false,
      player,
      playerPaused = true,
      mediaReadyCallbacks = [],
      playerState = -1,
      lastLoadedFraction = 0,
      firstPlay = true,
      firstPause = false;

    // Namespace all events we'll produce
    self._eventNamespace = Popcorn.guid( "HTMLJWPlayerVideoElement::" );

    self.parentNode = parent;

    // Mark this as JWPlayer
    self._util.type = "JWPlayer";

    function addMediaReadyCallback( callback ) {
      mediaReadyCallbacks.unshift( callback );
    }

    //JWPlayer set the duration only after the video has started playing
    //http://support.jwplayer.com/customer/portal/questions/8145072-does-getduration-work-
    //Hence, in order to get the duration properly need to wait until duration is available
    function getCorrectDuration(){
      var duration = player.getDuration();
      if(duration == -1){
        setTimeout(getCorrectDuration, 0);
      } else {
        impl.duration = duration
        self.dispatchEvent( "durationchange" );
      }
    }

    function onReady() {
      // JWPlayer needs a play/pause to force ready state.
      // However, the ready state does not happen until after the play/pause callbacks.
      // So we put this inside a setTimeout to ensure we do this afterwards,
      // thus, actually being ready.
      getCorrectDuration();
      setTimeout( function() {
        impl.readyState = self.HAVE_METADATA;
        self.dispatchEvent( "loadedmetadata" );
        self.dispatchEvent( "loadeddata" );

        impl.readyState = self.HAVE_FUTURE_DATA;
        self.dispatchEvent( "canplay" );

        mediaReady = true;

        var i = 0;
        while( mediaReadyCallbacks.length ) {
          mediaReadyCallbacks[ i ]();
          mediaReadyCallbacks.shift();
        }
        // We can't easily determine canplaythrough, but will send anyway.
        impl.readyState = self.HAVE_ENOUGH_DATA;
        self.dispatchEvent( "canplaythrough" );
      }, 0 );
    }

    // TODO: (maybe)
    // JWPlayer events cannot be removed, so we use functions inside the event.
    // This way we can change these functions to "remove" events.
    function onPauseEvent() {
      if ( catchRoguePauseEvent ) {
        catchRoguePauseEvent = false;
      } else if ( firstPause ) {
        firstPause = false;
        onReady();
      } else {
        onPause();
      }
    }
    function onPlayEvent() {
      if ( firstPlay ) {
        // fake ready event
        firstPlay = false;

        // Set initial paused state
        if ( impl.autoplay || !impl.paused ) {
          impl.paused = false;
          addMediaReadyCallback( onPlay );
          onReady();
        } else {
          firstPause = true;
          catchRoguePlayEvent = true;
          player.pause( true );
        }
      } else if ( catchRoguePlayEvent ) {
        catchRoguePlayEvent = false;
        catchRoguePauseEvent = true;
        // Repause without triggering any events.
        player.pause( true );
      } else {
        onPlay();
      }
    }

    function onSeekEvent() {
      if ( impl.seeking ) {
        onSeeked();
      }
    }

    function onPlayerReady() {
      player.onPause( onPauseEvent );
      player.onTime(function() {
        if ( !impl.ended && !impl.seeking ) {
          impl.currentTime = player.getPosition();
          self.dispatchEvent( "timeupdate" );
        }
      });
      player.onSeek( onSeekEvent );
      player.onPlay(function() {
        if ( !impl.ended ) {
          onPlayEvent();
        }
      });
      player.onBufferChange( onProgress );
      player.onComplete( onEnded );
      player.play( true );
    }

    function getDuration() {
      return player.getDuration();
    }

    function onPlayerError( e ) {
      var err = { name: "MediaError" };
      err.message = e.message;
      err.code = e.code || 5;

      impl.error = err;
      self.dispatchEvent( "error" );
    }

    function destroyPlayer() {
      if ( !( playerReady && player ) ) {
        return;
      }

      player.destroy();
    }

    function changeSrc( aSrc ) {
      if ( !self._canPlaySrc( aSrc ) ) {
        impl.error = {
          name: "MediaError",
          message: "Media Source Not Supported",
          code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
        };
        self.dispatchEvent( "error" );
        return;
      }

      // Use any player vars passed on the URL
      var playerVars = self._util.parseUri( aSrc ).queryKey;

      // Show/hide controls. Sync with impl.controls and prefer URL value.
      impl.controls = playerVars.controls = playerVars.controls || impl.controls;

      impl.src = aSrc;

      // Make sure JWPlayer is ready, and if not, register a callback
      if ( !isJWPlayerReady() ) {
        addJWPlayerCallback( function() { changeSrc( aSrc ); } );
        return;
      }

      if ( playerReady ) {
        destroyPlayer();
      }

      jwplayer( parent.id ).setup({
        file: aSrc,
        width: "100%",
        height: "100%",
        controls: impl.controls
      });

      player = jwplayer( parent.id );
      player.onReady( onPlayerReady );
      player.onError( onPlayerError );
      jwplayer.utils.log = function( msg, obj ) {
        if ( typeof console !== "undefined" && typeof console.log !== "undefined" ) {
          if ( obj ) {
            console.log( msg, obj );
          } else {
            console.log( msg );
          }
        }

        if ( msg === "No suitable players found and fallback enabled" ) {
          onPlayerError({
            message: msg,
            code: 4
          });
        }
      };

      impl.networkState = self.NETWORK_LOADING;
      self.dispatchEvent( "loadstart" );
      self.dispatchEvent( "progress" );
    }

    function getCurrentTime() {
      return impl.currentTime;
    }

    function changeCurrentTime( aTime ) {
      impl.currentTime = aTime;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() {
          onSeeking();
          player.seek( aTime );
        });
        return;
      }

      onSeeking();
      player.seek( aTime );
    }

    function onSeeking() {
      impl.seeking = true;
      // jwplayer plays right after a seek, we do not want this.
      if ( impl.paused ) {
        catchRoguePlayEvent = true;
      }
      self.dispatchEvent( "seeking" );
    }

    function onSeeked() {
      impl.ended = false;
      impl.seeking = false;
      self.dispatchEvent( "timeupdate" );
      self.dispatchEvent( "seeked" );
      self.dispatchEvent( "canplay" );
      self.dispatchEvent( "canplaythrough" );
    }

    function onPlay() {
      impl.paused = false;

      if ( playerPaused ) {
        playerPaused = false;

        // Only 1 play when video.loop=true
        if ( ( impl.loop && !loopedPlay ) || !impl.loop ) {
          loopedPlay = true;
          self.dispatchEvent( "play" );
        }
        self.dispatchEvent( "playing" );
      }
    }

    function onProgress() {
      self.dispatchEvent( "progress" );
    }

    self.play = function() {
      self.dispatchEvent( "play" );
      impl.paused = false;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() { self.play(); } );
        return;
      }
      if ( impl.ended ) {
        changeCurrentTime( 0 );
        impl.ended = false;
      }
      player.play( true );
    };

    function onPause() {
      impl.paused = true;
      if ( !playerPaused ) {
        playerPaused = true;
        self.dispatchEvent( "pause" );
      }
    }

    self.pause = function() {
      impl.paused = true;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() { self.pause(); } );
        return;
      }
      player.pause( true );
    };

    function onEnded() {
      if ( impl.loop ) {
        changeCurrentTime( 0 );
      } else {
        impl.ended = true;
        onPause();
        self.dispatchEvent( "timeupdate" );
        self.dispatchEvent( "ended" );
      }
    }

    function setVolume( aValue ) {
      impl.volume = aValue;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() {
          setVolume( impl.volume );
        });
        return;
      }
      player.setVolume( impl.volume * 100 );
      self.dispatchEvent( "volumechange" );
    }

    function setMuted( aValue ) {
      impl.muted = aValue;
      if ( !mediaReady ) {
        addMediaReadyCallback( function() { setMuted( impl.muted ); } );
        return;
      }
      player.setMute( aValue );
      self.dispatchEvent( "volumechange" );
    }

    function getMuted() {
      return impl.muted;
    }

    Object.defineProperties( self, {

      src: {
        get: function() {
          return impl.src;
        },
        set: function( aSrc ) {
          if ( aSrc && aSrc !== impl.src ) {
            changeSrc( aSrc );
          }
        }
      },

      autoplay: {
        get: function() {
          return impl.autoplay;
        },
        set: function( aValue ) {
          impl.autoplay = self._util.isAttributeSet( aValue );
        }
      },

      loop: {
        get: function() {
          return impl.loop;
        },
        set: function( aValue ) {
          impl.loop = self._util.isAttributeSet( aValue );
        }
      },

      width: {
        get: function() {
          return self.parentNode.offsetWidth;
        }
      },

      height: {
        get: function() {
          return self.parentNode.offsetHeight;
        }
      },

      currentTime: {
        get: function() {
          return getCurrentTime();
        },
        set: function( aValue ) {
          changeCurrentTime( aValue );
        }
      },

      duration: {
        get: function() {
          return getDuration();
        }
      },

      ended: {
        get: function() {
          return impl.ended;
        }
      },

      paused: {
        get: function() {
          return impl.paused;
        }
      },

      seeking: {
        get: function() {
          return impl.seeking;
        }
      },

      readyState: {
        get: function() {
          return impl.readyState;
        }
      },

      networkState: {
        get: function() {
          return impl.networkState;
        }
      },

      volume: {
        get: function() {
          return impl.volume;
        },
        set: function( aValue ) {
          if ( aValue < 0 || aValue > 1 ) {
            throw "Volume value must be between 0.0 and 1.0";
          }

          setVolume( aValue );
        }
      },

      muted: {
        get: function() {
          return impl.muted;
        },
        set: function( aValue ) {
          setMuted( self._util.isAttributeSet( aValue ) );
        }
      },

      error: {
        get: function() {
          return impl.error;
        }
      },

      buffered: {
        get: function () {
          var timeRanges = {
            start: function( index ) {
              if ( index === 0 ) {
                return 0;
              }

              //throw fake DOMException/INDEX_SIZE_ERR
              throw "INDEX_SIZE_ERR: DOM Exception 1";
            },
            end: function( index ) {
              var duration;
              if ( index === 0 ) {
                duration = getDuration();
                if ( !duration ) {
                  return 0;
                }

                return duration * ( player.getBuffer() / 100 );
              }

              //throw fake DOMException/INDEX_SIZE_ERR
              throw "INDEX_SIZE_ERR: DOM Exception 1";
            },
            length: 1
          };

          return timeRanges;
        }
      }
    });

    self._canPlaySrc = Popcorn.HTMLJWPlayerVideoElement._canPlaySrc;
    self.canPlayType = Popcorn.HTMLJWPlayerVideoElement.canPlayType;

    return self;
  }

  Popcorn.HTMLJWPlayerVideoElement = function( id ) {
    return new HTMLJWPlayerVideoElement( id );
  };

  // Helper for identifying URLs we know how to play.
  Popcorn.HTMLJWPlayerVideoElement._canPlaySrc = function( url ) {
    // Because of the nature of JWPlayer playing all media types,
    // it can potentially play all url formats.
    return "probably";
  };

  // This could potentially support everything. It is a bit of a catch all player.
  Popcorn.HTMLJWPlayerVideoElement.canPlayType = function( type ) {
    return "probably";
  };

}( Popcorn, window, document ));
<|endoftext|>


<commit_before>/**
 * Created by jhon on 29/03/14.
 */
var BogoData = {};

BogoData.options = {
    passphrase: 'dg76sdgdfg',
    localStorageItem: 'BgD0',
    localStorageDataset: 'DseT'
};

BogoData.markersArray = [];

BogoData.init = function () {
    BogoData.initMap();
    BogoData.setRoutes();
}

BogoData.setRoutes = function () {
    $.router.add('/auth/refresh', function () {
        $.ajax({
            url: "/auth/user"
        }).done(function (data) {
                var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), BogoData.options.passphrase);
                //var decrypted = CryptoJS.AES.decrypt(encrypted, BogoData.options.passphrase);
                if (data) {
                    $("#signInButton").hide();
                    $("#signOutButton").show();
                    localStorage.setItem(BogoData.options.localStorageItem, encrypted);
                } else {
                    $("#signInButton").show();
                    $("#signOutButton").hide();
                    localStorage.removeItem(BogoData.options.localStorageItem);
                }
                //reset URL
                $.router.go("/", "");

            }).fail(function (jqXHR, textStatus, errorThrown) {
                $("#signInButton").show();
                $("#signOutButton").hide();
                localStorage.removeItem(BogoData.options.localStorageItem);
                //reset URL
                $.router.go("/", "");
            });
    });
}

BogoData.showSignIn = function () {
    $("#signIn").dialog({
        modal: true
    });
}

BogoData.setUpActions = function () {
    google.maps.event.addListener(BogoData.map, "click", function (event) {

        var templateLoaded = function (template) {

            var html = $.tmpl(template).html();

            var infowindow = new google.maps.InfoWindow({
                content: html
            });

            var selectDatasetDialog = $("#selectDataset");

            selectDatasetDialog.dialog({
                modal: true
            });

            var placeMarker = function () {

                if (BogoData.marker) {
                    BogoData.marker.setMap(null);
                }

                BogoData.marker = new google.maps.Marker({
                    position: event.latLng,
                    draggable: true,
                    map: BogoData.map
                });

                infowindow.open(BogoData.map, BogoData.marker);

                google.maps.event.addListener(BogoData.marker, "click", function () {
                    infowindow.open(BogoData.map, BogoData.marker);
                });
            }

            var options = $("#selectDatasetShowDatasets");

            $.ajax({
                url: "/datasets"
            }).done(function (data) {
                    $.each(data, function () {
                        options.append($("<option />").val(this._id).text(this.title));
                    });

                    options.change(function () {
                        var selected;
                        $.each(data, function () {
                            if (this._id === options.val()) {
                                localStorage.setItem(BogoData.options.localStorageDataset, JSON.stringify(this));
                            }
                        });

                        selectDatasetDialog.dialog('close');
                        placeMarker();
                    });

                }).fail(function (jqXHR, textStatus, errorThrown) {
                    options.append($("<option />").val(0).text("No hay datasets"));
                });
        }

        //load template first
        $.get('/templates/hurtosForm.html', templateLoaded);

    });
}

BogoData.initMap = function () {
    var mapCanvas = document.getElementById('map_canvas');
    var mapOptions = {
        center: new google.maps.LatLng(4.670332, -74.086028),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(mapCanvas, mapOptions);

    BogoData.map = map;

    BogoData.setUpActions();
}

BogoData.report = function () {

    var postData = {
        latitude: BogoData.marker.position.k,
        longitude: BogoData.marker.position.A,
        detail: $("#detailInput").val(),
        data: {
            tipoRobo: $("#tipoRobo").val()
        }
    }

    var selectedDataset = JSON.parse(localStorage.getItem(BogoData.options.localStorageDataset));

    $.ajax({
        url: "/datasets/" + selectedDataset.name + "/reports",
        type: "POST",
        data: postData
    }).done(function (data) {
            console.log(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        });
}

BogoData.cancelReport = function () {
    BogoData.marker.setMap(null);
}

google.maps.event.addDomListener(window, 'load', BogoData.init);<commit_msg>Fixed bug when reporting<commit_after>/**
 * Created by jhon on 29/03/14.
 */
var BogoData = {};

BogoData.options = {
    passphrase: 'dg76sdgdfg',
    localStorageItem: 'BgD0',
    localStorageDataset: 'DseT',
    localStorageAllDatasets: 'ADseTs'
};

BogoData.markersArray = [];

BogoData.init = function () {
    BogoData.initMap();
    BogoData.loadLayers();
    BogoData.setRoutes();
}

BogoData.loadLayers = function () {
    $.ajax({
        url: "/datasets"
    }).done(function (data) {
            localStorage.setItem(BogoData.options.localStorageAllDatasets, JSON.stringify(data));

        }).fail(function (jqXHR, textStatus, errorThrown) {
            alert("Error");
        });
}

BogoData.setRoutes = function () {
    $.router.add('/auth/refresh', function () {
        $.ajax({
            url: "/auth/user"
        }).done(function (data) {
                var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), BogoData.options.passphrase);
                //var decrypted = CryptoJS.AES.decrypt(encrypted, BogoData.options.passphrase);
                if (data) {
                    $("#signInButton").hide();
                    $("#signOutButton").show();
                    localStorage.setItem(BogoData.options.localStorageItem, encrypted);
                } else {
                    $("#signInButton").show();
                    $("#signOutButton").hide();
                    localStorage.removeItem(BogoData.options.localStorageItem);
                }
                //reset URL
                $.router.go("/", "");

            }).fail(function (jqXHR, textStatus, errorThrown) {
                $("#signInButton").show();
                $("#signOutButton").hide();
                localStorage.removeItem(BogoData.options.localStorageItem);
                //reset URL
                $.router.go("/", "");
            });
    });
}

BogoData.showSignIn = function () {
    $("#signIn").dialog({
        modal: true
    });
}

BogoData.setUpActions = function () {
    google.maps.event.addListener(BogoData.map, "click", function (event) {

        var templateLoaded = function (template) {

            var html = $.tmpl(template).html();

            var infowindow = new google.maps.InfoWindow({
                content: html
            });

            var selectDatasetDialog = $("#selectDataset");

            selectDatasetDialog.dialog({
                modal: true
            });

            var placeMarker = function () {

                if (BogoData.marker) {
                    BogoData.marker.setMap(null);
                }

                BogoData.marker = new google.maps.Marker({
                    position: event.latLng,
                    draggable: true,
                    map: BogoData.map
                });

                infowindow.open(BogoData.map, BogoData.marker);

                google.maps.event.addListener(BogoData.marker, "click", function () {
                    infowindow.open(BogoData.map, BogoData.marker);
                });
            }

            var options = $("#selectDatasetShowDatasets");

            var dataSets = JSON.parse(localStorage.getItem(BogoData.options.localStorageAllDatasets));

            $.each(dataSets, function () {
                options.append($("<option />").val(this._id).text(this.title));
            });

            options.change(function () {
                var selected;
                $.each(dataSets, function () {
                    if (this._id === options.val()) {
                        localStorage.setItem(BogoData.options.localStorageDataset, JSON.stringify(this));
                    }
                });

                selectDatasetDialog.dialog('close');
                placeMarker();
            });
        }

        //load template first
        $.get('/templates/hurtosForm.html', templateLoaded);

    });
}

BogoData.initMap = function () {
    var mapCanvas = document.getElementById('map_canvas');
    var mapOptions = {
        center: new google.maps.LatLng(4.670332, -74.086028),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(mapCanvas, mapOptions);

    BogoData.map = map;

    BogoData.setUpActions();
}

BogoData.report = function () {

    var postData = {
        latitude: BogoData.marker.position.k,
        longitude: BogoData.marker.position.A,
        detail: $("#detailInput").val(),
        data: {
            tipoRobo: $("#tipoRobo").val()
        }
    }

    var selectedDataset = JSON.parse(localStorage.getItem(BogoData.options.localStorageDataset));

    $.ajax({
        url: "/datasets/" + selectedDataset.name + "/reports",
        type: "POST",
        data: postData
    }).done(function (data) {
            BogoData.cancelReport();
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        });
}

BogoData.cancelReport = function () {
    BogoData.marker.setMap(null);
}

google.maps.event.addDomListener(window, 'load', BogoData.init);<|endoftext|>


<commit_before>import { templateParser, parseQuotasUsage, parseComponents } from '../utils';
import { templateComparator } from './openstack-template';

// @ngInject
export default function packageTemplatesService($filter, baseServiceClass, resourcesService, coreUtils) {
  let ServiceClass = baseServiceClass.extend({
    init: function () {
      this._super();
      this.endpoint = '/package-templates/';
    },

    loadTenant: function (tenant_url) {
      return resourcesService.$get(null, null, tenant_url);
    },

    loadTenantQuotasUsage: function (tenant) {
      return this.loadTenant(tenant.url).then(tenant => parseQuotasUsage(tenant.quotas));
    },

    loadTemplates: function (tenant, template) {
      return this.loadTenantQuotasUsage(tenant).then(quotas => {
        return this.getAll({
          service_settings_uuid: tenant.service_settings_uuid,
          archived: 'False',
        }).then(templates => {
          let result = templates.map(templateParser)
            .map(choice => {
              const check = this.checkTemplate(template, quotas, choice);
              return {...choice, ...check};
            })
            .sort(templateComparator);
          return result;
        });
      });
    },

    checkTemplate: function (currentTemplate, quotas, template) {
      // Exclude current package template
      if (currentTemplate && currentTemplate.uuid === template.uuid) {
        return false;
      }

      // Allow to change package only if current usage of all quotas <= new package quotas
      const components = parseComponents(template.components);
      const enabled = (
        quotas.cores <= components.cores &&
        quotas.ram <= components.ram &&
        quotas.disk <= components.disk);

      if (enabled) {
        return {
          disabled: false,
          disabledReason: ''
        };
      }

      let disabledReason = coreUtils.templateFormatter(gettext('Package is not available because current VPC resource usage exceeds package quota limits.'));

      const parts = [
        {
          quota: 'cores',
          label: 'vCPU',
        },
        {
          quota: 'ram',
          label: 'RAM',
          filter: 'filesize',
        },
        {
          quota: 'disk',
          label: 'Storage',
          filter: 'filesize',
        },
      ];

      const messageTemplate = gettext('{quota} usage exceeds quota limit by {amount}.');

      parts.forEach(part => {
        const amount = quotas[part.quota] - components[part.quota];
        if (amount > 0) {
          let formattedAmount = amount;
          if (part.filter) {
            formattedAmount = $filter(part.filter)(amount);
          }
          const messageContext = {
            amount: formattedAmount,
            quota: part.label,
          };
          disabledReason += ' ' + coreUtils.templateFormatter(messageTemplate, messageContext);
        }
      });

      return {
        disabled: !enabled,
        disabledReason,
      };
    }
  });
  return new ServiceClass();
}
<commit_msg>Filter out current tenant package in change package dialog.<commit_after>import { templateParser, parseQuotasUsage, parseComponents } from '../utils';
import { templateComparator } from './openstack-template';

// @ngInject
export default function packageTemplatesService($filter, baseServiceClass, resourcesService, coreUtils) {
  let ServiceClass = baseServiceClass.extend({
    init: function () {
      this._super();
      this.endpoint = '/package-templates/';
    },

    loadTenant: function (tenant_url) {
      return resourcesService.$get(null, null, tenant_url);
    },

    loadTenantQuotasUsage: function (tenant) {
      return this.loadTenant(tenant.url).then(tenant => parseQuotasUsage(tenant.quotas));
    },

    loadTemplates: function (tenant, template) {
      return this.loadTenantQuotasUsage(tenant).then(quotas => {
        return this.getAll({
          service_settings_uuid: tenant.service_settings_uuid,
          archived: 'False',
        }).then(templates => {
          let result = templates
            // Exclude current package template
            .filter(choice => choice.uuid !== template.uuid).map(templateParser)
            .map(choice => {
              const check = this.checkTemplate(template, quotas, choice);
              return {...choice, ...check};
            })
            .sort(templateComparator);
          return result;
        });
      });
    },

    checkTemplate: function (currentTemplate, quotas, template) {
      // Allow to change package only if current usage of all quotas <= new package quotas
      const components = parseComponents(template.components);
      const enabled = (
        quotas.cores <= components.cores &&
        quotas.ram <= components.ram &&
        quotas.disk <= components.disk);

      if (enabled) {
        return {
          disabled: false,
          disabledReason: ''
        };
      }

      let disabledReason = coreUtils.templateFormatter(gettext('Package is not available because current VPC resource usage exceeds package quota limits.'));

      const parts = [
        {
          quota: 'cores',
          label: 'vCPU',
        },
        {
          quota: 'ram',
          label: 'RAM',
          filter: 'filesize',
        },
        {
          quota: 'disk',
          label: 'Storage',
          filter: 'filesize',
        },
      ];

      const messageTemplate = gettext('{quota} usage exceeds quota limit by {amount}.');

      parts.forEach(part => {
        const amount = quotas[part.quota] - components[part.quota];
        if (amount > 0) {
          let formattedAmount = amount;
          if (part.filter) {
            formattedAmount = $filter(part.filter)(amount);
          }
          const messageContext = {
            amount: formattedAmount,
            quota: part.label,
          };
          disabledReason += ' ' + coreUtils.templateFormatter(messageTemplate, messageContext);
        }
      });

      return {
        disabled: !enabled,
        disabledReason,
      };
    }
  });
  return new ServiceClass();
}
<|endoftext|>


<commit_before>// post4a.js - POST for Anchor
// JavaScript for sending a POST HTTP request with an HTML anchor tag
//
// (c) Yuji Kosuga 2010 http://blog.yujikosuga.com
// post4a.js is freely distributable under the MIT license
// <http://www.opensource.org/licenses/mit-license.php>.
//
// The usage example of post4s.js
// link
//
function post4a() {
    // The class name for the use of post4a.js. An anchor tag to be POSTed
    // requires this class name.
    var CLASSNAME = 'post4a';

    // The attribute name for the data to be POSTed. The value of this attribute
    // should be in JSON format.
    var POSTDATA = 'data-postdata';

    var elems = document.getElementsByClassName(CLASSNAME);
    for ( var i = 0; i < elems.length; i++) {

	// Override the default onclick function.
	elems[i]['onclick'] = function() {
	    var postData = JSON.parse(this.getAttribute(POSTDATA));
	    var form = document.createElement('form');
	    form['method'] = 'POST';
	    form['action'] = this['href'];

	    // Creates <input> tags for the data to be POSTed.
	    var inputTemp = document.createElement('input');
	    for ( var key in postData) {
		var input = inputTemp.cloneNode(true);
		input['name'] = key;
		input['value'] = postData[key];
		form.appendChild(input);
	    }

	    // For the debug use, the following line adds a newly created form
	    // to the anchor's parent node.
	    // this.parentNode.appendChild(form);
	    form.submit();

	    // Deactivate the default onclick event.
	    return false;
	};
    }
}
// Attach post4a to window.onload.
(function(func) {
    if (window.addEventListener) // for W3C DOM
	window.addEventListener('load', func, false);
    else if (window.attachEvent) // for IE
	window.attachEvent('onload', func);
    else
	window.onload = func;
})(post4a);
<commit_msg>Fixed major browser compatibility issues<commit_after>// post4a.js - POST for Anchor
// JavaScript for sending a POST HTTP request with an HTML anchor tag
//
// (c) Yuji Kosuga 2010 http://blog.yujikosuga.com
// post4a.js is freely distributable under the MIT license
// <http://www.opensource.org/licenses/mit-license.php>.
//
// The usage example of post4s.js
// link
//
var post4a = {
    // The class name for the use of post4a.js. An anchor tag to be POSTed
    // requires this class name.
    CLASSNAME : 'post4a',

    // The attribute name for the data to be POSTed. The value of this attribute
    // should be in JSON format.
    POSTDATA : 'data-postdata',

    // Add a post4a 'onclick' event listener to each anchor that has 'post4a'
    // class.
    attach : function() {
	var elems = getPost4aClassElement();
	for ( var i in elems)
	    post4a.addEvent(elems[i], 'click', post4a.submit);

	// Returns an array of anchor tags containing the 'post4a' class.
	function getPost4aClassElement() {
	    var elems = new Array();
	    if (document.getElementsByClassName) // For W3C DOM
		elems = document.getElementsByClassName(post4a.CLASSNAME);
	    else { // For IE
		var aNodes = document.getElementsByTagName("a");
		for ( var i = 0; i < aNodes.length; i++) {
		    var a = aNodes[i];
		    if (a.className == post4a.CLASSNAME)
			elems.push(a);
		}
	    }
	    return elems;
	}
    },

    submit : function(event) {
	preventDefaultEvent(event);
	var postData = jsonParse(this.getAttribute(post4a.POSTDATA));
	var form = document.createElement('form');
	form['method'] = 'POST';
	form['action'] = this['href'];

	// Creates <input> tags for the data to be POSTed.
	var inputTemp = document.createElement('input');
	for ( var key in postData) {
	    var input = inputTemp.cloneNode(true);
	    input['name'] = key;
	    input['value'] = postData[key];
	    form.appendChild(input);
	}

	// Firefox requires a form to be attached on the document.
	// We make the newly created form invisible.
	form['style']['display'] = 'none';
	this.parentNode.appendChild(form);

	form.submit();

	// Deactivate the default event.
	function preventDefaultEvent(event) {
	    if (event.preventDefault) {// For W3C DOM
		event.preventDefault();
	    } else { // For IE
		event.returnValue = false;
	    }
	}

	// Return JSON value of the specified JSON format string.
	function jsonParse(data) {
	    try {
		if (window.JSON) // For browsers that have Native JSON
		    return window.JSON.parse(data);
	    } catch (e) {
		;
	    }
	    // For old browsers
	    if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(
		    /(?:^|:|,)(?:\s*\[)+/g, "")))
		return (new Function("return " + data))();
	    return '';
	}
    },

    // Although this addEvent function does not have any depenency to this class
    // so can be globally used, it is defined in this post4a class not to
    // pollute the global namespace.
    addEvent : function(node, type, handler) {
	if (document.addEventListener) // For W3C DOM
	    node.addEventListener(type, handler, false);
	else if (document.attachEvent) // For IE
	    node.attachEvent('on' + type, function(event) {
		handler.call(node, event);
	    });
	else { // For older browsers
	    var _handler = node['on' + type];
	    node['on' + type] = function(event) {
		if (_handler)
		    _handler.call(node, event || window.event);
		handler.call(node, evt);
	    };
	}
    }
};
// Attach post4a to window.onload.
(function() {
    post4a.addEvent(window, 'load', post4a.attach);
})();
<|endoftext|>


<commit_before>var querystring = require("querystring"),
    fs = require('fs'),
    formidable = require("formidable");

function start(response) {
  console.log("Request handler 'start' was called.");

  var body = ''+
    ''+
    '<meta http-equiv="Content-Type" content="text/html; '+
    'charset=UTF-8" />'+
    ''+
    ''+
    '<form action="/upload" enctype="multipart/form-data" '+
    'method="post">'+
    '<input type="file" name="upload" multiple="multiple">'+
    '<input type="submit" value="Upload file" />'+
    '</form>'+
    ''+
    '';

  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(body);
  response.end();
}

function upload(response, request) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  form.parse(request, function(error, fields, files) {
    if (error) {
      console.log("data parsing error: " + error);
    } else {
      console.log("image data parsing done");
      fs.renameSync(files.upload.path, "/tmp/test.jpg");
      response.writeHead(200, {"Content-Type": "text/html"});
      response.write("received image:
");
      response.write("");
      response.end();
    }
  });
}

function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile("/tmp/test.jpg", "binary", function(error, file) {
    if(error) {
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\n");
      response.end();
    } else {
      response.writeHead(200, {"Content-Type": "image/jpg"});
      response.write(file, "binary");
      response.end();
    }
  });
}

exports.start = start;
exports.upload = upload;
exports.show = show;<commit_msg>Fix directly GET /upload error.<commit_after>var querystring = require("querystring"),
    fs = require('fs'),
    formidable = require("formidable");

function start(response) {
  console.log("Request handler 'start' was called.");

  var body = ''+
    ''+
    '<meta http-equiv="Content-Type" content="text/html; '+
    'charset=UTF-8" />'+
    ''+
    ''+
    '<form action="/upload" enctype="multipart/form-data" '+
    'method="post">'+
    '<input type="file" name="upload" multiple="multiple">'+
    '<input type="submit" value="Upload file" />'+
    '</form>'+
    ''+
    '';

  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(body);
  response.end();
}

function upload(response, request) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  form.parse(request, function(error, fields, files) {
    if (error) {
      console.log("data parsing error: " + error);
    } else if (!files.upload) {
      console.log("upload data error: " + error);
      response.writeHead(200, {"Content-Type": "text/html"});
      response.write("upload data error, please retry again.
");
      response.end();
    } else {
      console.log("image data parsing done");
      fs.renameSync(files.upload.path, "/tmp/test.jpg");
      response.writeHead(200, {"Content-Type": "text/html"});
      response.write("received image:
");
      response.write("");
      response.end();
    }
  });
}

function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile("/tmp/test.jpg", "binary", function(error, file) {
    if(error) {
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\n");
      response.end();
    } else {
      response.writeHead(200, {"Content-Type": "image/jpg"});
      response.write(file, "binary");
      response.end();
    }
  });
}

exports.start = start;
exports.upload = upload;
exports.show = show;<|endoftext|>


<commit_before>"use strict";

var env = require("./env.js");

module.exports = function(req, res, next){

	var doRedirect = false,
		hostHeaderValue = req.header("host"),
		forwardHeaderValue = req.header('x-forwarded-proto'); //This header is what our app sees in Heroku.

	//if people navigate to jonandlizwedding.herokuapp.com, I'd like to redirect them to jonandlizwedding.com.
	if(env.get("HEROKUAPP_REDIRECT") && (!hostHeaderValue || hostHeaderValue.toLowerCase().indexOf("herokuapp") !== -1)){
		hostHeaderValue = "plumfeed.com";
		doRedirect = true;
	}

	//redirect from http to https if setting is on
	if(env.get("HTTPS_REDIRECT") && forwardHeaderValue && forwardHeaderValue !== "https"){
		doRedirect = true;
	}

	if(doRedirect){

		var protocol = "https://";
		if(!env.get("HTTPS_REDIRECT")){
			protocol = "http://";
		}

		res.redirect(protocol + hostHeaderValue +req.url);
	}
	else{
		next();
	}
};<commit_msg>Forgot to clean up a reference to my other website.<commit_after>"use strict";

var env = require("./env.js");

module.exports = function(req, res, next){

	var doRedirect = false,
		hostHeaderValue = req.header("host"),
		forwardHeaderValue = req.header('x-forwarded-proto'); //This header is what our app sees in Heroku.

	//if people navigate to jonandlizwedding.herokuapp.com, I'd like to redirect them to jonandlizwedding.com.
	if(env.get("HEROKUAPP_REDIRECT") && (!hostHeaderValue || hostHeaderValue.toLowerCase().indexOf("herokuapp") !== -1)){
		hostHeaderValue = "jonandlizwedding.com";
		doRedirect = true;
	}

	//redirect from http to https if setting is on
	if(env.get("HTTPS_REDIRECT") && forwardHeaderValue && forwardHeaderValue !== "https"){
		doRedirect = true;
	}

	if(doRedirect){

		var protocol = "https://";
		if(!env.get("HTTPS_REDIRECT")){
			protocol = "http://";
		}

		res.redirect(protocol + hostHeaderValue +req.url);
	}
	else{
		next();
	}
};<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');

const opticsAgent = require('optics-agent');

const {
    graphqlExpress,
    graphiqlExpress
} = require('graphql-server-express');

const bodyParser = require('body-parser');

const featureContext = {};

const features = require('../util/features');

if (features.has('plebiscite')) {
    _.assign(featureContext, {
        plebiscite: require('../features/plebiscite')
    });
}

const querySchema = require('../graph');

const Connector = require('../graph/storage/connector');
const {Substances} = require('../graph/storage/models');

const SMWDataArbitrator = require('../graph/helpers/smwDataArbitrator');
const smwDataArbitrator = new SMWDataArbitrator();

const PWPropParser = require('../graph/helpers/pwPropParser');

const pwPropParser = new PWPropParser({
    smwDataArbitrator
});

module.exports = function* ({app, log}) {
    const baseQuerySchema = querySchema({log});

    app.use(opticsAgent.middleware());

    app.get('/', graphiqlExpress({
        endpointURL: '/',
        query:
`{
  substances(query: "Armodafinil") {
    effects {
      name
      substances {
        addictionPotential
        crossTolerances
        featured
        name
        summary
        url
      }
      url
    }
    name
  }
}`,
    }));

    app.post('/', bodyParser.json(), (req, res, next) =>
        graphqlExpress({
            schema: opticsAgent.instrumentSchema(baseQuerySchema.schema),
            rootValue: baseQuerySchema.root(req, res),
            context: _.assign({}, {
                substances: new Substances({
                    connector: new Connector({log}),
                    pwPropParser,
                    log
                }),
                opticsContext: opticsAgent.context(req)
            }, featureContext)
        })(req, res, next)
    );
};
<commit_msg>Enhance default demo-query to showcase new ROA collection format<commit_after>'use strict';

const _ = require('lodash');

const opticsAgent = require('optics-agent');

const {
    graphqlExpress,
    graphiqlExpress
} = require('graphql-server-express');

const bodyParser = require('body-parser');

const featureContext = {};

const features = require('../util/features');

if (features.has('plebiscite')) {
    _.assign(featureContext, {
        plebiscite: require('../features/plebiscite')
    });
}

const querySchema = require('../graph');

const Connector = require('../graph/storage/connector');
const {Substances} = require('../graph/storage/models');

const SMWDataArbitrator = require('../graph/helpers/smwDataArbitrator');
const smwDataArbitrator = new SMWDataArbitrator();

const PWPropParser = require('../graph/helpers/pwPropParser');

const pwPropParser = new PWPropParser({
    smwDataArbitrator
});

module.exports = function* ({app, log}) {
    const baseQuerySchema = querySchema({log});

    app.use(opticsAgent.middleware());

    app.get('/', graphiqlExpress({
        endpointURL: '/',
        query:
`{
    substances(query: "Armodafinil") {
        name

        # routes of administration
        roas {
            name

            dose {
                units
                threshold
                heavy
                common { min max }
                light { min max }
                strong { min max }
            }

            duration {
                afterglow { min max units }
                comeup { min max units }
                duration { min max units }
                offset { min max units }
                onset { min max units }
                peak { min max units }
                total { min max units }
            }

            bioavailability {
                min max
            }
        }

        # subjective effects
        effects {
            name url
        }
    }
}`,
    }));

    app.post('/', bodyParser.json(), (req, res, next) =>
        graphqlExpress({
            schema: opticsAgent.instrumentSchema(baseQuerySchema.schema),
            rootValue: baseQuerySchema.root(req, res),
            context: _.assign({}, {
                substances: new Substances({
                    connector: new Connector({log}),
                    pwPropParser,
                    log
                }),
                opticsContext: opticsAgent.context(req)
            }, featureContext)
        })(req, res, next)
    );
};
<|endoftext|>


<commit_before>angular.module('cesium.es.document.controllers', ['cesium.es.services'])

  .config(function($stateProvider) {
    'ngInject';

    $stateProvider

      .state('app.document_search', {
        url: "/data/search/:index/:type?q",
        views: {
          'menuContent': {
            templateUrl: "plugins/es/templates/document/lookup.html",
            controller: 'ESDocumentLookupCtrl'
          }
        },
        data: {
          silentLocationChange: true
        }
      })
    ;
  })

  .controller('ESDocumentLookupCtrl', ESDocumentLookupController)

;

function ESDocumentLookupController($scope, $ionicPopover, $location, $timeout,
                                    csSettings, csWallet, UIUtils, esDocument) {
  'ngInject';

  $scope.search = {
    loading: true,
    hasMore: true,
    text: undefined,
    index: 'invitation',
    type: 'certification',
    results: undefined,
    sort: 'time',
    asc: false
  };
  $scope.entered = false;
  $scope.searchTextId = 'documentSearchText';
  $scope.ionItemClass = 'item-border-large';
  $scope.defaultSizeLimit = UIUtils.screen.isSmall() ? 50 : 100;
  $scope.helptipPrefix = 'helptip-document';

  $scope.$on('$ionicView.enter', function(e, state) {

    if (!$scope.entered) {
      $scope.entered = true;
      $scope.search.index = state.stateParams && state.stateParams.index || $scope.search.index;
      $scope.search.type = state.stateParams && state.stateParams.type || $scope.search.type;
      $scope.search.text = state.stateParams && state.stateParams.q || $scope.search.text;

      $scope.search.last = !$scope.search.text;
      $scope.load();
    }
    $scope.expertMode = angular.isDefined($scope.expertMode) ? $scope.expertMode : !UIUtils.screen.isSmall() && csSettings.data.expertMode;
  });

  $scope.load = function(size, offset) {
    var options  = {
      index: $scope.search.index,
      type: $scope.search.type,
      from: offset || 0,
      size: size || $scope.defaultSizeLimit
    };

    // add sort
    if ($scope.search.sort) {
      options.sort = $scope.search.sort + ':' + (!$scope.search.asc ? "desc" : "asc");
    }
    else { // default sort
      options.sort = "time:desc";
    }

    $scope.search.loading = true;

    var searchFn =  $scope.search.last
      ? esDocument.search(options)
      : esDocument.searchText($scope.search.text||'', options);
    return searchFn
      .then(function(res) {
        $scope.search.results = res.hits;
        $scope.search.total = res.total;
        $scope.search.took = res.took;

        UIUtils.loading.hide();
        $scope.search.loading = false;

        if (res.hits && res.hits.length > 0) {
          $scope.motion.show({selector: '.list .item.item-document'});
          $scope.search.hasMore = res.total > $scope.search.results.length;
        }
        else {
          $scope.search.hasMore = false;
        }

        $scope.$broadcast('$$rebind::rebind'); // notify binder
      })
      .catch(function(err) {
        UIUtils.onError('DOCUMENT.ERROR.LOAD_DOCUMENTS_FAILED')(err);
        $scope.search.results = [];
        $scope.search.loading = false;
      });
  };

  $scope.doSearchText = function() {
    $scope.search.last = $scope.search.text ? false : true;
    return $scope.load()
      .then(function() {
        // Update location href
        $location.search({q: $scope.search.text}).replace();
      });
  };

  $scope.doSearchLast = function() {
    $scope.search.last = true;
    $scope.search.text = undefined;
    return $scope.load();
  };

  $scope.removeAll = function() {
    $scope.hideActionsPopover();
    if (!$scope.search.results || !$scope.search.results.length) return;

    return UIUtils.alert.confirm('DOCUMENT.CONFIRM.REMOVE_ALL')
      .then(function(confirm) {
        if (confirm) {
          return esDocument.removeAll($scope.search.results)
            .catch(UIUtils.onError('DOCUMENT.ERROR.REMOVE_ALL_FAILED'));
        }
      });
  };

  $scope.remove = function(index) {
    var doc = $scope.search.results[index];
    if (!doc) return;

    UIUtils.alert.confirm('DOCUMENT.CONFIRM.REMOVE')
      .then(function(confirm) {
        if (confirm) {
          esDocument.remove(doc)
            .then(function () {
              $scope.search.results.splice(index,1); // remove from messages array
              UIUtils.toast.show('DOCUMENT.INFO.REMOVED');
            })
            .catch(UIUtils.onError('MESSAGE.ERROR.REMOVE_FAILED'));
        }
      });
  };

  $scope.selectDocument = function(doc) {
    console.debug("Selected document: ", doc);
  };

  $scope.toggleSort = function(sort){
    if ($scope.search.sort === sort && !$scope.search.asc) {
      $scope.search.asc = undefined;
      $scope.search.sort = undefined;
    }
    else {
      $scope.search.asc = ($scope.search.sort === sort) ? !$scope.search.asc : true;
      $scope.search.sort = sort;
    }
    $scope.load();
  };

  /* -- Modals -- */

  /* -- Popover -- */

  $scope.showActionsPopover = function(event) {
    if (!$scope.actionsPopover) {
      $ionicPopover.fromTemplateUrl('plugins/es/templates/document/lookup_popover_actions.html', {
        scope: $scope
      }).then(function(popover) {
        $scope.actionsPopover = popover;
        //Cleanup the popover when we're done with it!
        $scope.$on('$destroy', function() {
          $scope.actionsPopover.remove();
        });
        $scope.actionsPopover.show(event);
      });
    }
    else {
      $scope.actionsPopover.show(event);
    }
  };

  $scope.hideActionsPopover = function() {
    if ($scope.actionsPopover) {
      $scope.actionsPopover.hide();
    }
  };

  /* -- watch events -- */

  // Watch unauth
  $scope.onUnauth = function() {
    // Reset all data
    $scope.search.results = undefined;
    $scope.search.loading = false;
    $scope.entered = false;
  };
  csWallet.api.data.on.unauth($scope, $scope.onUnauth);

  // for DEV only
  /*$timeout(function() {
    // launch default action fo DEV
   }, 900);
   */
}
<commit_msg>js hint<commit_after>angular.module('cesium.es.document.controllers', ['cesium.es.services'])

  .config(function($stateProvider) {
    'ngInject';

    $stateProvider

      .state('app.document_search', {
        url: "/data/search/:index/:type?q",
        views: {
          'menuContent': {
            templateUrl: "plugins/es/templates/document/lookup.html",
            controller: 'ESDocumentLookupCtrl'
          }
        },
        data: {
          silentLocationChange: true
        }
      })
    ;
  })

  .controller('ESDocumentLookupCtrl', ESDocumentLookupController)

;

function ESDocumentLookupController($scope, $ionicPopover, $location, $timeout,
                                    csSettings, csWallet, UIUtils, esDocument) {
  'ngInject';

  $scope.search = {
    loading: true,
    hasMore: true,
    text: undefined,
    index: 'invitation',
    type: 'certification',
    results: undefined,
    sort: 'time',
    asc: false
  };
  $scope.entered = false;
  $scope.searchTextId = 'documentSearchText';
  $scope.ionItemClass = 'item-border-large';
  $scope.defaultSizeLimit = UIUtils.screen.isSmall() ? 50 : 100;
  $scope.helptipPrefix = 'helptip-document';

  $scope.$on('$ionicView.enter', function(e, state) {

    if (!$scope.entered) {
      $scope.entered = true;
      $scope.search.index = state.stateParams && state.stateParams.index || $scope.search.index;
      $scope.search.type = state.stateParams && state.stateParams.type || $scope.search.type;
      $scope.search.text = state.stateParams && state.stateParams.q || $scope.search.text;

      $scope.search.last = !$scope.search.text;
      $scope.load();
    }
    $scope.expertMode = angular.isDefined($scope.expertMode) ? $scope.expertMode : !UIUtils.screen.isSmall() && csSettings.data.expertMode;
  });

  $scope.load = function(size, offset) {
    var options  = {
      index: $scope.search.index,
      type: $scope.search.type,
      from: offset || 0,
      size: size || $scope.defaultSizeLimit
    };

    // add sort
    if ($scope.search.sort) {
      options.sort = $scope.search.sort + ':' + (!$scope.search.asc ? "desc" : "asc");
    }
    else { // default sort
      options.sort = "time:desc";
    }

    $scope.search.loading = true;

    var searchFn =  $scope.search.last ?
      esDocument.search(options) :
      esDocument.searchText($scope.search.text||'', options);
    return searchFn
      .then(function(res) {
        $scope.search.results = res.hits;
        $scope.search.total = res.total;
        $scope.search.took = res.took;

        UIUtils.loading.hide();
        $scope.search.loading = false;

        if (res.hits && res.hits.length > 0) {
          $scope.motion.show({selector: '.list .item.item-document'});
          $scope.search.hasMore = res.total > $scope.search.results.length;
        }
        else {
          $scope.search.hasMore = false;
        }

        $scope.$broadcast('$$rebind::rebind'); // notify binder
      })
      .catch(function(err) {
        UIUtils.onError('DOCUMENT.ERROR.LOAD_DOCUMENTS_FAILED')(err);
        $scope.search.results = [];
        $scope.search.loading = false;
      });
  };

  $scope.doSearchText = function() {
    $scope.search.last = $scope.search.text ? false : true;
    return $scope.load()
      .then(function() {
        // Update location href
        $location.search({q: $scope.search.text}).replace();
      });
  };

  $scope.doSearchLast = function() {
    $scope.search.last = true;
    $scope.search.text = undefined;
    return $scope.load();
  };

  $scope.removeAll = function() {
    $scope.hideActionsPopover();
    if (!$scope.search.results || !$scope.search.results.length) return;

    return UIUtils.alert.confirm('DOCUMENT.CONFIRM.REMOVE_ALL')
      .then(function(confirm) {
        if (confirm) {
          return esDocument.removeAll($scope.search.results)
            .catch(UIUtils.onError('DOCUMENT.ERROR.REMOVE_ALL_FAILED'));
        }
      });
  };

  $scope.remove = function(index) {
    var doc = $scope.search.results[index];
    if (!doc) return;

    UIUtils.alert.confirm('DOCUMENT.CONFIRM.REMOVE')
      .then(function(confirm) {
        if (confirm) {
          esDocument.remove(doc)
            .then(function () {
              $scope.search.results.splice(index,1); // remove from messages array
              UIUtils.toast.show('DOCUMENT.INFO.REMOVED');
            })
            .catch(UIUtils.onError('MESSAGE.ERROR.REMOVE_FAILED'));
        }
      });
  };

  $scope.selectDocument = function(doc) {
    console.debug("Selected document: ", doc);
  };

  $scope.toggleSort = function(sort){
    if ($scope.search.sort === sort && !$scope.search.asc) {
      $scope.search.asc = undefined;
      $scope.search.sort = undefined;
    }
    else {
      $scope.search.asc = ($scope.search.sort === sort) ? !$scope.search.asc : true;
      $scope.search.sort = sort;
    }
    $scope.load();
  };

  /* -- Modals -- */

  /* -- Popover -- */

  $scope.showActionsPopover = function(event) {
    if (!$scope.actionsPopover) {
      $ionicPopover.fromTemplateUrl('plugins/es/templates/document/lookup_popover_actions.html', {
        scope: $scope
      }).then(function(popover) {
        $scope.actionsPopover = popover;
        //Cleanup the popover when we're done with it!
        $scope.$on('$destroy', function() {
          $scope.actionsPopover.remove();
        });
        $scope.actionsPopover.show(event);
      });
    }
    else {
      $scope.actionsPopover.show(event);
    }
  };

  $scope.hideActionsPopover = function() {
    if ($scope.actionsPopover) {
      $scope.actionsPopover.hide();
    }
  };

  /* -- watch events -- */

  // Watch unauth
  $scope.onUnauth = function() {
    // Reset all data
    $scope.search.results = undefined;
    $scope.search.loading = false;
    $scope.entered = false;
  };
  csWallet.api.data.on.unauth($scope, $scope.onUnauth);

  // for DEV only
  /*$timeout(function() {
    // launch default action fo DEV
   }, 900);
   */
}
<|endoftext|>


<commit_before>import debugFactory from 'debug';
import assign from 'object.assign';

const debug = debugFactory('freecc:services:hikes');

export default function hikesService(app) {
  const Challenge = app.models.Challenge;

  return {
    name: 'hikes',
    read: (req, resource, params, config, cb) => {
      const query = {
        where: { challengeType: '6' },
        order: 'difficulty ASC'
      };

      debug('params', params);
      if (params) {
        assign(query.where, {
          dashedName: { like: params.dashedName, options: 'i' }
        });
      }
      debug('query', query);
      Challenge.find(query, (err, hikes) => {
        if (err) {
          return cb(err);
        }
        cb(null, hikes);
      });
    }
  };
}
<commit_msg>Change hikes order<commit_after>import debugFactory from 'debug';
import assign from 'object.assign';

const debug = debugFactory('freecc:services:hikes');

export default function hikesService(app) {
  const Challenge = app.models.Challenge;

  return {
    name: 'hikes',
    read: (req, resource, params, config, cb) => {
      const query = {
        where: { challengeType: '6' },
        order: 'suborder ASC'
      };

      debug('params', params);
      if (params) {
        assign(query.where, {
          dashedName: { like: params.dashedName, options: 'i' }
        });
      }
      debug('query', query);
      Challenge.find(query, (err, hikes) => {
        if (err) {
          return cb(err);
        }
        cb(null, hikes);
      });
    }
  };
}
<|endoftext|>


<commit_before>var _ = require('underscore');

exports.start = function(config) {
  var started = {};
  var starting = {};

  function start(name) {
    if (started[name]) return;
    if (starting[name]) {
      throw new Error('cyclic dependencies: ' + name);
    }
    starting[name] = true;
    var service = require('./' + name);
    _.each(service.depends, function(depend) {
      start(depend);
    });
    service.start(config[name]);
    delete starting[name]
    started[name] = true;
  }

  _.each(config, function(config, name) {
    start(name);
  });
}
<commit_msg>Explicitly list services<commit_after>var _ = require('underscore');

var services = [
  'console', 'exit', 'mopidy', 'server', 'socket.io'
];

exports.start = function(config) {
  var started = {};
  var starting = {};

  function start(name) {
    if (started[name]) return;
    if (starting[name]) {
      throw new Error('cyclic dependencies: ' + name);
    }
    starting[name] = true;
    var service = require('./' + name);
    _.each(service.depends, function(depend) {
      start(depend);
    });
    service.start(config[name]);
    delete starting[name]
    started[name] = true;
  }

  _.each(services, function(name) {
    start(name);
  });
}
<|endoftext|>