function handleLoad(sender, args) {	
	eval("var initparams = {"+sender.getHost().initParams+"}");
	sl_player = new SilverLightPlayer(sender);
	sl_initialized=true;
	console.log("handleLoad: in silverlight load event");
	if(typeof bam=="object" && typeof bam.media=="object"){console.log("handleLoad: in silverlight load event --- before bam.media.silverLightOnLoad"); bam.media.silverLightOnLoad(sl_player); }
	try{
		silverlight_presence_check();
	}catch(e){}
}
//hookups to flash
function get_media_vars(){
	var m = sl_player.mediaElement;
	thisMovie("controls").set_controller_vars(m.currentState,m.naturalDuration.seconds,m.position.seconds,m.volume,"","");
}


var sl_initialized = false;

function silverlight_presence_check(){
		if (sl_initialized){
			thisMovie("controls").silverlight_init_callback();
		}
}

function thisMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function restart_media(){
	sl_player.restart();
}

function handle_play_btn(){
	sl_player.play();
}

function handle_pause_btn(){
	sl_player.pause();
}

function set_video_scale(val){
	sl_player.setScale(val);
}

function set_video_y(newy){
	sl_player.set_media_y(newy);
}

function set_video_x(newx){
	sl_player.set_media_x(newx);
}


function get_video_scale(){
	sl_player.get_video_scale();
}

function seek(seektime){
	sl_player.seekTo(seektime);
}

function set_volume(newvolume){
	sl_player.setVolume(newvolume);
}

//end hookups to flash

function SilverLightPlayer(wpfeControl) {
	this.wpfeControl = wpfeControl;
	
	this.rootCanvas = wpfeControl.findName("Root");
	this.mediaElementArray = [ wpfeControl.findName("MediaElement1"), wpfeControl.findName("MediaElement2") ];
	this.mediaScale = wpfeControl.findName("mediascale");
	
	this.video_width = 630;
	this.video_height= 360;
	
	this.cancel_fullscreen_scale="regular";
	
	this.isDraggingPlayhead = false;
	this.isDraggingVolume = false;
	this.interval = 250;
	this.downloadProgress = 0;
	this.onClose = null;
	this.kill_timer = false;
	this.mouse_seek_val = 0;
	this.newscale=1;
	this.c_scale = 1;
	this.controls_timeout_i;
	this.controls_timeout = 5;

	this.startTime = 0;
	this.endTime = 0;
	this.hasAd = false;
	this.div_id = "MLBPlayer_SLPWrapper";
	this.parent_div = document.getElementById(this.div_id);
	this.getSilverlightElements(wpfeControl);
	this.setCallbacks();

	this.initMediaElement = function(mElement){
		setCallback(mElement, "bufferingProgressChanged", delegate(this, this.handleDownloadProgressChanged));
		setCallback(mElement, "downloadProgressChanged", delegate(this, this.handleDownloadProgressChanged));
		setCallback(mElement, "MediaOpened", delegate(this, this.handleMediaOpened));
		setCallback(mElement, "MediaEnded", delegate(this, this.handleMediaEnded));	
		setCallback(mElement, "MediaFailed", delegate(this, this.handleMediaFailed));
		setCallback(mElement, "MarkerReached", delegate(this, this.handleMarkerReached));
		//mElement.autoPlay="false";
		this.setVolume(mElement.volume);
	}

	this.mediaElementArray = [ wpfeControl.findName("MediaElement1"), wpfeControl.findName("MediaElement2") ];
	this.initMediaElement(this.mediaElementArray[0]);
	this.initMediaElement(this.mediaElementArray[1]);
	this.mediaElementArray[0].autoPlay="true";
	this.mediaElementArray[1].autoPlay="false";

	this.show_controls();
	this.scale="standard";
	this.adButton.Visibility = "Collapsed";
}

