var histManager;  
var mediaElement;
var progressThumb;
var progressRect;
var loaded = false;
var flyoutState = "expanded";

window.onresize = resize;

function root_Loaded(sender, args) {
    // Initialize transport buttons
    setupTransportButtions(sender);
    
    // Initialize the ListBox
    setupListbox(sender);
    
    // Initialize MediaElement
    mediaElement = sender.findname("mediaElement");
    mediaElement.mediaOpened = "javascript:onMediaOpened";
    mediaElement.downloadProgressChanged = "javascript:onDownloadProgressChanged";
    
    // Call resize to layout for the browser's original size
    resize();
    
    // Conenct the flyout toggle button to code
    new button(sender.findName("toggleButton"), sender.findName("toggleButtonBackground"), "gray", "dimGray", toggleClick);
    
    // Fill the listbox
    loadListBoxItems();
}

// Creates an XML HTTP object to get the XAML tempalte string from the server
function loadListBoxItems() {
    xmlinstance = createXmlObj();
    xmlinstance.onreadystatechange = storeXamlString;
    try {
        xmlinstance.open('GET', "XAML/itemTemplate.xaml", true);
        xmlinstance.send(null);
    }
    catch (exception) {
        alert("This sample needs to be run from a web server or Visual Studio 2005");
    }
}

// Handles the XML HTTP object's ready state chagned event
function storeXamlString(){
    if (xmlinstance.readyState == 4){ //if request of file completed
        if (xmlinstance.status == 200){ //if request was successful
        
            // Store the XAML tempalte string
            xamlTemplate = xmlinstance.responseText;
            
            // Get the data
            getVideoTitles();
        }
        else {
            alert("This sample needs to be run from a web server or Visual Studio 2005");
        }
    }
}

function getVideoTitles() {
    // Canned array for data, this could be replaced by a JSON or XML HTTP request
    var videoEntries = new Array();
    videoEntries[0] = new videoEntry("Mike Harsh", "\"WPF\\E\"", "http://download.microsoft.com/download/3/b/0/3b0b0ab5-eb51-4896-bf3a-2f08a4007144/mike_harsh_wpf_e_2006.wmv", "assets/MikeHarsh.jpg");
    videoEntries[1] = new videoEntry("Mike Swanson", "Adobe Illustrator to XAML converter", "http://download.microsoft.com/download/3/1/c/31c7c851-d455-476d-8a11-6306f0383d20/illustrator_to_xaml_2005.wmv", "assets/MikeSwanson.jpg");
    videoEntries[2] = new videoEntry("Bill Gates", "17 Minutes with Bill", "http://download.microsoft.com/download/d/8/7/d8751d87-3c99-4470-8e3e-bf352932601a/ctorrec9billg.wmv", "assets/BillGates.jpg");
    videoEntries[3] = new videoEntry("Katy Hunter", "Steve Ballmer's Speechwriter", "http://download.microsoft.com/download/8/1/c/81cdb151-0aae-4f50-ab44-654b5f7ae0db/WM_IN_2005_KatyHunter.wmv", "assets/KatyHunter.jpg");
    videoEntries[4] = new videoEntry("London Niners", "Tour, Drinks and Debate", "http://download.microsoft.com/download/3/0/9/30948eab-b25d-462b-8e88-91160e92ff22/LondonNiners.wmv", "assets/London.jpg");
    videoEntries[5] = new videoEntry("Channel 9 Team", "Rory Meets Da Team", "http://download.microsoft.com/download/5/4/a/54aa352e-2587-40cc-8a9f-dcd1932973de/Rory_Team_Meet.wmv", "assets/RoryTeam.jpg");
    videoEntries[6] = new videoEntry("Jacqueline Russell", "Microsoft at Maker Faire", "http://download.microsoft.com/download/3/b/0/3b0b0ab5-eb51-4896-bf3a-2f08a4007144/Maker_Faire_Russel.wmv", "assets/JacquelineRussell.jpg");
    videoEntries[7] = new videoEntry("Jenny Lam", "Designing Experiences at Microsoft", "http://download.microsoft.com/download/7/d/b/7dbc5bf1-884c-476a-8915-b2e883de8642/jenny_lam_windows_vista_designer_2005.wmv", "assets/JennyLam.jpg");
    videoEntries[8] = new videoEntry("MS Research Cambridge", "Tour of the Cambridge Campus", "http://download.microsoft.com/download/2/a/d/2adef79f-192f-4fba-ac2c-44975b750ccf/Tour_Final.wmv", "assets/Cambridge.jpg");
    
    // Set the data source for the listbox
    setDataSource(videoEntries);
}

function loadVideo(videoNumber) {
    // Set mediaPlayer state
    loaded = false;
    
    // Stop timer
    var timer = mediaElement.findName("timer");
    timer.Stop();
    
    // Get the video URL from the TextBlock in the item template
    var sourceUrlTextBlock = mediaElement.findName("sourceUrlTextBlock" + videoNumber);
    var url = sourceUrlTextBlock.text;
    
    // Set the source to the URL
    mediaElement.source = url;
    
    // Move the selection rectangle
    selectionRect["Canvas.Top"] = (videoNumber - 1) * 47;
}

