


if (!window.PanacheSilverlightPlayerJS)
	window.PanacheSilverlightPlayerJS = {};

PanacheSilverlightPlayerJS.Scene = function() 
{
}

PanacheSilverlightPlayerJS.Scene.prototype =
{
    panacheController_ : null,
    video_ : null,
    rootElement_ : null,
    statusCanvas_ : null,
    statusText_ : null,
    sourceXMLPath_ : "",
    
    //Video controls
    videoControls_ : null,
    playBtn_ : null,
    stopBtn_ : null,
    pauseBtn_ : null,
    muteBtn_ : null,
    soundBtn_ : null,
    position_ : null,
    thumb_ : null,
    
    downloadProgress_ : null,
    border_ : null,
    content_ : null,
    draggingThumb_ : false,

    total_ : 0,
    value_ : 0,
    
    partnerID_ : 2,
    
    bPreviewMode_ : false,
    
    userContext_ : null,
    
	handleLoad: function(plugIn, userContext, rootElement) 
	{
		this.plugIn = plugIn;
		this.rootElement_ = rootElement;
		
		this.video_ = rootElement.findName("video");
		this.videoControls_ = rootElement.findName("VideoControls");
	    this.statusCanvas_ = this.rootElement_.findName("StatusCanvas");
	    this.statusText_ = this.rootElement_.findName("txtStatus");
	    this.userContext_ = userContext;
    },
    
    setPreviewMode : function(mbdd)
    {
        this.bPreviewMode_ = true;
        this.sPreviewMBDD_ = mbdd;
    },
    
    loadMBDD : function(sURL, sTemplateSetName, sTemplateKeys, opts, nPartnerID)
    {
        if (nPartnerID != null)
            this.partnerID_ = nPartnerID;
            
	    var pThis = this;
	    
	    //If using a package XML, load it in order to the determine the source MBDD name.
	    var sXMLSource = new String(opts.XMLSource);
	    if (sXMLSource.length > 0)
	    {
	        var completion = function(sTemplateSetOverride)
	        {
	            pThis.continueLoad(sURL, sURL, sTemplateSetOverride, sTemplateKeys, opts);
	        }
	        this.getMBDDURLFromXMLSource(sXMLSource, completion);
            return;
	    }
	    
	    //Not using package xml file, continue loading immediately.
	    this.continueLoad(sURL, sURL, sTemplateSetName, sTemplateKeys, opts);
	},
	
	continueLoad : function(sURL, sMBDDURL, sTemplateSetName, sTemplateKeys, opts)
	{
	    var pThis = this;
	
        this.panacheController_ = null;
	    this.panacheController_ = new Panache.Controller(this.rootElement_, this.video_, this.partnerID_, this.userContext_, opts);
        
        if (this.bPreviewMode_)
            this.panacheController_.setMBDDPreviewMode(this.sPreviewMBDD_);
            
        var readyToPlay = false;
        var videoLoaded = false;
        
        var statusCallback = function(percent)
        {
            if (percent == 100)
            {
    	        if (pThis.statusCanvas_ != null)
    	        {
    	            pThis.statusCanvas_.Visibility = "Collapsed";
		        }
		        
		        if (videoLoaded)
		        {
                    //pThis.video_.play();
		            pThis.adjustVideoControls();
		            pThis.videoStateChanged();
                }
                else
                    readyToPlay = true;
            }
            else
            {
                pThis.statusText_.Text = percent.toString() + "%";
            }
        }
        
	    if (this.statusCanvas_ != null)
	    {
	        this.statusCanvas_.Visibility = "Visible";
	        this.statusCanvas_.AddEventListener("MouseLeftButtonDown", function() 
	            {
	            } );
	    }   
        this.video_.Source = sURL;
	    this.panacheController_.loadMBDD(sMBDDURL, sTemplateSetName, sTemplateKeys, statusCallback);
	    
	        
	    this.video_.AddEventListener("MediaOpened", function(sender, e)
	        {
	            pThis.onVideoOpened();
	            

	            if (readyToPlay)
	            {
            	    //pThis.video_.play();
                    pThis.adjustVideoControls();
                    pThis.videoStateChanged();
	            }
	            else
	                videoLoaded = true;
	                
	            pThis.forceUpdateDownloadProgress();
	        }
	    );


        this.video_.AddEventListener("DownloadProgressChanged", function(sender, e)
            {
                var progress = pThis.video_.DownloadProgress * 100;

                pThis.updateDownloadProgress(progress);
            }
        );
      	    

        //This timer is used only to power the slider, not for Panache
        window.setInterval(function() {pThis.timer_tick();}, 100);

        //this.video_.play();
		
	},

    forceUpdateDownloadProgress : function(sender, args)
    {
        var progress = this.video_.DownloadProgress * 100;
        this.updateDownloadProgress(progress);
    },
    

    
    getMBDDURLFromXMLSource : function (sXMLSource, completion)
    {
        var req = null;
        
        try
        {
            req = new XMLHttpRequest(); 
        }
        catch(e)
        {
            req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
            {
                var sMBDDURL = "";
                var xml = new String(req.responseText);
                var sPrefix = "<panache";
                var fnd = xml.search(sPrefix); 
                if (fnd != -1)
                {
                    xml = xml.substr(fnd + sPrefix.length);
                    fnd = xml.search("\"");
                    if (fnd != -1)
                    {
                        xml = xml.substr(fnd + 1);
                        fnd = xml.search("\"");
                        if (fnd != -1)
                        {
                            sMBDDURL = xml.substr(0, fnd);
                        }
                    }
                }
                completion(sMBDDURL);
            }
        }

        
        req.open("GET", "relay.aspx?xmlsource=" + escape(sXMLSource), true);
        req.send(null);
        return "";        
    },
    
    onVideoOpened : function()
    {	
        with (this)
        {
            video_.Width = video_.NaturalVideoWidth;
            video_.Height = video_.NaturalVideoHeight;
            
            panacheController_.start();
//            adjustVideoControls();
//            videoStateChanged();
        }
	},
	
	timer_tick : function()
	{
        if (this.video_.NaturalDuration.Seconds != 0)
        {
            this.total_ = this.video_.NaturalDuration.Seconds;
            this.value_ = this.video_.Position.Seconds;
            this.updatePosition();
        }
	},
	
	updatePosition : function()
	{
	    if (this.border_ == null)
	        return;
	        
        var width = (this.value_ * this.border_.Width) / this.total_;
        if (width < 1)
        {
            width = 0;
        }

        this.content_.Width = width;
        
        if (!this.draggingThumb_)
            this.thumb_["Canvas.Left"] = width;

	},
	
	onSeekTo : function(position)
	{
	    var pos = this.video_.Position;
	    pos.Seconds = position;
	    this.video_.Position = pos;
	},
	
	updatePositionEx : function(position)
	{
        if (position < 0)
        {
            position = 0;
        }

        if (position > this.downloadProgress_.Width - 2)
        {
            position = this.downloadProgress_.Width - 2;
        }

        this.value_ = position * this.total_ / this.border_.Width;
        this.updatePosition();
        
        this.onSeekTo(this.value_);
	},

    updatePositionArgs : function(args)
    {	
    },
    
	adjustVideoControls : function()
	{
        var btnWidth = 26;
        var barGap = 10;
        
        with (this)
        {
            playBtn_    = videoControls_.findName("playBtn");
            stopBtn_    = videoControls_.findName("stopBtn");
            position_   = videoControls_.findName("Position");
            pauseBtn_   = videoControls_.findName("pauseBtn");
            muteBtn_    = videoControls_.findName("muteBtn");
            soundBtn_   = videoControls_.findName("soundBtn");
            thumb_      = videoControls_.findName("thumb");
            
            border_     = videoControls_.findName("Border");
            content_    = videoControls_.findName("Content");
            totalTime_  = videoControls_.findName("TotalTime");
            downloadProgress_ = videoControls_.findName("DownloadProgress");
            
            videoControls_.Visibility = "Visible";

            downloadProgress_.Cursor = "hand";
            
            videoControls_["Canvas.Top"] = video_.Height;
            var nProgressStart = stopBtn_["Canvas.Left"] + btnWidth + barGap;
            var nSoundBtnStart = video_.Width - btnWidth - 4;

            muteBtn_["Canvas.Left"] = nSoundBtnStart;
            soundBtn_["Canvas.Left"] = nSoundBtnStart;
            position_["Canvas.Left"] = nProgressStart;
            totalTime_["Canvas.Left"] = 0; //nProgressStart;
            
            var nPosWidth = nSoundBtnStart - nProgressStart - barGap;
            position_.Width = nPosWidth;

            totalTime_.Width = nPosWidth;
            
            border_.Width = nPosWidth;
            
            //Create all video control listeners
            var pThis = this;
            playBtn_.AddEventListener("MouseLeftButtonDown", function()
            {
                pThis.video_.Play();
            } );
            
            pauseBtn_.AddEventListener("MouseLeftButtonDown", function()
            {
                pThis.video_.Pause();
            } );
            
            stopBtn_.AddEventListener("MouseLeftButtonDown", function()
            {
                pThis.video_.Stop();
                pThis.playBtn_.Visibility = "visible";
                pThis.pauseBtn_.Visibility = "collapsed";
            } );
            
            video_.AddEventListener("CurrentStateChanged", function()
            {
                pThis.videoStateChanged();
            } );
            
            position_.AddEventListener("MouseLeftButtonUp", function(sender, args)
            {
                var x = args.getPosition(sender).x; 
                pThis.updatePositionEx(x);
            } );
            
            muteBtn_.AddEventListener("MouseLeftButtonDown", function(sender, args)
            {
                pThis.mute(false);
            });

            soundBtn_.AddEventListener("MouseLeftButtonDown", function(sender, args)
            {
                pThis.mute(true);
            });
            
            thumb_.AddEventListener("MouseLeftButtonDown", function(sender, args)
            {
                pThis.thumb_.captureMouse();
                pThis.draggingThumb_ = true;
            });
            
            thumb_.AddEventListener("MouseLeftButtonUp", function(sender, args)
            {
                pThis.thumb_.releaseMouseCapture();
                pThis.draggingThumb_ = false;
            });
            
            thumb_.AddEventListener("MouseMove", function(sender, args)
            {
                if (!pThis.draggingThumb_)
                    return;
                
                var offset = nProgressStart;
                var x = args.getPosition(null).x - offset;
                pThis.thumb_["Canvas.Left"] = x;
                
                if (x < 0)
                {
                    x = 0;
                    pThis.thumb_.releaseMouseCapture();
                    pThis.draggingThumb_ = false;
                }
                else if (x >= nPosWidth)
                {
                    x = nPosWidth;
                    pThis.thumb_.releaseMouseCapture();
                    pThis.draggingThumb_ = false;
                }
                pThis.updatePositionEx(x);

            });
            
            forceUpdateDownloadProgress();

        }
	},

    
    mute : function(bMute)
    {
        var vol = bMute ? 0 : 0.5;
        this.muteBtn_.Visibility = bMute ? "Visible" : "Collapsed";
        this.soundBtn_.Visibility = bMute ? "Collapsed" : "Visible";
        this.video_.Volume = vol;
    },
    
    videoStateChanged : function()
    {
        var state = this.video_.CurrentState;
        if (state == "Paused" || state=="Stopped")
        {
            this.playBtn_.Visibility = "Visible";
            this.pauseBtn_.Visibility = "Collapsed";
        }
        else
        {
            this.playBtn_.Visibility = "Collapsed";
            this.pauseBtn_.Visibility = "Visible";
        }
	},
	
	updateDownloadProgress : function(progress)
	{
	
	    if (this.downloadProgress_ == null || this.border_ == null)
	        return;

        var width = (progress * this.border_.Width) / 100;
        this.downloadProgress_.Width = width;
    
	}
 	

	
}