SilverLightPlayer.prototype.getSilverlightElements = function(wpfeControl){
	
	this.master = wpfeControl.findName("Master");
	this.letterbox = wpfeControl.findName("Letterbox");
	this.controlRoot = wpfeControl.findName("Controls");
	this.controlsBg = wpfeControl.findName("ControlsBg");
	this.controlScale = wpfeControl.findName("controlscale");
	this.mediaElement = this.setMediaElement();
	this.playhead = wpfeControl.findName("Playhead");
	this.playControls = wpfeControl.findName("PlayControls");
	this.root = wpfeControl.findName("Root");
	this.timeText = wpfeControl.findName("TimeText");
	this.toBeLoadedPath = wpfeControl.findName("ToBeLoadedPath");
	this.loadedPath = wpfeControl.findName("LoadedPath");
	this.playheadTrail = wpfeControl.findName("PlayheadTrail");
	this.smallPlayButton = wpfeControl.findName("smallPlayButton");
	this.smallPauseButton = wpfeControl.findName("smallPauseButton");
	this.smallPlayButtonLeft = this.smallPlayButton["canvas.left"];
	this.backButton = wpfeControl.findName("backButton");
	this.volumeControl = wpfeControl.findName("VolumeControl");
	this.volumeBar = wpfeControl.findName("VolumeBar");
	this.controlBlocker = wpfeControl.findName("ControlBlocker");
	this.loadingBg = wpfeControl.findName("LoadingBg");
	this.loadingGraphic = wpfeControl.findName("LoadingGraphic");
	this.loadingMessage = wpfeControl.findName("LoadingMessage");
	
	//scale controls
	this.scaleControls = wpfeControl.findName("ScaleControls");
	this.fullScreenButton = wpfeControl.findName("FullScreenButton");
	this.miniScreenButton = wpfeControl.findName("MiniScreenButton");
	this.standardScreenButton = wpfeControl.findName("StandardScreenButton");
	this.mouseGrabber = wpfeControl.findName("MouseGrabber");
	
	//instream ad
	this.adText = wpfeControl.findName("AdText");
	this.adButton = wpfeControl.findName("AdButton");
	this.adButtonStroke = wpfeControl.findName("AdButtonStroke");
	this.adButtonBg = wpfeControl.findName("AdButtonBg");
}

SilverLightPlayer.prototype.setCallbacks = function(){
	
	//playhead
	setCallback(this.playControls, "mouseLeftButtonDown", delegate(this, this.handlePlayheadPress));
	setCallback(this.playControls, "mouseLeftButtonUp", delegate(this, this.handlePlayheadRelease));
	setCallback(this.playControls, "mouseMove", delegate(this, this.handlePlayheadDrag));
	
	//volume
	setCallback(this.volumeControl, "mouseLeftButtonDown", delegate(this, this.handleVolumePress));
	setCallback(this.volumeControl, "mouseLeftButtonUp", delegate(this, this.handleVolumeRelease));
	setCallback(this.volumeControl, "mouseMove", delegate(this, this.handleVolumeDrag));
	
	// play pause restart buttons
	setCallback(this.smallPauseButton, "mouseLeftButtonUp", delegate(this, this.pause));
	setCallback(this.smallPlayButton, "mouseLeftButtonUp", delegate(this, this.play));
	setCallback(this.backButton, "mouseLeftButtonUp", delegate(this, this.handleRestartButtonPress));
	
	//scaleControls	
	setCallback(this.fullScreenButton, "mouseLeftButtonUp", delegate(this, this.set_scale_full));
	setCallback(this.miniScreenButton, "mouseLeftButtonUp", delegate(this, this.set_scale_mini));
	setCallback(this.standardScreenButton, "mouseLeftButtonUp", delegate(this, this.set_scale_standard));
	setCallback(this.standardScreenButton, "mouseEnter", delegate(this, this.handle_standard_rollover));
	setCallback(this.standardScreenButton, "mouseLeave", delegate(this, this.handle_standard_rollout));
	setCallback(this.fullScreenButton, "mouseEnter", delegate(this, this.handle_full_rollover));
	setCallback(this.fullScreenButton, "mouseLeave", delegate(this, this.handle_full_rollout));
	setCallback(this.miniScreenButton, "mouseEnter", delegate(this, this.handle_mini_rollover));
	setCallback(this.miniScreenButton, "mouseLeave", delegate(this, this.handle_mini_rollout));
	
	setCallback(this.mouseGrabber, "MouseEnter", delegate(this, this.show_controls));
	setCallback(this.mouseGrabber, "MouseMove", delegate(this, this.show_controls));
	
	//adbutton 
	setCallback(this.adButton, "MouseEnter", delegate(this, this.handleInStreamAdMouseOver));
	setCallback(this.adButton, "MouseLeave", delegate(this, this.handleInStreamAdMouseOut));
	setCallback(this.adButton, "mouseLeftButtonUp", delegate(this, this.handleInStreamAdClick));
}


