
var plugin
var media_loaded
var updateTimeCodesInt
var vid
var main
var video_directory="video/"
var xmlDoc
var items

materials =new Array();
links = new Array();
links["item_1"] = "http://download.microsoft.com/download/3/D/9/3D920277-4D2E-492B-B903-92DFDD64CF5C/El_Origen.zip";
links["item_2"] = "http://download.microsoft.com/download/E/2/C/E2C2F33C-B3B0-4717-83F9-AC5BC1125C89/TechNet_Viral_Video_Gag_Soporte_Tecnico.zip";
links["item_3"] = "http://download.microsoft.com/download/E/2/C/E2C2F33C-B3B0-4717-83F9-AC5BC1125C89/TechNet_Viral_Video_Gag_Seguridad.zip";
links["item_4"] = "http://download.microsoft.com/download/E/2/C/E2C2F33C-B3B0-4717-83F9-AC5BC1125C89/TechNet_Viral_Video_Gag_Implementacion.zip";
links["item_5"] = "http://download.microsoft.com/download/5/5/E/55E27890-A070-4EF9-83D7-69354BA1C4D6/TechNet_Viral_Video_Gag_Tecnologia.zip";
function mainCanvasLoaded(s) {
		
	vid=s.findName("videoElement")
	main=s.findName("mainCanvas")
	plugin = s.getHost()	
	
	vid.addEventListener("downloadProgressChanged", handleDownloadProgressChanged)
	vid.addEventListener("bufferingProgressChanged", handleBufferProgressChanged)
	
	plugin.content.onFullScreenChange = onFullScreenChanged	
	mediaLoaded(plugin.content)	
	openVideoPanel()	
	LoadXmlDocument("xml/materials.xml",myCallBack)
	loadMaterialArray(1)
	
	s.findName("playPauseText").Text="play"
	
    videoCanvasLoaded(main.findName("videoContainer"));
}

function videoCanvasLoaded(s) {
    s.Children.Clear();
	var slControl = s.getHost();
	
	for(var i = 0; i <materials.length ;i++)
	{	    
	    var image = materials[materials[i]].Material_ImageUrl;
	    materials[materials[i]].Material_Id;	    
        var top = 50 * i - 25;// + 27;
	    var left = 0;
	    var e =slControl.content.createFromXaml(
	     '<Canvas Name="item_'  + materials[materials[i]].Material_Id +
	     '" Width="60" Height="35" Cursor="Hand" Canvas.Top="' + top + '" Canvas.Left="' + left + 
	     '">' +
	     //'<Rectangle Fill="#FFF" Height="95" Width="118" Opacity="1.3"></Rectangle>' + 	     
	     '<TextBlock Text="' + materials[materials[i]].Material_Title + '" FontSize="15" Canvas.Top="30" Canvas.Left="0" Canvas.ZIndex="10" FontWeight="Bold" />' +	     
	     '<Image Source="' + image + '" Stretch="Fill" Height="35" Width="50" Canvas.Left="15" Canvas.Top="20" />' +
	     '</Canvas>'
	     
	     );	
	    e.addEventListener("MouseLeftButtonDown", this.videoBtn);	    	    	    	    
	    s.children.Add(e);	
	}
}

function getAbsoluteTop(objectId) {
	var o = document.getElementById(objectId)
	var oTop = o.offsetTop        
	while(o.offsetParent!=null) { 
		oParent = o.offsetParent  
		oTop += oParent.offsetTop 
		o = oParent
	}
	return oTop
}

function getAbsoluteLeft(objectId) {
	var o = document.getElementById(objectId)
	var oLeft = o.offsetLeft        
	while(o.offsetParent!=null) {   
		oParent = o.offsetParent    
		oLeft += oParent.offsetLeft 
		o = oParent
	}	
	return oLeft
}

function mainCanvasMouseLeave(s) {
	this.mouse_down=0
	//clearInterval(mouseCheckInt)
	s.releaseMouseCapture()
}

function onFullScreenChanged(s, e) {	
	
    updateLayout(s,plugin.content.actualWidth, plugin.content.actualHeight)
}