function onItemsLoaded() {
    // Load the first video
    videoNumber = 1;
    loadVideo(videoNumber);
    
    //Setup Microsoft AJAX history manager
	if (!histManager) {
	    histManager = $create(Sys.Samples.HistoryManager,{},{navigated : onNavigated },{},$get('_historyFrame'));     
	}
	
	histManager.addEntry(videoNumber + "");
}

// Set app state on the media opened event
function onMediaOpened(sender, args) {
    // Set mediaPlayer state
    loaded = true;
    
    // Start timer
    var timer = sender.findName("timer");
    timer.begin(); 
    
    // Set duration textblock
    // Process the duration of the media into an hours:minutes:seconds string to be presented.
    var datetime = new Date(0, 0, 0, 0, 0, mediaElement.naturalDuration.Seconds)
    var hours = datetime.getHours();
    var minutes = datetime.getMinutes();
    var seconds = datetime.getSeconds();
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    
    var durationString;
    if (hours > 0) {
        durationString = hours.toString() + ":" + minutes + ":" + seconds;
        sender.findName("duration").text = durationString.toString();
        sender.findName("duration")["canvas.left"] = 493;
    }
    else {
        durationString = minutes + ":" + seconds;
        sender.findName("duration").text = durationString.toString();
        sender.findName("duration")["canvas.left"] = 504;
    } 
    
    // Set icon to pause
    var pauseIcon = sender.findName("pauseIcon");
    pauseIcon.opacity = 1;
    var playIcon = sender.findName("playIcon");
    playIcon.opacity = 0;  
}

// Update the download progress bar
function onDownloadProgressChanged(sender, eventArgs) {
    var downloadProgressRect = mediaElement.findName("downloadProgressRect");
    width = mediaElement.downloadProgress * 320 ;
    downloadProgressRect.width = width;
}

// Handles the timer's tick event
function timerCompleted (sender, eventArgs) {
    if (loaded) {
        if (progressThumb == null) {
          progressThumb = mediaElement.findName("progressThumb");
          progressRect = mediaElement.findName("playbackProgressRect");
        }

        var pos = mediaElement.position;
        if(pos)
        {
          var width = pos.Seconds;
          var duration = mediaElement.naturalDuration.seconds;
        
          width = width * 320 / duration;
          progressRect.width = width - 2;
          progressThumb["canvas.left"] = width + 211;
        }
        
        // Restart timer
        var timer = sender.findName("timer");
        timer.stop();
        timer.begin(); 
    }
}

// Handle the Microsoft AJAX history manager navigated event
function onNavigated(sender, args)
{
    var target = args.get_entryName();
    if ( (target != null) && (target != '')) 
    { 
   	    loadVideo(target / 1);     
    }
} 

// When the toggle button is clicked, start the transition animation
function toggleClick(sender,args) {
    if (flyoutState == "expanded") {
        var flyout = sender.findName("listBoxFlyout"); 
        flyout.stop();
        var collapse = sender.findName("listBoxCollapse"); 
        collapse.begin();
        flyoutState = "transition";
    }
    else if (flyoutState == "collapsed") {
        var flyout = sender.findName("listBoxFlyout"); 
        flyout.begin();
        flyoutState = "transition";
    }   
}

// Swap the UI on the toggle button 
function collapseCompleted(sender,args) {
    flyoutState = "collapsed";
    var expandButton = sender.findName("expandButton");
    expandButton.opacity = 1;
    var collapseButton = sender.findName("collapseButton");
    collapseButton.opacity = 0; 
}

// Swap the UI on the toggle button 
function flyoutCompleted(sender,args) {
    flyoutState = "expanded";
    var collapseButton = sender.findName("collapseButton");
    collapseButton.opacity = 1; 
    var expandButton = sender.findName("expandButton");
    expandButton.opacity = 0;
}

// Roughly equivalent to the WPF Viewbox element
// Stretch=Uniform HorizontalAlignment=left VerticalAlignment=top
function resize () {
   var wpfeControl1 = document.getElementById("wpfeControl1");
   
   var sourceWidth = wpfeControl1.findName("root").width;
   var targetWidth = wpfeControl1.clientWidth;
   var sourceHeight = wpfeControl1.findName("root").height;
   var targetHeight = wpfeControl1.clientHeight;
   
   var scale = 0;
   if (sourceHeight > 0 && sourceWidth > 0) {
       var aspectRatio = sourceWidth/sourceHeight;
       scale = Math.min(targetHeight / sourceHeight, targetWidth / sourceWidth);
   }
   
   var scaleTransform = wpfeControl1.findName("scaleTransform");
   scaleTransform.scaleX = scale;
   scaleTransform.scaleY = scale;
}