﻿var bcExp, modVP, modExp, modCon, modSocial;
var videoList,playList, queryVideoID, queryPlaylistID;
var LoadedUsingVideoIDAndPlayListID = false;
var LoadedUsingVideoID = false;
var isTemplateReady = false;
var const_videoIDParam = "videoid";
var const_playListIDParam = "playlistid";
var const_linkURL = "www.hollywood.com/trailer/external/";
var const_dyanmicTabName = "Latest Videos"; //"Requested Video"
var FirstVideo = true;
 
function onTemplateLoaded(experienceID) 
{
    bcExp = brightcove.getExperience(experienceID);
 
	modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
	modSocial = bcExp.getModule(APIModules.SOCIAL);
	
    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady); 
    modVP.addEventListener(BCMediaEvent.BEGIN,mediaBegin );
	modCon.addEventListener(BCContentEvent.MEDIA_LOAD, onMediaLoad);
}

function getPlayListIndex(playlistID)
{
 	var numitems = playList.getNumItems();
	var listData;
	
	for(i=0;i<numitems;i++)
	{
	  listData = playList.getDataAtIndex(i);
	  if(listData.id == playlistID)
	  {
	    return i;
	  }
	}
	//Notfound
}

function CreateTempPlaylist(playListName)
{
	var numitems = playList.getNumItems();
	var listData;
	var foundPlaylist=false;
	var count = 0;
	
	for(i=0;i<numitems;i++)
	{
	  listData = playList.getDataAtIndex(i);
	  if(listData.displayName == playListName)
	  {
		playList.setSelectedIndex(i);
		videoList.showPlaylist(listData.id);
	    foundPlaylist=true;
		break;
	  }
	}
	
	if(foundPlaylist == false)
	{
		var mediaDTOs = new Array();
		var newPlaylist = { displayName: playListName, mediaIds: mediaDTOs};
		var runtimeLineup = modCon.createRuntimeMediaCollection(newPlaylist,"playlist");
		playList.insertTabAt(runtimeLineup, numitems);
		listData = playList.getDataAtIndex(numitems);
		playList.setSelectedIndex(numitems);
		videoList.showPlaylist(listData.id);
	}
}

function LoadUsingVideoIDAndPlayerID(videoID,playListID)
{
	if(isTemplateReady)
	{
		 playList.setSelectedIndex(getPlayListIndex(playListID));
		 videoList.showPlaylist(playListID);
		 LoadedUsingVideoIDAndPlayListID = true;
		 modCon.getMediaAsynch(videoID);
		 window.scrollTo(0,0);	
		 return false;
	}
	else
	{
		return true;
	}
}

function LoadUsingPlayListID(playListID)
{
   var numitems = playList.getNumItems();
   for(i=0;i<numitems;i++)
    {
      listData = playList.getDataAtIndex(i);
      if(listData.id == playListID)
      {
            playList.setSelectedIndex(i);
            videoList.showPlaylist(listData.id);
            break;
      }
    }
}


function LoadUsingVideoID(videoID)
{
   	if(isTemplateReady)
	{
		CreateTempPlaylist(const_dyanmicTabName);
		LoadedUsingVideoID =true;
		modCon.getMediaAsynch(videoID);			
		return false;
	}
	else
	{
		return true;
	}
}

function SmartLoadUsingVideoID(videoID)
{
	var numitems = playList.getNumItems();
	var listData;
		
	for(i=0;i<numitems;i++)
	{
	  listData = playList.getDataAtIndex(i);
	  for(j=0;j<listData.videoIds.length;j++)
	  {
	    if(listData.videoIds[j]==videoID)
		{
		  LoadUsingVideoIDAndPlayerID(videoID,listData.id);
		  return;
		}
	  }
	}

	LoadUsingVideoID(videoID);
}

