if (!window.MsEducationHero)
	window.MsEducationHero = {};

MsEducationHero.Scene = function() 
{
}

MsEducationHero.Scene.prototype =
{
    plugIn: null,
    uiCanvas:null,
    canvas:null,
    video: null,
    scrub: null,
    scrubBg: null,
    time: null,
    timeText:null,
    scrubbing:null,
    videoPlayerScale:null,
    assetHolder:null,
    videoExpanded:null,

	
	handleLoad: function( plugIn, userContext, rootElement ) 
	{
		this.plugIn = plugIn;
		this.uiCanvas = rootElement;
		this.videoExpanded = ( document.location.search == "?videoExpanded=true" ) ? true : true;
		
		// load fonts, images, videos & init buttons after
		this.loadAssets( "assets.DEPLOY" );
	},
	
	loadAssets: function( item, callback ) 
	{
	    this.progInd = this.plugIn.content.findName( "preloadProgress" );
	    this.progText = this.plugIn.content.findName( "loading_text" );
	    this.progRect = this.plugIn.content.findName( "preloadRectangle" );
	    
		var assetDl = this.plugIn.createObject( "downloader" );
	        assetDl.addEventListener( "downloadProgressChanged", Silverlight.createDelegate( this, this.dlProgress ) );
	        assetDl.addEventListener( "completed", Silverlight.createDelegate( this, this.initControls ) );
	        assetDl.open( "GET", item );
	        assetDl.send();
	},
	
	dlProgress: function( sender, eventArgs ) 
	{
	    // show loading progress
	    var percentage = sender.downloadProgress;
	    this.progInd.scaleY = percentage;
	    this.progText.text = Math.round( percentage * 100 ).toString() + "% Loaded";
	    //this.progText[ "Canvas.Top" ] = this.progRect.actualHeight * percentage;
	},

	initControls: function( sender ) 
	{
	    
	    // save a reference to the downloaded content
	    this.assetHolder = sender;
	    
	    // get the main ui
        this.canvas = this.createElem( this.uiCanvas, sender, undefined, undefined, undefined, "hero.xaml", true );
        
        // set image sources
        this.configureImages( this.canvas, this.assetHolder );

        var textBlocks = this.getXamlObjects( this.canvas, "TextBlock" );
        for( var j in textBlocks )
        {
            var tb = textBlocks[ j ];
            this.setProps( tb, { source: this.assetHolder, text: tb.text } );
        }

		this.video = this.canvas.findName( "VideoWindow" );
		this.videoPlayerScale = this.canvas.findName( "VideoPlayerScale" );
		this.scrub = this.canvas.findName( "btn_scrub" );
		this.scrubBg = this.canvas.findName( "ScrubBg" );
		this.time = this.canvas.findName( "time_sb" );
		this.timeTextBlock = this.canvas.findName( "timerText" );
		this.buffer = this.canvas.findName( "bufferingProgressIndicator" );
		
	    // set up video events
	    this.setProps( this.video, { "MediaEnded" : this.videoEnded } );
	    this.setProps( this.video, { "DownloadProgressChanged" : this.videoDownloadProgressChanged } );
	    //this.setProps( this.video, { "CurrentStateChanged" : this.videoCurrentStateChanged } );
		//this.video.bufferingTime = "0:3:10";
		this.video.source = "mms://wm.microsoft.com/ms/education/videos/Resume.wmv";
	    
	    // set up storyboard events
	    this.setProps( this.canvas.findName( "hideStartBtn_sb" ), { "Completed" : this.startVideo } );
	    this.setProps( this.time, { "Completed" : this.time_Completed } );
	    
	    // set up control events
	    var controls = this.getXamlObjects( this.canvas, undefined );
	    for( var i in controls )
	    {
	        var item = controls[ i ];
	        var itemName = item.name;
	        if( itemName.indexOf( "btn_" ) > -1 )
	        {
                this.setProps( item, { "MouseLeftButtonUp": this[ itemName + "_MouseLeftButtonUp" ], "MouseLeftButtonDown": this[ itemName + "_MouseLeftButtonDown" ], "MouseMove": this[ itemName + "_MouseMove" ] } );
	        }
	    }
	    
	},
	
	btn_link_MouseLeftButtonUp: function( sender, args ) 
	{
	    var newwindow = window.open( "http://www.microsoft.com/education", "" );
	},
	
	btn_video_link_0_MouseLeftButtonUp: function( sender, args ) 
	{
	    this.btn_play_pause_MouseLeftButtonUp( this.canvas.findName( "btn_play_pause" ) );
	    var newwindow = window.open( "http://get.liveatedu.com/Education/Connect/", "" );
	},
	
	btn_video_link_1_MouseLeftButtonUp: function( sender, args ) 
	{
	    this.btn_play_pause_MouseLeftButtonUp( this.canvas.findName( "btn_play_pause" ) );
	    var newwindow = window.open( "http://get.liveatedu.com/Education/Connect/CaseStudies/", "" );
	},
	
	startVideo: function( sender, args ) 
	{
        // move silverlight div to front
        document.getElementById( "SilverlightPlugInHost" ).style.zIndex = 100;
        
        this.setProps( this.canvas.findName( "start_video" ), { "Visibility" : "Collapsed" } );
        this.setProps( this.canvas.findName( "video_link" ), { "Visibility" : "Visible" } );
        this.btn_volume_MouseLeftButtonUp( undefined, false );
        this.time.begin();
        this.video.play();
        this.togglePlayIcon( false );
        
        if( this.videoExpanded == true )
        {
	        this.btn_full_MouseLeftButtonUp( this.canvas.findName( "btn_full" ) );
        }
	},
	
	videoEnded: function( sender, args ) 
	{
        // move silverlight div to BACK
        document.getElementById( "SilverlightPlugInHost" ).style.zIndex = 0;
        
        this.setProps( this.canvas.findName( "start_video" ), { "Visibility" : "Visible" } );
        this.setProps( this.canvas.findName( "video_link" ), { "Visibility" : "Collapsed" } );
        this.time.stop();
        this.setProps( this.canvas.findName( "timerText" ), { "Text" : "" } );
        this.video.stop();
        this.canvas.findName( "showStartBtn_sb" ).begin();
        this.togglePlayIcon( true );
	    if( this.videoPlayerScale.scaleX > 1 )
	    {
	        this.canvas.findName( "collapseVideo_sb" ).begin();
	    }
	},
	
	videoDownloadProgressChanged: function( sender, args )
	{
        var prog = this.video.DownloadProgress;
        //this.setProps( this.timeTextBlock, { "text" : prog.toString() } );
        this.setProps( this.buffer, { "ScaleX" : prog } );
	},
	
	videoCurrentStateChanged: function( sender, args ) 
	{
        this.setProps( this.timeTextBlock, { "text" : sender.CurrentState } );
	},
	
    time_Completed : function()
    {
        if ( this.video.CurrentState == "Playing" )
        {
            var p = this.getVideoPercent();
            var l = this.getScrubWidth() * p ;

            // set scrubber position
            this.scrub[ "Canvas.Left" ] =  l;
            
            // set the timer
            this.setVideoTimeString();
            
            this.time.begin();
        }
    },
    
    setVideoTimeString : function()
    {
        // set text
        this.setProps( this.timeTextBlock, { "text" : this.getVideoTimeString( this.video.position.seconds ) } );
    },
    
    getVideoTimeString : function( time )
    {
        var hours = Math.floor( time / 3600 ); 
        var minutes = Math.floor( ( time / 60 ) - ( hours * 60 ) ); 

        var seconds = Math.floor( time - hours * 60 * 60 - minutes * 60 ); 
        var a = "";

        if( hours > 0 ) 
        {
            a = hours < 10 ? "0" + hours : "" + hours;
            a+= ":"; 
        }

        a+= minutes < 10 ? "0" + minutes : "" + minutes; a+= ":"; 
        a+= seconds < 10 ? "0" + seconds : "" + seconds; 

        return a;
    },
    
    getScrubWidth : function()
    {
        return this.scrubBg.Width - ( this.scrub.Width );
    },
    
    getVideoPercent : function()
    {
        return this.video.position.seconds / this.video.naturalDuration.seconds;
    },
    
    togglePlayIcon: function( state ) 
	{
	    if( state == false )
	    {
	        this.canvas.findName( "icon_play" ).visibility = "Collapsed";
	        this.canvas.findName( "icon_pause" ).visibility = "Visible";
	    }
	    else
	    {
	        this.canvas.findName( "icon_play" ).visibility = "Visible";
	        this.canvas.findName( "icon_pause" ).visibility = "Collapsed";
	    }
	},
    
    btn_play_pause_MouseLeftButtonUp: function( sender, args ) 
	{
        if( this.canvas.findName( "icon_play" ).visibility == "Collapsed" )
        {
            this.togglePlayIcon( true );
            this.video.pause();
        }
        else
        {
            this.togglePlayIcon( false );
            this.video.play();
        }
	},
	
	btn_stop_MouseLeftButtonUp: function( sender, args ) 
	{
        this.videoEnded();	    
	},
	
	btn_close_MouseLeftButtonUp: function( sender, args ) 
	{
        this.videoEnded();	    
	},
	
	btn_volume_MouseLeftButtonUp: function( sender, args ) 
	{
        if( this.video.volume == 0 || args == false )
        {
            this.canvas.findName( "icon_volume" ).visibility = "Visible";
            this.video.volume = .5;
        }
        else
        {
            this.canvas.findName( "icon_volume" ).visibility = "Collapsed";
            this.video.volume = 0;
        }
	    
	},
	
	btn_full_MouseLeftButtonUp: function( sender, args ) 
	{
	    if( this.videoPlayerScale.scaleX > 1 )
	    {
	        this.canvas.findName( "collapseVideo_sb" ).begin();
	    }
	    else
	    {
	        this.canvas.findName( "expandVideo_sb" ).begin();
	    }
	},
	
	btn_scrub_MouseLeftButtonDown: function( sender, args ) 
	{
        this.scrubbing = true;
        this.time.stop();
        this.scrub.CaptureMouse();
        this.video.pause();
	},
	
	btn_scrub_MouseLeftButtonUp: function( sender, args ) 
	{
        this.scrubbing = false;
        this.scrub.ReleaseMouseCapture();
        this.time.begin();
        this.video.play();
	},
    
    btn_scrub_MouseMove : function( sender, eventArgs )
    {
        if ( this.scrubbing )
        {
            var timeRemaining = this.scrub.Width / 4;
            var currX = eventArgs.getPosition( this.scrubBg ).X;
            var currDlProg = this.scrubBg.Width * this.buffer.scaleX;

            if ( currX >= timeRemaining && currX <= this.scrubBg.Width - timeRemaining && currX <= currDlProg - ( timeRemaining * 2 ) )
            {
                var currScrubPos = ( this.scrubBg[ "Canvas.Left" ] - ( this.scrub.Width / 2 ) ) + currX;
                this.scrub[ "Canvas.Left" ] = currScrubPos;

                var newScrubPos = ( currX / this.scrubBg.Width ) * this.video.naturalDuration.seconds;

                var minutes = 0;
                if ( newScrubPos > 60 ){
                    minutes = newScrubPos / 60;
                }

                newScrubPos = newScrubPos % 59;
                var newVideoTime = "0:" + Math.round( minutes ) + ":" + Math.round( newScrubPos );
                try
                {
                    this.video.Position =  newVideoTime;
                } 
                catch( ex )
                {
                }                
                this.setVideoTimeString();
            }
        }
    },
	
	btn_start_video_MouseLeftButtonUp: function( sender, args ) 
	{
	     this.canvas.findName( "hideStartBtn_sb" ).begin();
	    
	},
	
	
	// get a list of desirable xaml objects
	getXamlObjects: function( canvas, type, objects, other ) {
	
        if( !objects )
        {
            var objects = [];
        }
        // sneak through xaml lookin for yummy items
        for ( var i=0; i<canvas.children.count; i++ ) {
            
            // get the current item
            var item = canvas.children.getItem( i );
            
            if( item == type || type == undefined )
            {
                if( other )
                {
                    // match some other params
                    var match = false;
                    for( var j in other )
                    {
                        match = ( item[ j ] == other[ j ] ) ? true : false;
                    }
                }
                else
                {
                    // nuthin else to match
                    var match = true;
                }
                
                if( match == true )
                {
                    objects.push( item ); // item matches type, so add it to the collection
                }
            }
            if( item == "Canvas" )
            {
	            this.getXamlObjects( item, type, objects ); // found a canvas, so look inside it
            }
        }
        
        // return the mess-o-objects
        return objects;

	},
	

	// create a xaml element
	createElem: function( canvas, type, name, params, prevName, partName, nameScope ) 
	{
        var nameScope = ( nameScope != undefined ) ? nameScope : true;
        // create textblock & canvas
        if( type == "Canvas" || type == "TextBlock" || type == "Image" )
        {
            var currXaml = '<' + type + ' xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="' + name + '" />';
            var currElem = this.plugIn.content.createFromXaml( currXaml, nameScope );
                currElem = canvas.children.add( currElem );
                currElem = canvas.children.getItem( currElem );
        }
        else if( type == "Downloader" && type.ResponseText )
        {
            var txt = ( !partName ) ? type.ResponseText : type.GetResponseText( partName ) ;
            
            if( name && prevName )
            {
                prevName = 'x:Name="' + prevName + '"';
                name = 'x:Name="' + name + '"';
                
                // set its name while it is text
                txt = txt.replace( prevName, name );
            }
            var currElem = this.plugIn.content.createFromXaml( txt, nameScope );
                currElem = canvas.children.add( currElem );
                currElem = canvas.children.getItem( currElem );
                
        }
        
        // set properties of object
        if( params )
        {
            this.setProps( currElem, params );	        
        }

        return currElem;
	},

	// set image sources to items in zip archive
	configureImages: function( canvas, assets ) 
	{
	    // gather all images from xaml
	    var imageItems = this.getXamlObjects( canvas, "Image" );
	    
	    // loop through and set sources of the images to part of zip archive
	    for( var i in imageItems )
	    {
    	    var item = imageItems[ i ];
    	    
    	    if( item.tag )
    	    {
    	        //item.setSource( assets, item.tag );
                this.setProps( item, { source: { downloader: this.assetHolder, part: item.tag } } );
    	    }
	    }
	},

	// set properties of an object
	setProps: function( obj, props ) 
	{
        obj = ( typeof( obj ) == "string" ) ? this.plugIn.content.findName( obj ) : obj;
        
        if( obj.toString() == "Storyboard" )
        {
            // make sure to stop storyboards
            obj.stop();
        }
        
        for( var i in props )
        {
            var currProp = i;
            var currVal = props[ i ];
            
		    try {
                if( ( currProp == "Completed" || currProp == "MouseEnter" || currProp == "MouseLeave" || currProp == "MouseLeftButtonUp" || currProp == "MediaEnded" || currProp == "MouseLeftButtonDown" || currProp == "MouseMove" || currProp == "BufferingProgressChanged" || currProp == "DownloadProgressChanged" || currProp == "CurrentStateChanged" ) && currVal != undefined )
                {
    	            // add a listener
    	            try
    	            {
    	                obj.addEventListener( currProp, Silverlight.createDelegate( this, currVal ) );
    	            }
    	            catch( ex )
    	            {
    	                //alert( "error: " + ex );
    	            }
                }
                else
                {
                    obj[ currProp ] = currVal;
                }
                //alert(obj.name+" [ "+currProp+" : "+currVal+" ]");
		    } catch (ex) {
                if( currProp == "source" && obj.toString() == "TextBlock" )
                {
                    obj.setFontSource( currVal );
                }
                else if( currProp == "source" && obj.toString() == "Image" )
                {
                    obj.setSource( currVal.downloader, currVal.part );
                }
                //alert("ERROR: "+ex);
			    // fail silently
		    }
		}
	}	    

}