// EmePlayer extends the BasePlayer player class, adding URL parsing and mediainfo support
//

Type.registerNamespace('EmePlayer');

//
// optional URL parameters
//
EmePlayer.UrlParam = {
    startTime   :   "startTime",    // specify start time for presentation on url in seconds as ...&start=5&...
    chapter     :   "chapter",      // start presentation at chapter # passed on url...&chapter=2&...
    loopCount   :   "loopCount",    // specify # of times to loop presentation on url as ...&loop=5&...  (-1 means forever)
    mediaUrl    :   "mediaUrl",     // overrides the video source passed into the script, plays this video instead
    volume      :   "volume",       // overrides starting volume
    muted       :   "muted",        // mute=true mutes volume at start
    duration    :   "duration",     // amount of time to play
    autoplay    :   "autoplay",    // auto start playing presentation (default = 1 - yes)
    mediainfo   :   "mediainfo"     // media info, URL to JScript file with function 'mediainfo' which returns a JSON array (see docs)
};


EmePlayer.Player = function(domElement) {
    EmePlayer.Player.initializeBase(this, [domElement]); 
    this._fInitialized=false;   
}
EmePlayer.Player.prototype =  {
    initialize: function() {    
        EmePlayer.Player.callBaseMethod(this, 'initialize');       
        
        // listen to URL parameters
        this.set_autoPlay( $getArgument(EmePlayer.UrlParam.autoplay, this.get_autoPlay().toString()) === "true" );
        this.set_mediaUrl( $getArgument(EmePlayer.UrlParam.mediaUrl, this.get_mediaUrl() ) );
        this.set_muted( $getArgument(EmePlayer.UrlParam.muted, this.get_muted().toString() ) === "true" );
        this.set_volume( parseFloat($getArgument(EmePlayer.UrlParam.volume, this.get_volume() )) );
        this.set_loopCount( parseInt($getArgument(EmePlayer.UrlParam.loopCount, this.get_loopCount())) );
        this.set_startTime( parseFloat($getArgument(EmePlayer.UrlParam.startTime, this.get_startTime())) );        
        this.set_mediainfo( $getArgument(EmePlayer.UrlParam.mediainfo, this.get_mediainfo()) );        
        var chapterArg = $getArgument(EmePlayer.UrlParam.chapter);
        if (chapterArg!=="") {
            this.set_currentChapter(parseInt(chapterArg));            
        }
        this.set_duration( parseFloat($getArgument(EmePlayer.UrlParam.duration, this.get_duration())) );
                
        if (this.get_mediainfo()!=="")
            this._initMediainfo();             
        
        this._fInitialized=true;
    },
    
    get_mediainfo: function () {
	return this._mediainfo;
    }, 
    set_mediainfo: function(mediainfo) {
        this._mediainfo = mediainfo;
        if (this._fInitialized)
            this._initMediainfo();
    },   
    
    _initMediainfo: function() {
        //
        // Load mediainfo from URL or is this a mediainfo JSON array or a function that returns 
        //
        if (typeof(this._mediainfo)==="string") {
            var req = new Sys.Net.WebRequest();
            req.set_url(this._mediainfo);
            req.add_completed(Function.createDelegate(this, this._loadedMediainfo));
            var executor = new Sys.Net.XMLHttpExecutor();
            req.set_executor(executor);    
            executor.executeRequest();    
            var started = executor.get_started();
        }
        else if (typeof(this._mediainfo)==="function") {
            this.set_mediaUrl( this._mediainfo().mediaUrl );
            this.set_chapters( this._mediainfo().chapters );
            this.set_placeholderImage( this._mediainfo().placeholderImage );
        }
        else if (this._mediainfo.mediaUrl!=null) {            
            this.set_mediaUrl( this._mediainfo.mediaUrl );
            this.set_chapters( this._mediainfo.chapters );
            this.set_placeholderImage( this._mediainfo.placeholderImage );            
        }
        else {
            throw Error.invalidOperation("unknown type for mediainfo");
        }        
    },
    
    _loadedMediainfo: function(executor, eventArgs) {
        if (executor.get_statusText()==="OK") {
            try {
                eval("("+executor.get_responseData()+")");
                var mediainfoJSON = mediainfo(); // call to your provided function...
                this.set_mediaUrl( mediainfoJSON.mediaUrl );
                this.set_chapters( mediainfoJSON.chapters );
                this.set_placeholderImage( mediainfoJSON.placeholderImage );                
            } catch (e) {
                throw Error.invalidOperation("problem with mediainfo");
            }
        }
    }
}
EmePlayer.Player.registerClass('EmePlayer.Player', Sys.Preview.UI.Xaml.BasePlayer);



function $getArgument(strArg, defVal) {
   var urlArgs=window.location.search.substring(1);
   var vals = urlArgs.split("&");
   var strArgLower = strArg.toLowerCase();
   for (var i=0;i<vals.length;i++) {
        var nvPair = vals[i].split("=");
        if (nvPair[0].toLowerCase() === strArgLower) {
            Sys.Debug.trace( "Parsed from URL: "+strArgLower+"="+unescape(nvPair[1]));
            return unescape(nvPair[1]);
        }
   }
   if (typeof(defVal)!=='undefined') {
        Sys.Debug.trace( "Not Parsed from URL: "+strArgLower+" using default value "+defVal);
        return defVal;
   }
   Sys.Debug.trace( 'Not Parsed from URL: '+strArgLower+' using ""');
   return "";
}