function onTemplateReady(evt) 
{
	videoList = modExp.getElementByID("videoList");
	playList = modExp.getElementByID("playlistTabs");
	
	queryVideoID= getQueryVariable(const_videoIDParam);
    queryPlaylistID = getQueryVariable(const_playListIDParam);
	
	isTemplateReady =true;

	if(queryVideoID !=null &&  queryPlaylistID!=null)
	{ 
		LoadUsingVideoIDAndPlayerID(queryVideoID,queryPlaylistID);
	}
	else if(queryVideoID !=null)
	{
	  SmartLoadUsingVideoID(queryVideoID);
	}
	else if(BrightcovePlayListID != null && BrightcovePlayListID != "0")
    {
       LoadUsingPlayListID(BrightcovePlayListID);
    }
	else if (BrightcoveID != null && BrightcoveID != "0")
	{
	  SmartLoadUsingVideoID(BrightcoveID);
	}	
	
	try
	{
		var currentVideo = modVP.getCurrentVideo();
		setLink(currentVideo.id);
	}
	catch(e)
	{ 
	  // do nothing
	}
		
}

function onMediaLoad(e) 
{	
	if(LoadedUsingVideoIDAndPlayListID)
	{
		var temparray = videoList.getData(); // get the current items in the list
		var count=0;
		var tempID;
		for(;count<temparray.length;count++)
		{
			tempID = temparray[count].id;
			if(tempID == e.media.id)
			{
			  videoList.setSelectedIndex(count);
			  break;
			}
		}
	
		LoadedUsingVideoIDAndPlayListID=false;
	}
	else if(LoadedUsingVideoID)
	{
		var mediaDTOs = new Array(); // SetData requires an array
		var temparray = videoList.getData(); 
		var count=0;
		mediaDTOs[count]  =  modCon.getMedia(e.media.id); 
		count = count + 1;
		for(;count<=temparray.length;count++)
		 {
 		   mediaDTOs[count] =  temparray[count-1]; 
		 }
		videoList.setData(mediaDTOs); 
		videoList.setSelectedIndex(0);
		LoadedUsingVideoID=false;
	}
}

function mediaBegin(evt) 
{
	//This is a hack to set the selected video if it is not set. This code ideally should have been 
	//placed in onMediaLoad event - LoadedUsingVideoIDAndPlayListID
	//Hack Start --
	var arr = videoList.getSelectedData();
	if(arr == null)
	{
		var temparray = videoList.getData(); // get the current items in the list
		var count=0;
		var tempID;
		for(;count<temparray.length;count++)
		{
			tempID = temparray[count].id;
			if(tempID == evt.media.id)
			{
			  videoList.setSelectedIndex(count);
			  break;
			}
		}
	}
	// -- Hack End
	
	if(FirstVideo)
    {
        FirstVideo = false;
    }
    else
    {
        IntilaizeSiteCatalystParam(evt.media.referenceId, evt.media.shortDescription, evt.media.tags);
        hbxPagename ="/home";
        hbxContentCategory ="/trailers";
        RefreshFrames();
    }
	
	setLink(evt.media.id);
	//alert("EVENT: Media Begin" +  evt.media.displayName );
}

function setLink(videoID)
{
	var newLink = const_linkURL + videoID;
	modSocial.setLink(newLink);
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0].toLowerCase()== variable.toLowerCase()) {
      return pair[1];
    }
  }
}