SilverLightPlayer.prototype.setMediaElement = function() {
	var mElement = this.mediaElementArray[0];
	
	this.mediaElementArray[1].visibility = "Collapsed";
	this.mediaElementArray[1].stop();
	mElement.stop();
	mElement.visibility = "Visible";
	return mElement;
}

SilverLightPlayer.prototype.getScale = function(val) {
	thisMovie("controls").get_sl_media_scale(this.mediaScale.scaleX,this.mediaScale.scaleY);
}

//send debug output to flash debugger
SilverLightPlayer.prototype.debug = function(msg) {
	try {
		thisMovie("controls").debuglog(msg);
	} catch(e){
		//flash not available yet...
	};
}

SilverLightPlayer.prototype.setScale = function(val) {
	//console.log("   > setScale : "+val);
	if (!isNaN(val)){
		this.mediaScale.scaleX = val;
		this.mediaScale.scaleY = val;
		this.parent_div.style.width = Math.round(this.video_width*val)+"px";
		this.parent_div.style.height = Math.round(this.video_height*val)+"px";
		this.c_scale = (val < 1) ? val : 1 ;
		this.controlScale.scaleX = this.c_scale;
		this.controlScale.scaleY = this.c_scale;
		this.controlRoot["canvas.left"] = ((this.video_width*val) - this.controlsBg.width* this.c_scale)/2;
		this.controlRoot["canvas.top"] = ((this.video_height*val) - this.controlsBg.height*this.c_scale)-5;
		this.loadingBg.width = Math.round(this.video_width*val);
		this.loadingBg.height = Math.round(this.video_height*val);
		this.loadingGraphic["canvas.left"] = Math.round((Math.round(this.video_width*val)- this.loadingGraphic.width)/2);
		this.loadingGraphic["canvas.top"] = Math.round((Math.round(this.video_height*val) - this.loadingGraphic.height)/2);
		
		//this.adTextBg.width = Math.round(this.video_width*val);
		this.adButton["canvas.left"] = Math.round((Math.round(this.video_width*val) - this.adText.actualwidth) / 2);
		this.adButton["canvas.top"] = Math.round((Math.round(this.video_height*val) - this.adText.actualheight) / 2);
		this.adButtonInitialX = this.adButton["canvas.left"]; //for use later when val is outta scope

	}
}


SilverLightPlayer.prototype.showFromWrapper = function (){
	
}

SilverLightPlayer.prototype.hideFromWrapper = function (){
	
}

SilverLightPlayer.prototype.get_video_scale = function() {
	thisMovie("controls").set_scale_full();
}

/////////////////////////////////////////////
//transport handlers

SilverLightPlayer.prototype.stop = function(sender,args) {
	this.refreshPlayTime();
	this.mediaElement.stop();
}

SilverLightPlayer.prototype.play = function(sender,args) {
	this.mediaElement.play();
	this.setPlayPauseBtn("playing");
	this.startControlInterval();
}

SilverLightPlayer.prototype.set_media_src = function(src_url) {
	this.debug("JS --> setting media src: "+src_url);
	this.mediaElement = this.setMediaElement(); //reset default mediaElement
	var o = ( arguments.length>1 &&  typeof arguments[1]=="object" ) ? arguments[1] : {};
	//var theMediaUrl = SilverLightPlayer.parseASX(src_url);
	if(o["startTime"]){ this.startTime = o.startTime; }
	if(o["endTime"]){ this.endTime = o.endTime; }
	if(o["adUrl"]){
		//var theAdUrl = SilverLightPlayer.parseASX(o.adUrl);
		this.hasAd = true;
		this.controlBlocker.visibility = "Visible";
		this.mediaElement.source = o["adUrl"]; //set ad pre-roll
		this.mediaElementArray[1].source = src_url; //set main stream
	}
	else{
		this.hasAd = false;
		this.mediaElement.source = src_url;
	}
	if (mlbMediaUtils.currentMediaMeta.w_id) { this.mymediaID = mlbMediaUtils.currentMediaMeta.w_id; }
	else if (mlbMediaUtils.currentMediaMeta.id) { this.mymediaID = mlbMediaUtils.currentMediaMeta.id; }
	console.log("mymediaID: " + this.mymediaID);
	this.play();
}

SilverLightPlayer.prototype.restart = function(){
	this.seekTo(0);
	this.play();
	this.cleanInStreamStuff();
}

