// ExpressionPlayer extends the Sys.UI.SilverlightMedia player class, adding URL parsing and mediainfo support
//

Type.registerNamespace('ExpressionPlayer');

//
// optional URL parameters
//
ExpressionPlayer.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)
    mediaSource :   "mediaSource",  // 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)
    autocue     :   "autocue",      // cue up media on load.
    mediainfo   :   "mediainfo",    // media info, URL to JScript file with function 'mediainfo' which returns a JSON array (see docs)
    fakeoutput  :   "fakeoutput"    // used only internally, causes script to use stock output for content.
};


ExpressionPlayer.Player = function(domElement) {
    ExpressionPlayer.Player.initializeBase(this, [domElement]);    
}
ExpressionPlayer.Player.prototype =  {
    _autoCue: null,
    _fInitialized: false,
    _fakeOutput: "",
    _startButton: null,
    _tmpUrl: null,

    initialize: function() {
        ExpressionPlayer.Player.callBaseMethod(this, 'initialize');

        var content = this.get_element().content;       
         
        // listen to URL parameters
        this.set_autoPlay( $getArgument(ExpressionPlayer.UrlParam.autoplay, this.get_autoPlay().toString()) === "true" );
        this.set_autoCue( $getArgument(ExpressionPlayer.UrlParam.autocue, this.get_autoCue().toString()) === "true" );
        this.set_mediaSource( $getArgument(ExpressionPlayer.UrlParam.mediaSource, this.get_mediaSource() ) );
        this.set_muted( $getArgument(ExpressionPlayer.UrlParam.muted, this.get_muted().toString() ) === "true" );
        this.set_volume( parseFloat($getArgument(ExpressionPlayer.UrlParam.volume, this.get_volume() )) );
        this.set_position( parseFloat($getArgument(ExpressionPlayer.UrlParam.startTime, this.get_position())) );
        this.set_mediainfo( $getArgument(ExpressionPlayer.UrlParam.mediainfo, this.get_mediainfo()) );
        this.set_fakeOutput( $getArgument(ExpressionPlayer.UrlParam.fakeoutput, this.get_fakeOutput()) );
        var chapterArg = $getArgument(ExpressionPlayer.UrlParam.chapter);
        if (chapterArg!=="") {
            this.set_currentChapter(parseInt(chapterArg));
        }
        
        if (this.get_mediainfo()!=="")
            this._initMediainfo();
	            
        this._fInitialized=true;
    },
    
    set_galleryInfo : function ( galleryItems, callbackDelegate ) {
        if (this._gallery == null) {
            var galleryElement = this.get_element().content.findName( "GalleryArea" );        
            if (galleryElement!=null) {
                var galleryToggleButton = this.get_element().content.findName( "GalleryToggleButton" );
                this._gallery = new Sys.UI.Silverlight._ImageList( galleryElement, galleryToggleButton, false, callbackDelegate, this);
            }
        }        
        if (this._gallery != null) {
            this._gallery.set_items( galleryItems );
        }
    },

    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_chapters( this._mediainfo().chapters );
            this.set_placeholderImageSource( this._mediainfo().placeholderImageSource );
            this.set_mediaSource( this._mediainfo().mediaSource );
        }
        else if (this._mediainfo.mediaSource!=null) {
            this.set_chapters( this._mediainfo.chapters );
            this.set_placeholderImageSource( this._mediainfo.placeholderImageSource );
            this.set_mediaSource( this._mediainfo.mediaSource );
        }
        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_chapters( mediainfoJSON.chapters );
                this.set_placeholderImageSource( mediainfoJSON.placeholderImageSource );
                this.set_mediaSource( mediainfoJSON.mediaSource );
            } catch (e) {
                throw Error.invalidOperation("problem with mediainfo");
            }
        }
    },
    
    set_fakeOutput: function(value) {
        this._fakeOutput=unescape(value);
        if (this._fakeOutput!="") {
            this.set_mediainfo(
            { "mediaSource": this._fakeOutput+"/sl.wmv",
              "placeholderImageSource": this._fakeOutput+"/sl1.jpg",
              "chapters": [ new Sys.UI.Silverlight.MediaChapter("", 1,this._fakeOutput+"/sl1.jpg") , 
                            new Sys.UI.Silverlight.MediaChapter("", 2,this._fakeOutput+"/sl2.jpg") , 
                            new Sys.UI.Silverlight.MediaChapter("", 4,this._fakeOutput+"/sl3.jpg")  ] } 
            );            
        }
    },
    get_fakeOutput: function() {
        return this._fakeOutput;
    },

    set_timeIndex: function(value) {
	    // check for skipping past end of file and raise media ended
        if(this._mediaElement && this._canSeek && value>this._naturalduration ) {
		this._raiseEvent("mediaEnded", Sys.EventArgs.Empty);
	}
	else {
		ExpressionPlayer.Player.callBaseMethod(this, 'set_position', [value]);
	}
    }
}
ExpressionPlayer.Player._playerCount = 0;
ExpressionPlayer.Player._getUniqueName = function(baseName) {
    return baseName + ExpressionPlayer.Player._playerCount++;
}
ExpressionPlayer.Player.registerClass('ExpressionPlayer.Player',  Sys.UI.Silverlight.MediaPlayer);




ExpressionPlayer.GalleryItem = function (title, thumbnailSource) {
    this._title = title;
    this._thumbnailSource = thumbnailSource;
    ExpressionPlayer.GalleryItem.initializeBase(this);
}
ExpressionPlayer.GalleryItem.prototype = {
    get_thumbnailSource : function() {
        return this._thumbnailSource;
    },
    get_title : function () {
        return this._title;
    }
}
ExpressionPlayer.GalleryItem.registerClass("ExpressionPlayer.GalleryItem");




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) {
            return unescape(nvPair[1]);
        }
   }
   if (typeof(defVal)!=='undefined') {
        return defVal;
   }
   return "";
}