//Start: Intialize Video SiteCatalyst
function IntilaizeSiteCatalystParam(Content_ID, Content_Title, Tags)
{    
    try
    {    
        var _Prop1, _Prop2, _Prop3, Heir, Tags, TotalTags, Priority, tempPriority, Content_Type, tempContent_Type;
        _Prop1 = 'video';
        Priority = null;
       
       //Tags Starts
        var TotalTags = Tags.length;
        for (var i = 0; i < TotalTags; i++)
        {
            tempPriority = null;
            tempContent_Type = null;
            
            switch(Tags[i].name.toLowerCase())
            {
                case 'trailer':
                    tempPriority = 1;
                    tempContent_Type = 'trailer';
                    break;
                case 'interview':
                    tempPriority = 2;
                    tempContent_Type = 'video interview';
                    break;
                case 'movie clip':
                    tempPriority = 3;
                    tempContent_Type = 'video clip';
                    break;
                case 'tv clip':
                    tempPriority = 4;
                    tempContent_Type = 'tv clip';
                    break;
                case 'celeb':
                    tempPriority = 5;
                    tempContent_Type = 'video interview';
                    break;
                case 'dvd preview':
                    tempPriority = 6;
                    tempContent_Type = 'dvd preview';
                    break;
                case 'dvd trailer':
                    tempPriority = 7;
                    tempContent_Type = 'dvd trailers';
                    break;
                case 'podcast':
                    tempPriority = 8;
                    tempContent_Type = 'podcast';
                    break;
                case 'tv trailer':
                    tempPriority = 9;
                    tempContent_Type = 'tv trailers';
                    break;
                case 'tv video':
                    tempPriority = 10;
                    tempContent_Type = 'tv video';
                    break;
                case 'video clip':
                    tempPriority = 11;
                    tempContent_Type = 'video clip';
                    break;
                case 'event':
                    tempPriority = 12;
                    tempContent_Type = 'video events/award';
                    break;
                case 'award':
                    tempPriority = 13;
                    tempContent_Type = 'video events/award';
                    break;
                case 'premiere':
                    tempPriority = 14;
                    tempContent_Type = 'video premiere';
                    break;
            }   
            
            if(Priority == null || typeof( Priority ) == 'undefined')
            {
                if(tempPriority != null || typeof( tempPriority ) != 'undefined')
                {
                    Priority = tempPriority;
                    Content_Type = tempContent_Type;
                }
            }
            else
            {
                if(tempPriority < Priority)
                {
                    Priority = tempPriority;
                    Content_Type = tempContent_Type;
                }
            }
        }

        if(Content_Type == null || typeof( Content_Type ) == 'undefined')
        {
            _Prop2 = "video interview";
            hbxContentCategory = "/" + "video interview";
        }
        else
        {
            _Prop2 = Content_Type;
            hbxContentCategory = "/" + Content_Type;
        }
        //Tags ends

        //Content title Starts
        if(typeof( Content_Title ) == "undefined")
        {
            Content_Title = 'content title is not exists';
        }
        else
        {            
            Content_Title = Content_Title.toLowerCase();
            Content_Title = Content_Title.replace(/<[^>]*>|\n/g, " ");
            Content_Title = Content_Title.replace(/[^0-9a-zA-Z_\s]/g, "_");
            Content_Title = Content_Title.replace("  ", " ");
            Content_Title = Trim(Content_Title);
        }
        //Content title ends
        
        //Content id Starts
        if(Content_ID != null)
        {   
            Content_ID = Content_ID.toLowerCase();
            Content_ID = Content_ID.replace('_title','');
            Content_ID = Content_ID.replace('_hw','');
            Content_ID = Trim(Content_ID);        
        }
        else
        {
            Content_ID = 'content id is not exists';
        }
        //Content id ends
        
        _Prop3 = '(' + Content_ID + ') ' + Content_Title;
        if(_Prop3.length >= 255)
        {
            _Prop3 = _Prop3.substring(0, 255);
        }
        
        Heir = _Prop1 + ':' + _Prop2 + ':' + _Prop3;
        if(Heir.length >= 255)
        {                   
            Heir = Heir.substring(0, 255);
        }
               
        vars = new Object();
        vars.prop1 = _Prop1;
        vars.prop2 = _Prop2;
        vars.prop3 = _Prop3;
        vars.prop4 = "";
        vars.hier1 = Heir;
        vars.pageName = Heir.replace(/:/g, "/");        
    }
    catch(err)
    {       
        vars = new Object();
        vars.prop1 = "video";
        vars.prop2 = "home";
        vars.prop3 = "";
        vars.prop4 = "";
        vars.hier1 = "video:home";
        vars.pageName = Heir.replace(/:/g, "/");
    }
    //alert('completed');
}

//End: Intialize Video SiteCatalyst