SilverLightPlayer.prototype.seekTo = function(seconds) {
	var position = this.mediaElement.position;
	position.seconds = seconds;
	this.mediaElement.position = position;
	this.cleanInStreamStuff();
}

SilverLightPlayer.prototype.pause = function() {
	this.mediaElement.pause();
	this.setPlayPauseBtn("paused");
}

SilverLightPlayer.prototype.setPlayPauseBtn = function(mode) {
	if (mode=="playing"){
		this.smallPlayButton["canvas.left"]=2000;
		this.smallPauseButton["canvas.left"]=this.smallPlayButtonLeft;
	} else if (mode=="paused"){
		this.smallPauseButton["canvas.left"]=2000;
		this.smallPlayButton["canvas.left"]=this.smallPlayButtonLeft;
	}
}

SilverLightPlayer.prototype.handleDownloadProgressChanged = function(sender, eventArgs) {
	this.refreshPlayTime();
}

SilverLightPlayer.prototype.setStartTime = function(sender, seconds){
	var position = sender.position;
	position.seconds = seconds;
	sender.position = position;	
}

SilverLightPlayer.prototype.setEndTime = function(sender, seconds){
	var hrs  = 0,
		mins = 0,
		secs = seconds;
	if(secs > 3600) {
		while(true) {
			hrs ++;
			secs = secs - 3600;
			if(secs < 3600) { break; }
		}
	}
	if(secs > 60) {
		while(true) {
			mins ++;
			secs = secs - 60;
			if(secs < 60) { break; }						
		}
	}
	var timeStr = hrs + ":" + mins + ":" + secs;
	var marker = sender.getHost().content.createFromXaml("<TimelineMarker Time='" + timeStr + "' Type='SilverLightPlayer.EndTime' Text='end' />");
	sender.markers.add(marker);	
}

SilverLightPlayer.prototype.handleMediaOpened = function(sender, eventArgs){
	var isOnlyStream = (!this.hasAd && sender.getValue("Name")=="MediaElement1") ? true : false,
		 endTimeOffset = 0;
	if(this.startTime!=0 && isOnlyStream){
		endTimeOffset = this.startTime;
		this.setStartTime(sender, this.startTime);
		this.startTime = 0;
	}
	if(this.endTime!=0 && isOnlyStream){
		if(endTimeOffset!=0) this.endTime = parseInt(this.endTime) + parseInt(endTimeOffset);
		this.setEndTime(sender, this.endTime);
		this.endTime = 0;
	}
}

SilverLightPlayer.prototype.handleMediaEnded = function(sender, eventArgs) {
	var isOnlyStream = (!this.hasAd && sender.getValue("Name")=="MediaElement1") ? true : false,
		 endTimeOffset = 0;
	this.seekTo(0);
	this.pause();
	this.cleanInStreamStuff();
	this.setPlayPauseBtn("paused");
	if(!isOnlyStream){
		if(this.mediaElementArray[1].source!=""){
			this.mediaElement.visibility = "Collapsed";
			this.controlBlocker.visibility = "Collapsed";
			this.mediaElement = this.mediaElementArray[1];
			this.mediaElement.visibility = "Visible";
			if(this.startTime!=0){
				endTimeOffset = this.startTime;
				this.setStartTime(this.mediaElementArray[1], this.startTime);
				this.startTime = 0;
			}
			if(this.endTime!=0){
				if(endTimeOffset!=0) this.endTime = parseInt(this.endTime) + parseInt(endTimeOffset);
				this.setEndTime(this.mediaElementArray[1], this.endTime);
				this.endTime = 0;
			}
			this.mediaElement.play();
		}
	}
}

SilverLightPlayer.prototype.handleMediaFailed = function(sender, eventArgs) {
	this.stopControlInterval();
	this.timeText.text="Error";
	if( this.hasAd && sender.getValue("Name")=="MediaElement1" ){this.handleMediaEnded;}
}

SilverLightPlayer.prototype.convertBigEndian =  function (instring){
    var i=0;
    var retstring = "";
    
    while ( i < instring.length)
        {
        retstring += String.fromCharCode(instring.charCodeAt(i)/256);
        i++;
        }
    return unescape(retstring);
}

