﻿// VideoPlayer object
VideoPlayer = function(slRootObject, sControlId, sControlXAML, aCoordinates)
{
    // Make object root scope accessible to inner objects
    var that = this;
    
    // Make arguments and derived varibles public
    this._slRootObject = slRootObject;
    this._sControlId = sControlId;
    this._aCoordinates = aCoordinates;
    this._sControlXAML = sControlXAML;
   // this._host = this._parent.getHost();
    
    // Set default options
    this._sControlName = "videoPlayer";

    // The first step is to retrive the XAML content for the control
    this._buildControl();
}

VideoPlayer.prototype =
{
    // Resize and position elements
    _autoSize: function()
    {
        // Position elements
        this._control["Canvas.Left"] = this._aCoordinates[0];
        this._control["Canvas.Top"] = this._aCoordinates[1];
    
        // Resize elements to fit
        this._absoluteRight = this._aCoordinates[0] + this._control.Width;
        this._absoluteBottom = this._aCoordinates[1] + this._control.Height;
    },
    
    // Create control element from XAML
    _buildControl: function()
    {
        // Cusomise XAML to make names unique
        var originalXaml = this._sControlXAML.replace(/Name="/g, "Name=\"" + this._sControlId);

        // Create element from XAML
        this._control = this._slRootObject.control.content.createFromXaml(originalXaml);

        // The XML object is added to the root Canvas
        this._slRootObject.rootElement.children.add(this._control);

        // Set control references
        this._setControlReferences();
        
        // Position and resize objects
        this._autoSize();
        
        this.initialiseVideoPlayer();
    },


    // Find name using original XAML name
    _findNameByXamlID: function(nameInXamlFile)
    {
        return this._slRootObject.rootElement.findName(this._getIdFor(nameInXamlFile));
    },


    // Get name in original XAML name using instances name
    _getIdFor: function(nameInXamlFile)
    {
        return this._sControlId + nameInXamlFile;
    },
    
    
    // Hook up events
    _hookUpEvents:  function()
    {
        // Define event listeners
        
    },


    // Make references to elements
    _setControlReferences : function()
    {
        // Reference elements
        
    },

    
    
    
    // EVENT LISTENERS --------------------------------------------------------
    
    // Event listener for button clicked
    _somethingClicked : function(sender, eventArgs)
    {
        console.log(sender.Name + " clicked y'all");
    },
    
    initialiseVideoPlayer: function(control, userContext, rootElement) 
	{
		//Scope
		this.control = control;
		this.rootElement = rootElement;
		
		//
		//this.fullScreenMouseMoveEvent;
		
		//Mouse Drag for seek bar
		var isMouseCaptured;
		var mouseHorizontalPosition;
		
		
		//Declare xaml Elements 
		
		//Base of Player
		this.videoBaseCanvas = this.add("base_mc");
		this.videoBase = this.add("videoBase_mc");
		
		//Video Element
		this.videoHolder = this.add("screen_mc");
		this.fullScreenMouseMove = this.add("fullScreenMouseMove");
		this.videoScreenBground = this.add("screenBground_mc");
		this.videoPlayer = this.add("mediaElement_mc");
		
		//Controls
		this.controlHolder = this.add("controls_mc");
		this.playBtn = this.add("play_btn");
		this.muteBtn = this.add("mute_btn");
		this.fullScrnBtn = this.add("fullscreen_btn");
		this.scrubBtn = this.add("seek_btn");
		this.seekBar = this.add("seekBar_mc");
		this.statusTxt = this.add("vidStatus_txt");
		this.durationTxt = this.add("duration_txt");
		
		//ICONS 
		this.pauseIcon = this.add("pause_icon");
		this.playIcon = this.add("play_icon");
		
		this.muteOnIcon = this.add("muteOn_icon");
		this.muteOffIcon = this.add("muteOff_icon");
		
		this.defaultFull = this.add("toDefaultScreen_icon");
		this.fullFull = this.add("toFullScreen_icon");
		
		//FullScreen Skin
		this.fullScreenSkin = this.add("fullScreenSkin");
		this.controlAni = this.add("controlAni");
		this.controlAniStory = this.add("controlAnimation");
		
		this.debugTxt = this.add("Debugger");
		//EnterFrame
		this.onEnterFrame = this.add("onEnterFrame");
		
		//Highlight effect Animation
		this.highLightEffect = this.add("highlight_mc");
		this.highlightAniStory = this.add("highlightAnimation");
		this.highlightAni = this.add("highlightAni");
		
		this.playerHighlight = this.add("playerHighlight");
		
		//Initiate Events
		this.initiateEvents();
		this.setVideoPlayerDefault();
		//this.runVideo("http://www.microsoft.com/australia/wvx/heroes/vs08_wpf.wvx");
		
		
		
		this.onEnterFrame.Begin();
		
	},
	
	//Retreives the element from xaml
	add: function(sElement){
	    var tempElement = this._findNameByXamlID(sElement);
	    return tempElement;
	},
	
	//Initiate Event listeners
	addEvent: function(oElement, sEventType,fFunctionCall){
		oElement.addEventListener(sEventType, Silverlight.createDelegate(this, fFunctionCall));
	},
	
	
	initiateEvents: function() {
		
		this.addEvent(this.playBtn, "MouseLeftButtonDown", this.playAndPauseVideo);
		this.addEvent(this.muteBtn, "MouseLeftButtonDown", this.mute);
		this.addEvent(this.fullScrnBtn, "MouseLeftButtonDown", this.fullScreen);
		this.addEvent(this.videoPlayer, "CurrentStateChanged", this.media_status);
		
		//Timer 
		this.addEvent(this.onEnterFrame,"Completed", this.timer);
		
		//Control Animation
		this.addEvent(this.controlAniStory, "Completed", this.controlOut);
		
		//Highlight Animation
		this.addEvent(this.highlightAniStory, "Completed", this.aniHighlight);
		
		//Basic button Events
		this.userInteraction(this.playBtn);
		this.userInteraction(this.muteBtn);
		this.userInteraction(this.fullScrnBtn);
		
		//Seek button Events
		this.addEvent(this.scrubBtn, "MouseLeftButtonDown", this.handleMouseDown);
		this.addEvent(this.scrubBtn, "MouseMove", this.handleMouseMove);
		this.addEvent(this.scrubBtn, "MouseLeftButtonUp", this.handleMouseUp);
		
		//Check Screen size
		this._slRootObject.control.content.onfullScreenChange = Silverlight.createDelegate(this,this.checkScreenStatus);
		
		this.aniHighlight();
	},
	
	runVideo: function(sURL) {
	
	     var slPlugin = this._slRootObject.rootElement.getHost()
	     var versionCorrect = slPlugin.IsVersionSupported("1.0.30401");
	 
	     if(versionCorrect == false) {
	        alert("Your current Silverlight plugin is not supported.\nPlease right click, select Silverlight Configuration,\nclick on the Updates tab.\n\nSelect Install updates automatically(recommended)\nor contact your administrator.")
	     }
	     
		this.videoPlayer.Source = sURL;
		this.setVideoPlayerRunMode();
		this.captureVideoInitialProperites();
	},
	
	setVideoPlayerDefault: function(){
	    this.videoHolder.Background = "#00000000";
	    this.videoScreenBground.visibility = "Visible";
	    this.iconSwitch(this.playIcon, this.pauseIcon);
	    this.iconSwitch(this.muteOnIcon, this.muteOffIcon);
	    this.iconSwitch(this.defaultFull, this.fullFull);
	},
	
	
	setVideoPlayerRunMode: function() {
	    this.videoHolder.Background = "#FF000000";
	    this.videoScreenBground.visibility = "Collapsed";
	    this.iconSwitch(this.pauseIcon, this.playIcon);
	    this.iconSwitch(this.muteOnIcon, this.muteOffIcon);
	    this.iconSwitch(this.defaultFull, this.fullFull);
	    
	},
	
	userInteraction: function(oElement) {
	 this.addEvent(oElement, "MouseEnter", this.userOverEvent);
	 this.addEvent(oElement, "MouseLeave", this.userOutEvent);
	},
	
	//Calls on Frame rate used to refresh content
	timer: function(sender, eventArgs) {
		this.duration_display();
		this.seek_control();
		sender.Begin();
	},
	
	//Retreive initial Properties 
	captureVideoInitialProperites: function() {
		this.oDefaultVidHeight = this.videoPlayer.Height;
		this.oDefaultVidWidth = this.videoPlayer.Width;
		this.oDefaultVidX = this.videoPlayer["Canvas.Left"];
		this.oDefaultVidY = this.videoPlayer["Canvas.Top"];
		
		this.oDefaultVidHolderHeight = this.videoHolder.Height;
		this.oDefaultVidHolderWidth = this.videoHolder.Width;
		this.oDefaultVidHolderX = this.videoHolder["Canvas.Left"];
		this.oDefaultVidHolderY = this.videoHolder["Canvas.Top"];
		this.oDefaultVidHolderColor = this.videoHolder["Background"];
		
		this.oDefaultVidControlWidth = this.controlHolder.Width;
		this.oDefaultVidControlHeight = this.controlHolder.Height;
		this.oDefaultVidControlX = this.controlHolder["Canvas.Left"];
		this.oDefaultVidControlY = this.controlHolder["Canvas.Top"];
		this.oDefaultVidControlColor = this.controlHolder["Background"];
		
		this.oDefaultBaseX = this.videoBaseCanvas["Canvas.Left"];
		this.oDefaultBaseY = this.videoBaseCanvas["Canvas.Top"];
	},
	
	//VIDEO OUTPUT 
	media_status: function(sender, eventArgs) {
		this.statusTxt.Text = this.videoPlayer.CurrentState;
	},
	
	duration_display: function() {
		var nPosition = this.videoPlayer.Position.seconds.toFixed(1);
		this.durationTxt.Text = nPosition;
	},
	
	
	//SEEK BAR CONTROL AUTO AND MANUAL
	
	//MANUAL
	
	handleMouseDown: function(sender, eventsArg) {
        var item = sender;
        mouseHorizontalPosition = eventsArg.getPosition(null).x;
        this.isMouseCaptured = true;
        this.onEnterFrame.Stop(); // Stop Automation
        item.CaptureMouse();
     
	},
	
	handleMouseMove: function(sender, eventsArg) {
	    var item = sender;
	    
        if (this.isMouseCaptured) {
        
            var horizontalLimit = this.seekBar.Width - 6;
            // Calculate the current position of the object.
            var deltaH = eventsArg.getPosition(null).x - mouseHorizontalPosition;
            var newLeft = deltaH+ item["Canvas.Left"];

            // Set new position of object.
            item["Canvas.Left"] = newLeft;
          
            if (newLeft < horizontalLimit && newLeft >0) {

                // Update position global variables.
                mouseHorizontalPosition = eventsArg.getPosition(null).x;
              
                //Set Position of Seek
                var seekTime = this.videoPlayer.Position;
                seekTime.seconds = (((this.scrubBtn["Canvas.Left"]- this.seekBar["Canvas.Left"])/this.seekBar.Width) *this.videoPlayer.NaturalDuration.Seconds);
                this.videoPlayer.Position = seekTime;
                this.videoPlayer.Play();
            } else {
                this.isMouseCaptured = false;
                item.ReleaseMouseCapture();
            }
        }
	},
	
	handleMouseUp: function(sender, eventsArg) {
	     var item = sender;
         this.isMouseCaptured = false;
         item.ReleaseMouseCapture();
         mouseHorizontalPosition = -1;
         this.onEnterFrame.Begin(); // Begin Automation
	},
	

	
	//AUTO
	seek_control: function() {
		var nPosition = this.videoPlayer.Position.seconds.toFixed(0);
	    var nDuration = this.videoPlayer.NaturalDuration.seconds.toFixed(0);
	    var nPercentLoaded = (nPosition /nDuration) * this.seekBar.Width;
        if(nPercentLoaded >= 0){
	        this.scrubBtn["Canvas.Left"] = nPercentLoaded;
		}
	},
	
	
	//VIDEO CONTROLS
	//******************************************************************
	playAndPauseVideo: function(sender, eventArgs) {
 
	    var vidStatus = this.videoPlayer.CurrentState;
        if(vidStatus == "Playing" || vidStatus == "Buffering") {
	        this.iconSwitch(this.playIcon,this.pauseIcon); 
	        this.videoPlayer.pause();
	    }else {
		    this.videoPlayer.play(); 
		    this.iconSwitch(this.pauseIcon, this.playIcon);
	    }
	},
	
	mute: function(sender, eventArgs) {
	    var audioStatus = this.videoPlayer.IsMuted;
	    if(audioStatus) {
	        this.videoPlayer.IsMuted = false;
		    this.iconSwitch(this.muteOnIcon, this.muteOffIcon);
	    }else {
		    this.videoPlayer.IsMuted = true;
		    this.iconSwitch(this.muteOffIcon,this.muteOnIcon);
	    }
	},
	
	fullScreen: function(sender, eventArgs) {
	
	    var isFullScreen = this._slRootObject.control.content.fullScreen;
	    
		if (isFullScreen) {
		    this.iconSwitch(this.defaultFull, this.fullFull);
			this._slRootObject.control.content.fullScreen = false;
		} else {
		    this.iconSwitch(this.fullFull, this.defaultFull);
			this._slRootObject.control.content.fullScreen = true;
		}
	},
	
	
	checkScreenStatus: function(sender, eventArgs) {
	    var isFullScreen = this._slRootObject.control.content.fullScreen;
	   
	    
		if (isFullScreen) {
			this.setFull();
			this.setFullScreenMenu();
			this.setFullScreenEvent();
			
		} else {
		    this.removeFullScreenEvent();
			this.animateStop();
			this.setDefault();
			this.setFullScreenDefault();
		}
	},
	
	//SCREEN SIZING
	setFull: function() {
		
		//Adjust VideoPlayer Control Properites
        this._control["Canvas.Left"] = 0;
        this._control["Canvas.Top"] = 0;
		
        //Adjust Video Holder Properites
		this.videoHolder["Canvas.Left"] = 0;
		this.videoHolder["Canvas.Top"] = 0;
		this.videoHolder.Width = this._slRootObject.control.content.actualWidth;
		this.videoHolder.Height = this._slRootObject.control.content.actualHeight;
		this.videoHolder["Background"] = "Black";
		
		//Mouse Move
		this.fullScreenMouseMove["Canvas.Left"] = 0;
		this.fullScreenMouseMove["Canvas.Top"] = 0;
		this.fullScreenMouseMove.Width = this._slRootObject.control.content.actualWidth;
		this.fullScreenMouseMove.Height = this._slRootObject.control.content.actualHeight;
		
		//Adjust Video Player Properties
		this.videoPlayer["Canvas.Left"] = 0;
		this.videoPlayer["Canvas.Top"] = 0;		
		this.videoPlayer.Width = this._slRootObject.control.content.actualWidth;
		this.videoPlayer. Height = this._slRootObject.control.content.actualHeight;
		
		//Base Opacity
		this.videoBase.Opacity = 0;
		this.videoScreenBground.Opacity = 0;
		
		//Base Position
		this.videoBaseCanvas["Canvas.Left"] = 0;
		this.videoBaseCanvas["Canvas.Top"] = 0;

	},
	
	setDefault: function() {
	
		//Adjust VideoPlayer Control Properites
		this._control["Canvas.Left"] = this._aCoordinates[0];
		this._control["Canvas.Top"] = this._aCoordinates[1];
		
		//Adjust Video Holder Properites
		this.videoHolder["Canvas.Left"] = this.oDefaultVidHolderX;
		this.videoHolder["Canvas.Top"] = this.oDefaultVidHolderY;
		this.videoHolder.Width = this.oDefaultVidHolderWidth;
		this.videoHolder.Height = this.oDefaultVidHolderHeight;
		this.videoHolder["Background"] = this.oDefaultVidHolderColor;
		
		//Mouse Move
		this.fullScreenMouseMove["Canvas.Left"]= -5000;
		this.fullScreenMouseMove.Width = this.oDefaultVidHolderWidth;
		this.fullScreenMouseMove.Height = this.oDefaultVidHolderHeight;
		
		//Adjust Video Player Properties
		this.videoPlayer["Canvas.Left"] = this.oDefaultVidX;
		this.videoPlayer["Canvas.Top"] = this.oDefaultVidY;
		this.videoPlayer.Width = this.oDefaultVidWidth;
		this.videoPlayer. Height = this.oDefaultVidHeight;
		
		//Base Opacity
		this.videoBase.Opacity = 1;
		this.videoScreenBground.Opacity = 1;
		
		//Base Position
		this.videoBaseCanvas["Canvas.Left"] = this.oDefaultBaseX;
		this.videoBaseCanvas["Canvas.Top"] = this.oDefaultBaseY;
        
        this.iconSwitch(this.defaultFull, this.fullFull);
	},
	
	
	//FULL SCREEN NAVIGATION
    setFullScreenMenu: function() {
		this.controlHolder["Canvas.Top"] = this.videoHolder.Height;
		this.controlHolder["Canvas.Left"] = 100;
		this.fullScreenSkin.Opacity = 0.7;
	},
	
	setFullScreenDefault: function() {
	
		this.fullScreenSkin.Opacity = 0;
		this.controlHolder["Canvas.Top"]= this.oDefaultVidControlY;
		this.controlHolder["Canvas.Left"]= this.oDefaultVidControlX;

		//FullScreen Button CLick to default size 
		var border = this.fullScrnBtn.Name+"_bdr";
		var inner = this.fullScrnBtn.Name + "_grd";
		var icon = this.fullScrnBtn.Name + "_icon";

		this.fullScrnBtn.findName(border).Opacity = 1;
		this.fullScrnBtn.findName(border)["StrokeThickness"] = 0.5;
		this.fullScrnBtn.findName(inner).Color = "#FF7B8084";
		this.fullScrnBtn.findName(icon).Opacity = 1;

	},
	
	//FULL SCREEN EVENTS
	
	setFullScreenEvent: function() {
	    var eventDelegate = Silverlight.createDelegate(this,this.controlIn);
	//	this.fullScreenMouseMoveEvent = this.videoHolder.addEventListener("MouseMove", eventDelegate);
	    this.fullScreenMouseMoveEvent = this.fullScreenMouseMove.addEventListener("MouseMove", eventDelegate);
	},
	
    removeFullScreenEvent: function(sender, eventArgs) {
		//this.debugTxt.Text = " remove fullScreen called";
		this.fullScreenMouseMove.removeEventListener("MouseMove",this.fullScreenMouseMoveEvent);
	},
	
	//USER EVENTS
	userOverEvent: function(sender, eventArgs) {
		var border = sender.Name+"_bdr";
		var inner = sender.Name + "_grd";
		var icon = sender.Name + "_icon";
		var icon2 = sender.Name + "_icon2";
		var icon3 = sender.Name + "_icon3";
		var icon4 = sender.Name + "_icon4";
		
		sender.findName(border).Opacity = 0.5;
		sender.findName(border)["StrokeThickness"] = 3;
		sender.findName(inner).Color = "#FFE0E0E0";
		sender.findName(icon).Opacity = 0.2;
		if(sender.findName(icon2) != null) {
		    sender.findName(icon2).Opacity = 0.2;
        }
        
        if(sender.findName(icon3) != null) {
              sender.findName(icon3).Opacity = 0.2;
             
        }
        
      if(sender.findName(icon4) != null) {
        sender.findName(icon4).Opacity = 0.2;
      }
	},
	
	userOutEvent: function(sender, eventArgs) {
		var border = sender.Name+"_bdr";
		var inner = sender.Name + "_grd";
		var icon = sender.Name + "_icon";
		var icon2 = sender.Name + "_icon2";
	    var icon3 = sender.Name + "_icon3";
		var icon4 = sender.Name + "_icon4";
		
		
		sender.findName(border).Opacity = 1;
		sender.findName(border)["StrokeThickness"] = 0.5;
		sender.findName(inner).Color = "#FF7B8084";
		sender.findName(icon).Opacity = 1;
		
		if(sender.findName(icon2) != null) {
		    sender.findName(icon2).Opacity = 1;
        }
        
        if(sender.findName(icon3) != null) {
             sender.findName(icon3).Opacity = 1;
          
        }
        
       if(sender.findName(icon4) != null) {
        sender.findName(icon4).Opacity = 0.2;
      }
	
	},
	
    //SWICTH ICONS ON RELEASE
	iconSwitch: function(oShow, oHide) {
	    oShow.Opacity = 1;
	    oHide.Opacity = 0;
	},
	
	userReleaseEvent: function(sender, eventArgs) {
		
	},
	
	
	//ANIMATION IN OUT CALLS
	
	controlIn: function(sender, eventArgs) {
	    this.removeFullScreenEvent();
		this.animate(this.controlHolder["Canvas.Top"], 
					this.videoHolder.Height - this.controlHolder.Height + 70,
					 "0:0:00",
					 "0:0:01");
	},
	
	controlOut: function(sender, eventArgs) {
	    this.setFullScreenEvent();
		this.animate(this.controlHolder["Canvas.Top"],
					 this.videoHolder.Height,
					 "0:0:3",
					 "0:0:7");
	},
	
	//BASE ANIMATION
	
	animateStop: function() {
		this.controlAniStory.Stop();
	},
	
	animate: function(nFrom, nTo, nDelayTime, nTime) {
	  var isFullScreen = this._slRootObject.control.content.fullScreen
	 
	 if(isFullScreen) {
	    this.add("_Ease1").KeyTime = nDelayTime
		this.add("_Ease1").Value = nFrom;
		this.add("_Ease2").KeyTime = nTime;
		this.add("_Ease2").Value = nTo;
		this.controlAniStory.begin();
		}
	},
	
	//HIGHLIGHT EFFECT ANIMATION
	
	aniHighlight: function(sender, eventsArg) {
	  //  alert(this.highLightEffect["Canvas.Top"]);
	    if(this.highLightEffect["Canvas.Top"] >= 116) {
	        this.animateHighlight(this.highLightEffect["Canvas.Top"], 0);
	    }else {
	        this.animateHighlight(this.highLightEffect["Canvas.Top"], 116);
	    }
	
	},
	
    animateHighlight: function(nFrom, nTo) {
        this.add("_highEase1").Value = nFrom;
        this.add("_highEase2").Value = nTo;
        this.highlightAniStory.Begin();
    }	
}