function updateLayout(s,wid,hgt) {
	
	if(wid>700) {
		
		s.findName("videoPanel")["Canvas.Left"]=-26
		s.findName("videoPanel")["Canvas.Top"]=-7
			
		s.findName("videoElement").width=window.screen.width
		s.findName("videoElement").height=window.screen.height
		s.findName("videoElement").Stretch="Fill"
		
		s.findName("videoElementBG").width=window.screen.width
		s.findName("videoElementBG").height=window.screen.height
		
		
		s.findName("bufferMsgBG").width=window.screen.width
		s.findName("bufferMsgBG").height=window.screen.height
		
		//s.findName("titleMsgText").visibility="Collapsed"
	    //s.findName("descMsgText").visibility="Collapsed"
	    //s.findName("videoScroller_Container").Visibility = "Collapsed"	    
		
	}
	else {

		
		s.findName("videoPanel")["Canvas.Left"]=0
		s.findName("videoPanel")["Canvas.Top"]=0
	
	
		s.findName("videoElement").width=280
		s.findName("videoElement").height=210
		s.findName("videoElement").Stretch="Uniform"
		
		s.findName("videoElementBG").width=280
		s.findName("videoElementBG").height=210
		
		s.findName("bufferMsgBG").width=280
		s.findName("bufferMsgBG").height=210
		
        /*
        s.findName("titleMsgText").visibility="visible"
	    s.findName("descMsgText").visibility="visible"
	    s.findName("videoScroller_Container").Visibility = (materials.length > 6)?"Visible":"Collapsed";
	    */
		
	}
}	



function handleDownloadProgressChanged(s, e) {
	window.status="handle dpc called"
	updateDownloadProgress(s,e)
}



function updateDownloadProgress(s,e) {

	bgBar=s.findName("ToBeLoadedPath")
	progressBar=s.findName("LoadedPath")
	window.status=s.downloadProgress
	progressBar.width = bgBar.width * s.downloadProgress
}



function handleBufferProgressChanged (s,e) {

	s.findName("bufferMsgText").Text="Buffering Video: "+Math.floor(s.bufferingProgress*100)+"%"
	
	if(s.bufferingProgress >0 && s.bufferingProgress <1) {
		s.findName("bufferMsg").opacity=0.8
	}
	else {
		s.findName("bufferMsg").opacity=0
	}

}








function mediaLoaded(s){ 
	
	media_loaded=true
	vid=s.findName("videoElement")
	main=s.findName("mainCanvas")	
	updateTimeCodesInt=setInterval("updateTimeCodes()", 40)
}








function mediaEnd(s){ 
	s.stop()
	s.findName("playPauseText").Text="play"
	s.findName("playPauseText")["Canvas.Left"]=12
}

function videoBtn(s,e) {	
	media_loaded=false
	resetPlayHead(s,e)
	vid=s.findName("videoElement")
	vid.Source = materials[s.name].Material_Url	
	s.findName("playPauseBtn").visibility="visible"
	s.findName("fullScreenBtn").visibility="visible"
	s.findName("LoadedPath").visibility="visible"
	s.findName("muteBtn").visibility="visible"	
	var foo = document.getElementById('lnkDownload');
	if (foo)
	    foo.href = links[s.name];
}

function muteBtnPress(s,e) {
	if(s.opacity==1) {
		s.opacity=0.25
		s.findName("videoElement").volume=0
	}
	else {
		s.opacity=1
		s.findName("videoElement").volume=1
	}
}


function resetPlayHead(s,e) {

	s.findName("playPauseText").Text="pause"
	s.findName("playPauseText")["Canvas.Left"]=6
	s.findName("Playhead")["Canvas.Left"]=0
	
	s.findName("TimeText").Text=""
	s.findName("TimeText2").Text=""
}




function playPauseBtnPress(sender, args) {
        
    if(sender.findName("playPauseText").Text=="pause") {
    	sender.findName("videoElement").pause();
    	sender.findName("playPauseText")["Canvas.Left"]=12
    	sender.findName("playPauseText").Text="play"	
    }
    else {
    if (vid.Source == "")
        vid.Source = materials["item_1"].Material_Url;
    	sender.findName("videoElement").play();
    	sender.findName("playPauseText")["Canvas.Left"]=6
    	sender.findName("playPauseText").Text="pause"
    }   
}


function progressBarPress(s,e) {
	
	click_x=e.getPosition(null).x-45
	s.findName("playPauseText").Text="pause"
	s.findName("playPauseText")["Canvas.Left"]=6
	
	seekTo(s,click_x)
	me=s.findName("videoElement")
	me.play()
}



function seekTo(s,xpos) {

	var me=s.findName("videoElement")
	var mediaDuration = me.naturalDuration.seconds;
	var playheadWidth = s.findName("Playhead").width;
	var playAreaWidth = s.findName("ToBeLoadedPath").width - playheadWidth;
	
	var currentPlayTime = (xpos - playheadWidth / 2) / playAreaWidth * mediaDuration;
	
	if (currentPlayTime > mediaDuration) {
		currentPlayTime = mediaDuration;
	}
	else if (currentPlayTime < 0) {
		currentPlayTime = 0;
	}
	
	var position = me.position;
	position.seconds = currentPlayTime;
	me.position = position;
}