SilverLightPlayer.prototype.handleMarkerReached = function(sender, markerEventArgs){ 
	var marker_text;
	if (markerEventArgs.marker.text.charCodeAt(0)>256){
		marker_text = unescape(this.convertBigEndian(markerEventArgs.marker.text));
	} else {
		marker_text = unescape(markerEventArgs.marker.text);
	}
	console.log(markerEventArgs.marker.time.seconds.toString() + ": " + markerEventArgs.marker.type + " - " + marker_text);
	thisMovie("controls").send_marker(markerEventArgs.marker.time.seconds.toString(),markerEventArgs.marker.type,marker_text);
	if(markerEventArgs.marker.type){
		try {
			if(typeof(markerEventArgs.marker.text) == "string") {
				this.inStreamAdObject = eval("new Object(" + marker_text + ")");				
			}
		} catch (e) {
		};

		switch(markerEventArgs.marker.type){
			case "SilverLightPlayer.EndTime": sender.stop(); this.handleMediaEnded(sender); break;
			case "URL":
				try{
					//hack for now til type is correct
					//if(typeof(this.inStreamAdObject) == "object") { this.handleInStreamAdTracking(); }
					//else {
						if(markerEventArgs.marker.text.indexOf("http://")>-1){
							console.log("attempt to fire URL type marker");
							document.getElementById("wmpEventFrame").src=markerEventArgs.marker.text;
						}
					//}
				} 
				catch(e){
				}; 
				break;
			case "TRACK":
				if(typeof(this.inStreamAdObject) == "object") { this.handleInStreamAdTracking(); }
				break;
			default: break;
		}
	}
}

SilverLightPlayer.prototype.handleInStreamAdTracking = function() {
	console.log("in handle instream tracking");
	var btnWidth;
	var mymediaID = null;
	//fire initial url set for omniture
	if (this.inStreamAdObject.urls) {
		for(var i = 0; i < this.inStreamAdObject.urls.length; i++) {
			console.log("tracking: " + this.inStreamAdObject.urls[i]);
			if (mlbMediaUtils.currentMediaMeta.w_id) { mymediaID = mlbMediaUtils.currentMediaMeta.w_id; }
			else if (mlbMediaUtils.currentMediaMeta.id) { mymediaID = mlbMediaUtils.currentMediaMeta.id; }
			console.log("mymediaID: " + mymediaID);
			//send tracking into flash cuz bam.tracking isn't capable of switching suites/scope
			thisMovie("controls").track_ad_provision(this.inStreamAdObject.urls[i], this.mymediaID);
		}
	}
	//fire initial 3rd party url set via px trackage
	if (this.inStreamAdObject.thirdparty_urls) {
		for(i = 0; i < this.inStreamAdObject.thirdparty_urls.length; i++) {
			console.log("tracking 3rd party impressions: " + this.inStreamAdObject.thirdparty_urls[i]);
			document.getElementById("wmpEventFrame").src = this.inStreamAdObject.thirdparty_urls[i];
		}
	}
	//assign click action to message
	console.log("cmd: " + this.inStreamAdObject.cmd);
	switch(this.inStreamAdObject.cmd) {
		case "ad_start": case "ad_mid": 
			//display overlay message, center aligned
			if (this.inStreamAdObject.msg) {
				if(this.inStreamAdObject.msg.length > 0) {
					this.adText.Text = unescape(this.inStreamAdObject.msg);
					btnWidth = (this.adText.actualwidth > 100) ? Math.round(this.adText.actualwidth + 20) : 110;
					this.adButton["canvas.left"] = Math.round(this.video_width/2) - (btnWidth / 2);
					this.adButtonStroke.width = btnWidth;
					this.adButtonBg.width = btnWidth;
					this.hasInStreamAd = true;
					this.show_controls();
				}	
			}
			break;
		case "ad_end": case "ad_clear":
			this.cleanInStreamStuff();
			//anything else?
			break;
		default: 
			this.cleanInStreamStuff();
			break;
	}
	
	//track mouse movement
	
}

SilverLightPlayer.prototype.handleInStreamAdClick = function() {
	if(this.inStreamAdObject.msg_trackclick) {
		console.log("tracking click: " + this.inStreamAdObject.msg_trackclick);
		thisMovie("controls").track_ad_provision(this.inStreamAdObject.msg_trackclick, this.mymediaID);
	}
	if(this.inStreamAdObject.msg_url) {
		void(window.open(this.inStreamAdObject.msg_url));
	}
}

SilverLightPlayer.prototype.handleInStreamAdMouseOver = function () {
	if(this.inStreamAdObject.msg_trackover) {
		console.log("tracking over: " + this.inStreamAdObject.msg_trackover);
		thisMovie("controls").track_ad_provision(this.inStreamAdObject.msg_trackover, this.mymediaID);
	}	
	this.adButton.opacity = "1.0";
	this.adButtonStroke.strokeThickness = "3";
	this.adButtonStroke.width = this.adButtonStroke.width + 3;
}

