// requires jquery

function ParticleVidPlayer(options){

    var self        = this;

    // page elements
    this.player           = options.player ? options.player : $('#player').get(0);
    this.layover          = options.layover ? options.layover : $('#control-layover').get(0);
    this.playButton       = options.playButton ? options.playButton : $('#play-button').get(0);
    this.timerNub         = options.timerNub ? options.timerNub : $('#timer-nub').get(0);
    this.scrubTimeDisplay = options.scrubTimeDisplay ? options.scrubTimeDisplay : $('#scrub-time').get(0);
    this.timerBar         = options.timerBar ? options.timerBar : $('#timer-bar').get(0);
    
    // 
    this.autoPlay         = options.autoPlay ? options.autoPlay : false;
    this.isTouchscreen    = options.isTouchscreen ? options.isTouchscreen : false;
    
    //
    this.isFlashPlayer         = false;
    this.playbackPositionTimer = false;
    this.mousePosInTime        = 0;
    this.isClicked             = false;
    this.isDraggable           = false;
    this.isDragged             = false;
    this.dragTimer             = false;
    this.waitForIntentTimer    = false;
    
    // calculate pixelsPerSecond
    this.duration = parseFloat( $(this.player).attr('time') );
    this.width = parseFloat( $(this.player).attr('width') );
    this.pixelsPerSecond = this.width / this.duration;
    
    this.initialize = function(){
        
        
        /*
        // are we using a server that can handle byte-range requests
        try
        {
            console.log('<><><> using a server that handles byte-range requests (video.seekable.end() returns a valid response: '+self.player.seekable.end(0)+')');
            //self.isSeekable = true;
        }
        catch(er)
        {
            console.log('!!!!!!!!!!!!! video.seekable.end() returns an error!!  Most like this means this server does not handle byte-range requests');
            //self.isSeekable = false;
        }
        */
    
    
        if(this.isTouchscreen) {
            //////////////////////////////////////// mouse actions
            this.layover.ontouchstart = function(e){
                e.preventDefault();
                var touch = e.touches[0];
                var node = e.target;
                self.clickTouchDown();
            }
            this.layover.ontouchmove = function(e){
                e.preventDefault();
                var touch = e.touches[0];
                var node = e.target;
                self.clickTouchMove(touch);
            }
            this.layover.ontouchend = function(e){
                e.preventDefault();
                var touch = e.touches[0];
                var node = e.target;
                self.clickTouchUp();
            }
        }else{
            this.checkForHtml5();
            
            //////////////////////////////////////// touch actions
            $(this.layover).mousedown(function(e){
                self.clickTouchDown();
                e.stopPropagation();
            });
            
            $(this.layover).mousemove(function(event){
                self.clickTouchMove(event);
            });
            
            $(this.layover).mouseup(function(e){
                self.clickTouchUp();
                e.stopPropagation();
            });
        }
        
        if(this.autoPlay){
            this.playVid();
        }
    }
    
    this.checkForHtml5 = function(){
        var v = document.createElement("video"); // Are we dealing with a browser that supports <video>? 
        if ( !v.play ) { // If no, use Flash.
          this.isFlashPlayer = true;
          var thisVid = $(this.player).children().last().attr('src');
          var flashvars = {
            src: thisVid,
            autoPlay: 0,
            vidWidth: 640,
            vidHeight: 360,
            hideControls: 1,
            pid: 1
          };
          var params = {
            allowScriptAccess: "always",
            allowFullScreen: "true",
            bgcolor: "#000000"
          };
          var attributes = {
            name: $(this.player).attr('id'),
            id: $(this.player).attr('id')
          };
          swfobject.embedSWF("/swf/discrete-v2e.swf", $(this.player).attr('id'), "640", "360", "9.0.0","/swf/expressInstall.swf", flashvars, params, attributes); 
        }else{
          this.isFlashPlayer = false;
        }
    }
    
    //////////////////////////////////////////////////
    
    this.isPlaying = function(){
        if(this.isFlashPlayer){
          var isPlaying = document.getElementById('player').isPlaying();
        }else{
          var isPlaying = this.player.paused ? false : true;
        }
        
        return isPlaying;
    }
    
    this.playVid = function(){
        if(this.isFlashPlayer){
          document.getElementById('player').playVid();
        }else{
          this.player.play();
        }
        $(this.playButton).hide();
        this.playbackPositionTracker();
    }
    
    this.pauseVid = function(){
        if(this.isFlashPlayer){
          document.getElementById('player').pauseVid();
        }else{
          this.player.pause();
        }
        $(this.playButton).show();
        clearInterval(this.playbackPositionTimer);
    }
    
    this.jumpTo = function(position){
        if(this.isFlashPlayer){
          document.getElementById('player').jumpTo(position);
        }else{
          this.player.currentTime = position;
        }
        $(this.timerNub).css({left: Math.floor(this.player.currentTime * this.pixelsPerSecond)});
    }
    
    this.playbackPositionTracker = function(){
        clearInterval(this.playbackPositionTimer);
        this.playbackPositionTimer = setInterval(function(){
            if(self.isFlashPlayer){
              var currentTimePos = document.getElementById('player').playbackPosition();
            }else{
              var currentTimePos = self.player.currentTime;
            }
            $(self.timerNub).css({left: Math.floor(currentTimePos * self.pixelsPerSecond)});
            if(self.player.ended){
              clearInterval(self.playbackPositionTimer);
            }
        }, 10);
    }
  
    //////////////////////////////////////////////////
    
    this.clickTouchDown = function(){
      this.isClicked = true;
      clearTimeout(this.waitForIntentTimer);
      this.waitForIntentTimer = setTimeout(function(){
          self.isDraggable = true;
      }, 100);
    }
    
    this.clickTouchMove = function(event){
      if(this.isClicked && this.isDraggable) {
          $(this.playButton).hide();
          this.isDragged = true;
          
          // this should happen in a setInterval when the swf is embeded and wait till swf is ready
          this.player = options.player ? options.player : $('#player').get(0);
          
          var offset = $(this.player).offset();
          var posInElement = event.pageX - offset.left;
          //$('#feedback').empty().append('posInElement='+posInElement);
          $(this.timerBar).css({left: posInElement}).show();
          $(this.scrubTimeDisplay).css({left: event.pageX - offset.left, top: event.pageY - (offset.top + 20)}).show();
          this.mousePosInTime = posInElement / this.pixelsPerSecond;
          var minutes = Math.floor( this.mousePosInTime / 60 );
          var remainderSeconds = Math.floor(this.mousePosInTime % 60);
          if(minutes > 0){
            if(remainderSeconds < 10){
              var scrubString = minutes+":0"+remainderSeconds;
            }else{
              var scrubString = minutes+":"+remainderSeconds;
            }
          }else{
            var scrubString = remainderSeconds;
          }
          $(this.scrubTimeDisplay).html(scrubString);
          
          if(this.dragTimer == false) {
            this.dragTimer = setTimeout(function(e){
              if(!self.isFlashPlayer){
                self.jumpTo(self.mousePosInTime);
              }
              self.dragTimer = false;
            }, 20);
          }
      
      }
    }
    
    this.clickTouchUp = function(){
      if(this.isDragged) {
          if( !this.isPlaying() ){
              $(this.playButton).show();
          }
          if(this.isFlashPlayer){
              this.jumpTo(this.mousePosInTime);
          }
          $(this.timerBar).hide();
          $(this.scrubTimeDisplay).hide();
      }else{
          if( this.isPlaying() ) {
            
            this.pauseVid();
          }else{
            this.playVid();
          }
      }
      clearTimeout(this.waitForIntentTimer);
      this.waitForIntentTimer = false;
      this.isClicked = false;
      this.isDraggable = false;
      this.isDragged = false;
    }
    
}
