var DummyFlashPlayer = {

  memo: new Array(),

  SetVariable: function (key, value) {
    this.memo.push([key, value]);
  },

  GetVariable: function (name) {
    return this[name];
  },

  LoadUp: function (player) {
    for (var i=0; i < this.memo.length; i++) {
      player.SetVariable(this.memo[i][0], this.memo[i][1]);
    }
    return player;
  }

}

Module("wrapper", "0.0.1", function(mod){
    var dom=imprt('dom');

    mod.PlayingStopped=Class(dom.Event, function(publ,priv,supr){
        publ.__init__=function(target){
            supr.__init__.call(this,"playingStopped", target);
        };
    });
    
    mod.PlayingStarted=Class(dom.Event, function(publ,priv,supr){
        publ.__init__=function(target){
            supr.__init__.call(this,"playingStarted", target);
        };
    });
    
    mod.PlayingPaused=Class(dom.Event, function(publ,priv,supr){
        publ.__init__=function(target){
            supr.__init__.call(this,"playingPaused", target);
        };
    });
    
    mod.PositionChanged=Class(dom.Event, function(publ,priv,supr){
        publ.__init__=function(target, pos){
            supr.__init__.call(this,"positionChanged", target);
            this.position = pos;
        };
    });
    
    mod.DownloadProgressChanged=Class(dom.Event, function(publ,priv,supr){
        publ.__init__=function(target, downloadProgress){
            supr.__init__.call(this,"downloadProgressChanged", target);
            this.progress = downloadProgress;
        };
    });
    
    mod.Player=Class(dom.EventTarget, function(publ,supr){
            
        publ.__init__=function(nativePlayer){
            supr.__init__.call(this);
            this.player=nativePlayer;
            this.position=0;
            this.downloadProgress=0;
            this.isPlaying=false;
        };
        
        publ.load=function(uri){};

        publ.prefetch=function(uri){};

        publ.play=function(){};
        
        publ.pause=function(){};
        
        publ.seek=function(pos){};
        
        publ.setFullscreen=function(value){};
        
        publ.setVolume=function(value){};
        
        publ.getVolume=function(value){};
        
        publ.setSize=function(w,h){
            this.player.setAttribute("height", h);
            this.player.setAttribute("width", w);
            this.player.setAttribute("style", "width:%spx;height:%spx".format(w,h));
            log("set size to %sx%s".format(w,h));
        };
            
        publ.setMute=function(value){};
        publ.getMute=function(){};

        publ.getDuration=function(){};

        publ.stop = function () {
          this.seek(0);
        };
        
        publ.update=function(){
          //if (globals.fullscreen_transition)
          //  return;

            var state=this.getStateFromPlayer();
            
            if(state=='playing'){
                if(!this.isPlaying){
                    this.isPlaying=true;
                    this.dispatchEvent(new mod.PlayingStarted(this));
                }
                var pos = this.getPositionFromPlayer();
                if(this.position != pos){
                    this.position=pos;
                    this.dispatchEvent(new mod.PositionChanged(this, pos));
                };
            }else{
                if(this.isPlaying){
                    this.isPlaying=false;
                    if(state == "paused"){
                        this.dispatchEvent(new mod.PlayingPaused(this));
                    } else if(state != "seeking") {
                        this.dispatchEvent(new mod.PlayingStopped(this));
                    }
                      //}else{
                      //if (globals.fullscreen_transition) {
                      //  alert(state);
                      //} else {
                      // this.dispatchEvent(new mod.PlayingStopped(this));
                        //}
                      //}
                }
            }

            var downloadProgress = this.getDownloadProgress();
            if(this.downloadProgress != downloadProgress){
                this.downloadProgress = downloadProgress;
                this.dispatchEvent(new mod.DownloadProgressChanged(this, downloadProgress));
            }
        };
    });
    
    mod.FlashPlayer=Class(mod.Player, function(publ,priv,supr){

        publ.getVariableDefault=function(name, dflt){
            var v = this.player.GetVariable(name) + "";
            if(typeof dflt == "number"){
                v=Number(v);
                if(isNaN(v)){
                    return dflt;
                }else{
                    return v;
                }
            }else{
                return v;
            }
        };

        publ.load = function(uri, duration){
            // log("loading: %s".format(uri))
            uri += '?bufferLength=' + duration;
            this.SetVariable('msg', 'load:'  + uri);
        };

        publ.messages = new Array();

        publ.clear_to_send2flash = false;

        publ.SetVariable = function (key, value) {

          this.messages.push(key, value);
          this.call_flash();

        };

        publ.call_flash = function () {

          if (this.clear_to_send2flash && this.messages.length) {
              this.clear_to_send2flash = false;
              var key = this.messages.shift();
              var value = this.messages.shift();
              log(key);
              log(value);
              this.player.SetVariable(key, value);
          }

        };

        publ.handle_call_from_flash = function () {
            this.clear_to_send2flash = true;
            this.call_flash();
        };

        publ.play = function(){
           this.SetVariable('msg', 'play:'); 
        };

        publ.setPlayer = function (player) {
            this.player = player;
        };
        
        publ.pause=function(){
            this.SetVariable('msg', 'pause:'); 
        };
        
        publ.seek=function(pos){
            this.SetVariable('msg', 'seek:' + pos);
            this.dispatchEvent(new mod.PositionChanged(this, pos));
        };
          
        publ.setFullscreen=function(value){
            this.SetVariable("msg","fullscreen:" + value ? 1 : 0);
        };
        
        publ.setSize=function(w,h){
          // this.SetVariable("msg","size:" + w + "x" + h);
            this.player.width = w;
            this.player.height = h;
        };
        
        publ.setVolume=function(value){
            this.SetVariable("msg", "volume:" + value);
        };
        
        publ.getVolume=function(){
            Number(this.player.GetVariable("volume"));
        };
        
        publ.getStateFromPlayer=function(){
            var state = this.player.GetVariable("playState");
            return state;
        };
        
        publ.getDuration=function(){
            return this.player.GetVariable("duration");
        };
        
        publ.getDownloadProgress=function(){
            return Number(this.player.GetVariable("currentPercentLoaded"));
        };
        
        publ.getPositionFromPlayer=function(){
            return Number(this.player.GetVariable("currentPos"));
        };
        
        publ.getMute=function(){
            return (this.player.GetVariable("mute") == "on");
        };
        
        publ.setMute=function(value){
            this.SetVariable("msg", "mute:" + (value?"on":"off"));
        };
        
    });
    
    mod.WMPlayer=Class(mod.Player, function(publ,supr){
        var StateUndefined=0;
        var StateStopped =1;
        var StatePaused=2;
        var StatePlaying=3;
        var StateScanForward=4;
        var StateScanReverse=5;
        var StateBuffering=6;
        var StateWaiting=7;
        var StateMediaEnded=8;
        var StateTransitioning=9;
        var StateReady=10;
        var StateReconnecting=11;
        
        publ.load = function(uri){
          log("loading: %s".format(uri));
            this.player.URL = uri;
        };
        
        publ.play = function(){
            // log("setting position: " + this.position);
            this.player.controls.currentPosition=this.position;
            this.player.controls.play();
        };
        
        publ.pause=function(){
           this.player.controls.pause();
           // log(this.position = this.player.controls.currentPosition);
           //todo: stop handleEventPollLoop timeout
        };

        publ.seek=function(pos){
            this.player.controls.currentPosition = pos;
            this.position = pos;
            //why the hell does WMP stop after setting the position ?!?!?!?!?!?
            if(! this.isPlaying){
                //and why doed it not seem to update the image when restting the position
                //this.player.controls.play();
                //this.player.controls.pause();
                this.player.controls.step(1);
                //we need to reset the current position again so that when
                //playing resumes it actuall renders correctly
                //maybe this is just happening on my machine though.
                //this.player.controls.currentPosition += 0.01;
            }else{
                this.player.controls.play();
            }
            this.dispatchEvent(new mod.PositionChanged(this, pos));
        };
        
        publ.setFullscreen=function(value){
            this.player.fullScreen = value;
        };
        
        publ.setVolume=function(value){
            this.player.settings.volume = value;
        };
        
        publ.getVolume=function(){
            return this.player.settings.volume;
        };
        
        publ.getStateFromPlayer=function(){
            switch(this.player.playState){
                case StatePlaying: return "playing";
                case StatePaused:return "paused";
                default: return "stopped";
            }
        };
        
        publ.getDownloadProgress=function(){
            try {
                return this.player.network.downloadProgress;
            } catch(e) {
              return 0;
            }
        };
        
        publ.getMute=function(){
            return this.player.settings.mute;
        };
        
        publ.setMute=function(value){
            this.player.settings.mute = value;
        };
        
        publ.getPositionFromPlayer=function(){
            return this.player.controls.currentPosition;
        };
        
        publ.getDuration=function(){
            return this.player.currentMedia.duration;
        };
    });
    
    mod.QTPlayer=Class(mod.Player, function(publ,supr){
        
        publ.load = function(uri){
            log("loading: %s".format(uri));
            this.player.SetResetPropertiesOnReload(false);	// james edit, added to hide controls
            this.player.SetURL(uri);
            // this.player.Play();
        };
        
        publ.prefetch = function(uri){
            // log("loading: %s".format(uri))
            this.player.SetResetPropertiesOnReload(false);	// james edit, added to hide controls
            this.player.SetURL(uri);
        };
        
        publ.play = function(){
            this.player.Play();
        };
        
        publ.pause=function(){
            this.player.Stop();
            //todo: stop handleEventPollLoop timeout
        };

        publ.seek=function(pos){
            this.player.SetTime(pos * this.player.GetTimeScale());
            this.dispatchEvent(new mod.PositionChanged(this, pos));
        };
        
        publ.setFullscreen=function(value){
            //todo: QT has no fullScreen ?!?!?!
        };
        
        
        publ.setVolume=function(value){
            this.player.SetVolume(value);
        };
        
        publ.getVolume=function(){
            return this.player.GetVolume();
        };
        
        publ.getDownloadProgress=function(){
            try{
                var p=  100 * this.player.GetMaxTimeLoaded() / this.player.GetDuration();
                if(isNaN(p)){
                    return 0;
                }else{
                    return p;
                }
            }catch(e){
                return 0;
            }
        };
        
        publ.getStateFromPlayer=function(){
            try{
                var s=this.player.GetPluginStatus();
            }catch(e){
                return "error";
            }
            if(s.indexOf("Error") >= 0){
                return "error";
            }
            switch(s){
                case "Waiting":case"Loading":case"Error" : break;
                case "Playable":case"Complete": default:
                        var r = this.player.GetRate();
                        if(r != 0){
                            return "playing";
                        }else{
                            if(this.player.GetTime() == this.player.GetDuration()){
                                return "stopped"
                            }else{
                                return "paused";
                            }
                        }
            }
        };
        
        publ.getDuration=function(){
            return this.player.GetDuration() / this.player.GetTimeScale();
        };
        
        publ.getMute=function(){
            return this.player.GetMute();
        };
        
        publ.setMute=function(value){
            this.player.SetMute(value);
        };
        
        publ.getPositionFromPlayer=function(){
            return  this.player.GetTime() / this.player.GetTimeScale();
        };
        
    });
    
    
    mod.EventPollTime=300;
    
    mod.handleEventPollLoop=function(){
        setTimeout('imprt("wrapper").handleEventPollLoop()', mod.EventPollTime);
        try{
            mod.player.update();
        }catch(e){
            log("this should not happen: " + e.message);
        }
    };
    
    mod.player;
    
    mod.createPlayer=function(choice, player){
        if (choice.indexOf("Flash") >= 0) {
          //if (choice == "Flash 8") {
            mod.player = new mod.FlashPlayer(DummyFlashPlayer);
            //} else {
            // mod.player = new mod.FlashPlayer(player);
            // }
        } else if (choice.indexOf("Quicktime") >= 0) {
            mod.player = new mod.QTPlayer(player);
        } else if (choice.indexOf("Windows Media") >= 0) {
            mod.player = new mod.WMPlayer(player);
        } else {
            throw mod.Exception("No suitable Wrapper found for plugin");
        }
        // log("created %s".format(mod.player));
        // log("starting event polling loop");
        setTimeout('imprt("wrapper").handleEventPollLoop()', mod.EventPollTime);
        return mod.player;
    };
    
    
    mod.__main__=function(){
       
    };

});
    
    