SilverLightPlayer.prototype.handleInStreamAdMouseOut = function () {
	if(this.inStreamAdObject.msg_trackout) {
		console.log("tracking out: " + this.inStreamAdObject.msg_trackout);
		thisMovie("controls").track_ad_provision(this.inStreamAdObject.msg_trackout, this.mymediaID);
	}	
	this.adButton.opacity = "0.5";
	this.adButtonStroke.strokeThickness = "1";
	this.adButtonStroke.width = this.adButtonStroke.width - 3;
}

SilverLightPlayer.prototype.cleanInStreamStuff = function () {
	console.log("cleanInStreamStuff");
	this.adText.Text = " ";
	this.adButton.visibility = "Collapsed";
	this.inStreamAdObject = null;
	this.hasInStreamAd = false;
}

SilverLightPlayer.prototype.set_media_x = function(newx) {
	//this.rootCanvas["canvas.left"] = newx;
	if (!isNaN(newx)){
		this.parent_div.style.left = Math.round(newx)+"px";
	}
}

SilverLightPlayer.prototype.set_media_y = function(newy) {
  // this.rootCanvas["canvas.top"] = newy;
  if (!isNaN(newy)){
  	this.parent_div.style.top = Math.round(newy)+"px";
  }
}


//////////////////////////////////////////
//scrubber handlers

SilverLightPlayer.prototype.handlePlayheadPress = function(sender, eventArgs) {
	thisMovie("controls").reset_chyron();
	this.stopControlInterval();
	this.mediaElement.pause();
	this.isDraggingPlayhead = true;
	this.playControls.captureMouse();
	var newx = (eventArgs.getPosition(null).x/this.c_scale) - this.playControls["canvas.left"] - this.controlRoot["canvas.left"];
	if (!isNaN(newx)){
		this.seekFromMouse(newx);
	}}


SilverLightPlayer.prototype.handlePlayheadRelease = function() {
	this.isDraggingPlayhead = false;
	this.playControls.releaseMouseCapture();
	this.seekTo(this.mouse_seek_val);
	this.play();
}

SilverLightPlayer.prototype.handlePlayheadDrag = function(sender, eventArgs) {
	if (this.isDraggingPlayhead) {
		var newx = (eventArgs.getPosition(null).x/this.c_scale) - this.playControls["canvas.left"] - this.controlRoot["canvas.left"];
		if (!isNaN(newx)){
			this.seekFromMouse(newx);
		}
	}
}

//////////////////////////////////////////
//volume handlers
SilverLightPlayer.prototype.handleVolumePress = function(sender, eventArgs) {
	this.isDraggingVolume = true;
	this.volumeControl.captureMouse();
	this.setVolumeFromMouse((eventArgs.getPosition(null).x/this.c_scale) - this.volumeControl["canvas.left"] - this.controlRoot["canvas.left"]);
}

SilverLightPlayer.prototype.handleVolumeRelease = function() {
	this.isDraggingVolume = false;
	this.volumeControl.releaseMouseCapture();
}

SilverLightPlayer.prototype.handleVolumeDrag = function(sender, eventArgs) {
	if (this.isDraggingVolume) {
		this.setVolumeFromMouse((eventArgs.getPosition(null).x/this.c_scale) - this.volumeControl["canvas.left"] - this.controlRoot["canvas.left"]);
	}
}

SilverLightPlayer.prototype.setVolumeFromMouse = function(newx) {
	if (newx>this.volumeControl.width){
		newx=this.volumeControl.width;
	} else if (newx<0){
		newx = 0;
	}
	this.setVolume(newx/this.volumeControl.width);
}

SilverLightPlayer.prototype.setVolume = function(newvolume) {
	this.mediaElement.volume = newvolume;
	this.volumeBar.width = newvolume*this.volumeControl.width;
}


/////////////////////////////////////////////
//transport handlers

SilverLightPlayer.prototype.handleInterval = function() {
		this.refreshPlayTime();
}

SilverLightPlayer.prototype.startControlInterval = function(){
	this.controls_running = true;
	window.clearInterval(this.timer);
	this.timer = window.setInterval(delegate(this, this.handleInterval), this.interval);
}