function updateTimeCodes() { 

	if(media_loaded) {
		var currentPosition = 0;
	
	
		var position = vid.position;

		if (position != null) {
			currentPosition = position.seconds;
		}
	
	
		vidTime1=main.findName("TimeText")
		vidTime2=main.findName("TimeText2")
		
		vidTime1.Text = formatTime(currentPosition * 1000);
		vidTime2.Text = formatTime2(currentPosition );
		
		this.updatePlayhead(currentPosition);
	}
}


function updatePlayhead(time) {
	var offset = 0;
	
	var naturalDuration = vid.naturalDuration;
	
	if (naturalDuration != null) {
		var mediaDuration = naturalDuration.seconds;
		
		var percent = time / mediaDuration;
		
		var playhead_width = main.findName("Playhead").width;
		var playarea_width = main.findName("ToBeLoadedPath").width - playhead_width;
		
		offset = playarea_width * percent;
	}
}






function formatTime(time) {
	var timeString = "";
	timeString += Math.floor(time / 60000);
	if (timeString.length == 1) {
		timeString = "0" + timeString;
	}
	timeString += ":";
	var seconds = Math.floor(time / 1000.0) % 60;
	if (seconds < 10) {
		timeString += "0";
	}
	timeString += seconds;
	
	return timeString;
}


function formatTime2(time) {
	
	
	time_num=Math.ceil(vid.naturalDuration.seconds)-time
	
	elapsedM = Math.floor(time_num/60);
	remaining = time_num-(elapsedM*60);

	elapsedS = Math.floor(remaining);
	remaining = time_num-(elapsedS);

	if (elapsedM<10) {
		minutes = "0"+elapsedM.toString();
	} 
	else {
		minutes = elapsedM.toString();
	}
	if (elapsedS<10) {
		seconds = "0"+elapsedS.toString();
	} 
	else {
		seconds = elapsedS.toString();
	}
	
	return minutes+":"+seconds;
}


function LoadXmlDocument(xmlFile, cbFun)
{
   var xdoc;

   if( window.ActiveXObject && /Win/.test(navigator.userAgent) )
   {
      xdoc = new ActiveXObject("Microsoft.XMLDOM");

      xdoc.async = false;
      xdoc.load(xmlFile);

      cbFun(xdoc);

      return true;
   }
   else if( document.implementation && document.implementation.createDocument )
   {
      xdoc = document.implementation.createDocument("", "", null);
      xdoc.load(xmlFile);

      xdoc.onload = function()
      {
         cbFun(xdoc);
      }

      return true;
   }
   else
   {
      return false;
   }
}

function myCallBack(xdoc)
{
    xmlDoc = xdoc;
}


function getValue(TagName, node)
{
	var currentNode = (node == null) ? xmlDoc.getElementsByTagName(TagName) : 
					items[node].getElementsByTagName(TagName);
	if(currentNode.length > 0)
		return currentNode[0].firstChild.nodeValue;
}
function loadCategory(sender, categoryId)
{    
    hideSelCats();
    document.getElementById(sender.id + 'sel').style.display = '';    
    loadMaterialArray(categoryId);
    videoCanvasLoaded(main.findName("videoContainer"));    
    clicked = null;
}
function hideSelCats()
{
    for (i = 1; i<=6; i++)    
        document.getElementById('cat' + i + 'sel').style.display = 'none';    
}
function catOver(sender)
{
    sender.src = 'images/' + sender.id + '-on.jpg';
}
function catOut(sender)
{
    sender.src = 'images/' + sender.id + '.jpg';
}


function loadMaterialArray(categoryId)
{    
    //var categoryId = document.getElementById('ddlCategories').value;
    materials =new Array();
    
    items = xmlDoc.getElementsByTagName('DTV_Material');
    var m = 0;    
    for (var i=0;  i < items.length ; i++)
	{
        if(parseInt(getValue("Category_Id",i)) == categoryId)
        {
            var Item = "item_" + getValue("Material_Id",i);
            materials[Item] = new Object();
            materials[Item].Material_Id = getValue("Material_Id",i);
            materials[Item].Material_Title = getValue("Material_Title",i);
            materials[Item].Material_Des = getValue("Material_Des",i);
            materials[Item].Material_Url = getValue("Material_Url",i);            
            materials[Item].Material_ImageUrl = getValue("Material_ImageUrl",i);
            materials[m] = Item;
            m++;            
        }
	    
	}   
}

