///////////////////////////////////////////////////////////////////////////////
//
//  ExtendedPlayer
//
//  This extends the base player class, you may override the base player
//  member functions or add additional player functionality here.
//
///////////////////////////////////////////////////////////////////////////////
var global_ProductTotalNum=0;
var global_XMLTree;
var slideArr=[];
Type.registerNamespace('ExtendedPlayer');

ExtendedPlayer.Player = function(domElement) {
	this.expProductName = PlayerConfig.key;//to change category here, default="web"; 
	this.groupInd=-1;
	this.subItemInd=-1;
	this.videoLinkArr=[];
	this.videos_children=[]
    ExtendedPlayer.Player.initializeBase(this, [domElement]);  
}

ExtendedPlayer.Player.prototype =  {
    xamlInitialize: function() {    
        ExtendedPlayer.Player.callBaseMethod(this, 'xamlInitialize');   


		this.createXMLHttpRequest(webRoot + PlayerConfig.dataSource.replace("[key]",PlayerConfig.key));

		var b=this.get_element(),
			c=Ee.UI.Xaml.Media._Button;
		b.content.onFullScreenChange=Function.createDelegate(this,this._fullScreenChangedSupplement)

		new c(b,"VideoCloseButton",null,this.closeVideoPlayer,null,this)
		this._playList=b.content.findName("PlayListArea");
		this._fsTargetCanvas=b.content.findName("FullScreenTargetCanvas");
		this._fsStrCanvas=b.content.findName("FullScreenStretchCanvas");
		this._fsa=b.content.findName("FullScreenArea");
		this._controlPanel=b.content.findName("ControlPanel");
		this._cpOriginalLeft=this._controlPanel["Canvas.Left"];
		this._cpOriginalTop=this._controlPanel["Canvas.Top"];

    },
	initPlayList:function()
	{
		initLangDO();//coolice
		
		var htmlString="",videoGrpName;
		this.expProduct=getXmlNodeByKeyValue(this.xmlRoot.getElementsByTagName('product'),this.expProductName);
		if (this.expProduct)
		{	this.videoGroup=this.expProduct.getElementsByTagName("video-groups")[0].getElementsByTagName("video-group");
			this.downloadAllUrl=this.expProduct.getElementsByTagName("download-all-link")[0].childNodes[0].nodeValue;
			this.downloadWords=this.xmlRoot.getElementsByTagName("config")[0].getElementsByTagName("download-all")[0].childNodes[0].nodeValue;
			this.fullscreenImg=this.xmlRoot.getElementsByTagName("config")[0].getElementsByTagName("fullscreen")[0].childNodes[0].nodeValue;
			this.subDownloadWords=this.xmlRoot.getElementsByTagName("config")[0].getElementsByTagName("download")[0].childNodes[0].nodeValue;
			
		}
		for (var i=0;i<this.videoGroup.length;i++)
		{
		    //the togglers
			videoGrpName=this.videoGroup[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
			var _downloadUrl=this.videoGroup[i].getElementsByTagName("downloadUrl")[0].childNodes[0].nodeValue;
			htmlString+='<div class="video-group" id="VideoGroup'+i+'"><a id="toggle'+i+'" onclick="javascript:toggleSlides('+i+')">'+videoGrpName+' ></a>'+'<div class="content" id="VideoHideGrp'+i+'">';
			
			//init videoArr
			var videoArr=[];
			this.videos_children=this.videoGroup[i].getElementsByTagName("videos")[0].childNodes;

			for (var k=0;k<this.videos_children.length;k++)
			{
				if (this.videos_children[k].nodeName=="video")
				{
					videoArr[videoArr.length]=this.videos_children[k];
				}
			}
			
			//the videos
			htmlString += "<ul class='bullet-list'>";
			var  tmpFN ="";
			var  tmpIdxSH =-1;
			var  tmpIdxCOM =-1;
			
			for (var j=0;j<videoArr.length;j++)
			{
				var videoLink=videoArr[j].getElementsByTagName("video")[0].childNodes[0].nodeValue;
				var titleStr=videoArr[j].getElementsByTagName("title")[0].childNodes[0].nodeValue;
				/*htmlString +="<li><a class='sub-items' id='subItem_toggle_i"+i+"_j"+j+"' onclick='javascript:onSubItemClicked("
							+'"'+videoLink+'",'+i+","+j+")'>"+ titleStr+"</a></li>";*/
				//coolice_start
				tmpFN = videoLink;
				tmpIdxSH = tmpFN.lastIndexOf('/');
				tmpIdxCOM = tmpFN.indexOf('.', tmpIdxSH);
				tmpFN = tmpFN.substring(tmpIdxSH+1, tmpIdxCOM);
				tmpFN = "<li><a class='sub-items' id='subItem_toggle_i"+i+"_j"+j+"' onclick='javascript:onSubItemClicked("+'"'+videoLink+'",'+i+','+j+',"'+tmpFN+'")'+"'>"+ titleStr+"</a></li>";
				//alert(tmpFN);
				htmlString +=tmpFN;
				//coolice_end
			}
			htmlString += "</ul>";
			
			if (_downloadUrl != "none") {
			    htmlString += "<div class='separator'></div>";
			
			    //the download link
			    htmlString+='<div class="download-img"></div><a class="download" id="pl_DownloadLink" onclick="javascript:onDownloadLinkClicked('+"'"+_downloadUrl+"'"+')">'+this.subDownloadWords+'</a><br/>'
			}
			
			htmlString+='</div></div>';
			
		}
		//alert(htmlString);
		document.getElementById("playlist").innerHTML = htmlString;
		
		for (var i=0;i<this.videoGroup.length;i++)
		{
			slideArr[i]=new Fx.Slide('VideoHideGrp'+i);
			slideArr[i].hide();
		}
		
		//fullscreen
		PlayerConfig.playerInstance._player.get_element().content.root.findName("FullScreenImg").Source = webRoot + this.fullscreenImg;
		
		//download all
          	if(this.downloadAllUrl!="javascript:void(0);")
			document.getElementById("download-all").innerHTML="<a onclick='javascript:onDownloadAllClicked("+'"'+this.downloadAllUrl+'"'+");' title='" + this.downloadWords + "'>"+this.downloadWords+"</a>";
		
	    //init player first video
	    toggleSlides(0);
        
        setTimeout(function() {
            try {
                var firstSubItem = document.getElementById("subItem_toggle_i0_j0");
                
                if (firstSubItem != null) {
                    firstSubItem.onclick();
                }
            }
            catch(e) {
            
            }
        },2000);
	},
	createXMLHttpRequest: function(xmlURL) 
	{
	    if (window.XMLHttpRequest) { // If XMLHttpRequest available
	        this.xmlHttp = new XMLHttpRequest();  // Mozilla?Firefox?Safari
	    }
	    else if (window.ActiveXObject) { // If ActiveXObject available
	        this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
	    }
		if(this.xmlHttp) { // do request
		    this.xmlHttp.onreadystatechange = Function.createDelegate(this,this.handleStateChange);//handleStateChange;  
		    this.xmlHttp.open("GET", xmlURL);  // open the link
		    this.xmlHttp.send(null);  // send request	
		}
		else {
			alert("Your browser does not support this function.");
		}

	},
	handleStateChange:function () 
	{
	   if (this.xmlHttp.readyState == 4&&this.xmlHttp.status == 200) 
		{ 
			this.IsXMLLoaded=true;
			this.configXML=this.xmlHttp.responseXML;
			if (Silverlight.ua.browser=="Firefox")
			{	
				var parser=new DOMParser();
				this.configXML=parser.parseFromString(this.xmlHttp.responseText,"text/xml");
			}
			this.xmlRoot=this.configXML.getElementsByTagName('products')[0];
			this.TotalNum=this.xmlRoot.getElementsByTagName('product').length;
			
			this.initPlayList();
	    }
	},
	closeVideoPlayer:function()
	{
        hideModal();
        
        //clear the div, without it will have js error
        var widgetContainer = $(ModalConfig.widgetContainer);
		
		if (BrowserDetect.browser == "Explorer") {
			widgetContainer.innerHTML = "";
		}
	},
	playNextClip:function()
	{
		var j=this.subItemInd+1;
		var i=this.groupInd;
		var videoArrLength=this.getVideoArrLength(i);
		if (j>=videoArrLength)
		{
			j-=videoArrLength;
			i=i+1;
		}
		if (i<this.videoGroup.length)
		{
			var templink=this.getVideoLink(i,j);
			onSubItemClicked(templink,i,j);
		}
	},
	getVideoArrLength:function(i)
	{
		var videoArr=[];
		var children=this.videoGroup[i].getElementsByTagName("videos")[0].childNodes;
		for (var k=0;k<children.length;k++)
		{
			if (children[k].nodeName=="video")
			{
				videoArr[videoArr.length]=children[k];
			}
		}
		var res=videoArr.length;
		videoArr=null;
		return res;
	},
	getVideoLink:function(i,j)
	{
		var videoArr=[];
		var children=this.videoGroup[i].getElementsByTagName("videos")[0].childNodes;
		for (var k=0;k<children.length;k++)
		{
			if (children[k].nodeName=="video")
			{
				videoArr[videoArr.length]=children[k];
			}
		}
		videoArr=null;
		return videoArr[j].getElementsByTagName("video")[0].childNodes[0].nodeValue;
	},
	highlightSection:function(i,j)
	{
		if (this.groupInd>=0)
		{
			document.getElementById("VideoGroup"+this.groupInd).style.background="#000";
		}
		if (this.subItemInd>=0)
		{
			document.getElementById("subItem_toggle_i"+this.groupInd+"_j"+this.subItemInd).style.fontWeight="400";
			
		}
		
		this.groupInd=i;
		document.getElementById("VideoGroup"+this.groupInd).style.background="#222";
		
		this.subItemInd=j;
		document.getElementById("subItem_toggle_i"+this.groupInd+"_j"+this.subItemInd).style.fontWeight="700";
	}
}

ExtendedPlayer.Player.registerClass('ExtendedPlayer.Player', EePlayer.Player);

//try to override _fullScreenChanged event handler
ExtendedPlayer.Player.prototype._fullScreenChangedSupplement=function(){
//alert('full');
	this._fullScreenChanged();
	var IsFullScreen=this.get_element().content.fullscreen,
		FSHeight=this.get_element().content.ActualHeight,
		FSWidth=this.get_element().content.ActualWidth,
		xScale=FSWidth/this._fsStrCanvas.Width,
		yScale=FSHeight/this._fsStrCanvas.Height;
	var scale=Math.min(xScale,yScale);
	
	var st=this._fsStrCanvas.RenderTransform.Children.getItem(0);//scale transform of FullScreenStretchCanvas
	var tt=this._fsStrCanvas.RenderTransform.Children.getItem(3);//translate transform of FullScreenStretchCanvas
	var targetST=this._fsTargetCanvas.RenderTransform.Children.getItem(0);//scale transform of FullScreenTargetCanvas
	var targetTT=this._fsTargetCanvas.RenderTransform.Children.getItem(3);//scale transform of FullScreenTargetCanvas
	
	
	this._playList.Opacity=IsFullScreen?0:1;
	this._fsa.Visibility=IsFullScreen?"Collapsed":"Collapsed";

	if (IsFullScreen)
	{
		st.ScaleX=xScale;
		st.ScaleY=yScale;
		tt.X=-this._fsStrCanvas["Canvas.Left"];
		tt.Y=-this._fsStrCanvas["Canvas.Top"];
		targetST.ScaleY=scale/yScale;
		targetST.ScaleX=scale/xScale;

		this._controlPanel["Canvas.Left"]=this._fsStrCanvas.Width*(xScale-1)/2;
		this._controlPanel["Canvas.Top"]+=this._fsStrCanvas.Height*(yScale-1)/2*1.3;

		if (yScale > scale)
		{
			targetTT.Y += (FSHeight / scale - this._fsStrCanvas.Height) / 2;//fit y position
		}
        	else
        	{
            		targetTT.X += (FSWidth / scale - this._fsStrCanvas.Width) / 2;//fit x position 
		}
	}
	else
	{
		st.ScaleX=1.0;
		st.ScaleY=1.0;
		targetST.ScaleX=1.0;
		targetST.ScaleY=1.0;
		targetTT.X=0;
		targetTT.Y=0;
		tt.X=0;
		tt.Y=0;
		
		this._controlPanel["Canvas.Left"]=this._cpOriginalLeft;
		this._controlPanel["Canvas.Top"]=this._cpOriginalTop;
	}
		
}
function getXmlNodeByKeyValue(NodeArray,KeyValue)
{	
	for (var i=0;i<NodeArray.length;i++)
	{
		if (KeyValue==NodeArray[i].getAttributeNode("key").nodeValue)
			return NodeArray[i];
		else
			continue;
	}
	
	return null;
}
function initExpVideoXML(){
		var xotree=new XML.ObjTree();
		
		global_XMLTree=xotree.parseHTTP(webRoot + PlayerConfig.dataSource.replace("[key]",PlayerConfig.key));
		var iCount=0;
		while(global_XMLTree.products.product[iCount])
		{	
			iCount++;
		}
		
		global_ProductTotalNum=iCount++;
		
}
toggleSlides=function(i)
{

	if (slideArr[i])
	{
		slideArr[i].toggle();
	}
}
onSubItemClicked=function(link,i,j)
{
	PlayerConfig.playerInstance._player.set_mediainfo(get_mediainfoFromLink(link));
	PlayerConfig.playerInstance._player.highlightSection(i,j);
}
onSubItemClicked=function(link,i,j, videoFN)
{
	PlayerConfig.playerInstance._player.set_mediainfo(get_mediainfoFromLink(link));
	PlayerConfig.playerInstance._player.highlightSection(i,j);
	
	changeVideoDO(videoFN); //coolice
}
onDownloadLinkClicked=function(downloadUrl)
{
	if (confirm(msgDownload)){
		window.open(downloadUrl);
	}
}
onDownloadAllClicked=function(downloadUrl)
{
	if (confirm(msgDownload)){
		window.open(downloadUrl);
	}
}