SilverLightPlayer.prototype.stopControlInterval = function(){
	this.controls_running = false;
	window.clearInterval(this.timer);
}

SilverLightPlayer.prototype.refreshPlayTime = function() {
	try{
		//move the playhead
		var currentPosition = 0;
		var position = this.mediaElement.position;
		if (position != null){
			currentPosition = position.seconds;
			this.updatePlayhead(currentPosition);
		}
		
		//Set the state textfield
		if (this.mediaElement.currentState == "Playing" || this.mediaElement.currentState == "Paused"){
			this.timeText.Text = this.formatTime(currentPosition * 1000)+" | "+this.formatTime(this.mediaElement.naturalDuration.seconds * 1000);
			this.loadingMessage.visibility = "Collapsed";
			if(this.mediaElement.currentState == "Playing"){
				this.setPlayPauseBtn("playing");
			}
		} else if (this.mediaElement.currentState=="Buffering"){
			this.timeText.Text = "Buffering";
			this.loadingMessage.visibility = "Visible";
		} else {
			this.timeText.Text = this.mediaElement.currentState;
			this.loadingMessage.visibility = "Visible";
		}
	} catch(e){};
	
}

SilverLightPlayer.prototype.updatePlayhead = function(time) {
	if (isNaN(time)){
		return;
	}
	var offset = 0;
	
	var naturalDuration = this.mediaElement.naturalDuration;
	
	if ((naturalDuration != null) && (naturalDuration.seconds != 0))
	{
		var mediaDuration = naturalDuration.seconds;
		var percent = time / mediaDuration;
		var playheadWidth = this.playhead.width;
		var playAreaWidth = this.toBeLoadedPath.width;
		offset = (playAreaWidth-playheadWidth) * percent;
		this.playhead["canvas.left"] = offset;
		this.playheadTrail.width = offset+(playheadWidth/2);
	}
}

SilverLightPlayer.prototype.handleRestartButtonPress = function(){
	this.seekTo(0);
	this.play();
}

SilverLightPlayer.prototype.seekFromMouse = function(mousePosX) {
	
	var mediaDuration = this.mediaElement.naturalDuration.seconds;
	var playheadWidth = this.playhead.width;
	var playAreaWidth = this.toBeLoadedPath.width - playheadWidth;
	
	var currentPlayTime = (mousePosX - (playheadWidth / 2)) / playAreaWidth * mediaDuration;
	
	if (currentPlayTime > mediaDuration){
		currentPlayTime = mediaDuration;
	} else if (currentPlayTime < 0 || isNaN(currentPlayTime)) {
		return;
	}
	this.mouse_seek_val = currentPlayTime;
	
	this.updatePlayhead(currentPlayTime);
	
}

SilverLightPlayer.prototype.updateDownloadProgress = function() {
	this.loadedPath.width = this.toBeLoadedPath.width * this.mediaElement.downloadProgress;
}

SilverLightPlayer.prototype.formatTime = function(time) {
	
	var hours = Math.floor(time / 3600000);
	var minutes = Math.floor(time / 60000) - ( (isNaN(hours))? 0 : hours * 60 );
	var seconds = Math.floor(time / 1000.0) % 60;
	
	var timeString = (!isNaN(hours) && hours > 0) ? hours + ":" : "" ;
	timeString += (minutes < 10) ? "0"+minutes + ":" : minutes+":" ;
	timeString += (seconds < 10) ? "0"+seconds : seconds ;
	return timeString;
}

SilverLightPlayer.prototype.show_controls = function() {
  this.controlRoot.visibility = "Visible";
  this.scaleControls.visibility = "Visible";
  if (this.hasInStreamAd) { this.adButton.visibility = "Visible"; }
  clearInterval(this.controls_timeout_i);
  this.controls_timeout_i = setInterval(delegate(this, this.hide_controls),this.controls_timeout*1000);
  if (!this.controls_running){
  	this.startControlInterval();
  }
}


SilverLightPlayer.prototype.hide_controls = function() {
  this.controlRoot.visibility = "Collapsed";
  this.scaleControls.visibility = "Collapsed";
  if (this.hasInStreamAd) { this.adButton.visibility = "Collapsed"; }
  clearInterval(this.controls_timeout_i);
  this.stopControlInterval();
}

SilverLightPlayer.prototype.onFullScreenChanged = function(sender, args){
    var silverlightPlugin = sender.getHost();
    this.master["canvas.top"]=0;
	this.master["canvas.left"]=0;
	this.letterbox.width = silverlightPlugin.content.actualWidth;
	this.letterbox.height = silverlightPlugin.content.actualHeight;
    if (silverlightPlugin.content.fullScreen == true){
		var new_xscale= silverlightPlugin.content.actualWidth / this.video_width;
		var new_yscale= silverlightPlugin.content.actualHeight / this.video_height;		
		if (new_xscale < new_yscale ){
			this.master["canvas.top"] = (silverlightPlugin.content.actualHeight - Math.round(this.video_height*new_xscale))/2;
			this.setScale(new_xscale);
		} else {
			this.master["canvas.left"] = (silverlightPlugin.content.actualWidth - Math.round(this.video_width*new_yscale))/2;
			this.setScale(new_yscale);
		}
    } else {
		this.set_scale(this.cancel_fullscreen_scale);
	}
}

SilverLightPlayer.prototype.set_scale_full = function(sender,args) {
	var silverlightPlugin = sender.getHost();
	silverlightPlugin.content.onfullScreenChange = delegate(this, this.onFullScreenChanged);
    silverlightPlugin.content.fullScreen = true;  
	this.set_scale("large");
}

SilverLightPlayer.prototype.set_scale_mini = function(sender,args) {
	var silverlightPlugin = sender.getHost();
	this.set_scale("mini");
    silverlightPlugin.content.fullScreen = false; 
}

SilverLightPlayer.prototype.set_scale_standard = function(sender,args) {
	var silverlightPlugin = sender.getHost();
	this.set_scale("regular");
    silverlightPlugin.content.fullScreen = false; 
}

SilverLightPlayer.prototype.handle_full_rollover = function() {
	if (this.scale != "full"){
		this.fullScreenButton.opacity = "1";
	}
}

SilverLightPlayer.prototype.handle_full_rollout = function() {
	if (this.scale != "full"){
		this.fullScreenButton.opacity = "0.5";
	}
}

SilverLightPlayer.prototype.handle_mini_rollover = function() {
	if (this.scale != "mini"){
		this.miniScreenButton.opacity = "1";
	}
}

SilverLightPlayer.prototype.handle_mini_rollout = function() {
	if (this.scale != "mini"){
		this.miniScreenButton.opacity = "0.5";
	}
}

SilverLightPlayer.prototype.handle_standard_rollover = function() {
	if (this.scale != "standard"){
		this.standardScreenButton.opacity = "1";
	}
}

SilverLightPlayer.prototype.handle_standard_rollout = function() {
	if (this.scale != "standard"){
		this.standardScreenButton.opacity = "0.5";
	}
}


SilverLightPlayer.prototype.set_scale = function($which_scale) {
	console.log("   > set_scale:"+$which_scale);
	var on_val = "1"
	var off_val = "0.5"
	switch($which_scale){
		case "large":
			this.scale="full";
			this.fullScreenButton.opacity = on_val;
			this.miniScreenButton.opacity = off_val;
			this.standardScreenButton.opacity = off_val;
			break;
		case "mini":
			this.scale="mini";
			this.cancel_fullscreen_scale="mini";
			this.fullScreenButton.opacity = off_val;
			this.miniScreenButton.opacity = on_val;
			this.standardScreenButton.opacity = off_val;
			break;
		case "regular":
			this.scale="standard";
			this.cancel_fullscreen_scale="regular";
			this.fullScreenButton.opacity = off_val;
			this.miniScreenButton.opacity = off_val;
			this.standardScreenButton.opacity = on_val;
			break;
			
	}
	thisMovie("controls").set_scale($which_scale);
	console.log("   > flash called");
}

SilverLightPlayer.parseASX = function(url){}

/// Helper method for creating per-object callbacks
/// @param target object to invoke the callback on
/// @param callback method to be called on the object
function delegate(target, callback) {
	var func = function() {
		callback.apply(target, arguments);
	}
	return func;
}

/// Hook up the specified event to the specified delegate.
/// Allows javascript delegates to be used and dynamically
/// creates the global method.
/// @param target WPF/e element to set the event on
/// @param eventName name of the event to set, ie "MouseEnter"
/// @param delegate function to call when the event occurs.
var method_id = 0;
function setCallback(target, eventName, delegate) {
	var callbackName = "uniqueCallback" + (method_id++);
	eval(callbackName + " = delegate;");
	target.addEventListener(eventName,callbackName);
}

