var xmlHttp = new XMLHttpRequest();


var g_httpport=0;
var g_server_http_ip_port='';
var g_server_streaming_ip_port='';


var g_total_channel_category_no=0;
var g_Channel_Categories_tems=[];
var g_total_movie_category_no=0;
var g_Movie_Categories_tems=[];
var g_total_series_category_no=0;
var g_Series_Categories_tems=[];

var transformedChannelCategory = { categories: [] };
var transformedMovieCategory = { categories: [] };
var transformedSeriesCategory = { categories: [] };
var nContentCategoriesTotalNo=0;
var jsonSeriesEpisodesList=null;
var filteredCategory=null;

const iconListContainer = document.getElementById('iconlist');
const iconListContainer2 = document.getElementById('iconlist2');

var nCurrentContent = 0;
const CHANNEL = 1;
const MOVIE = 2;
const SERIES = 3;
const EPISODES = 4;
const FILTER_MOVIE = 5;
const FILTER_SERIES = 6;
var videoPlayer
var g_focusedElementId;
  
var menuindex=1;
var menuid=null;

var imageIcons=[];
var imageIcons2=[];
var nCurrentCategoryFirstIndex=0;
var nCurrentCategorySecondIndex=0;
var g_cur_series_name;
var bMobileDevice=0;
var main_screen_str;
var parentnode;
var main_screen;
var content_screen;
var bAndroidFullScreen=false;
var g_contentname=null;

var screenWidth = window.screen.width;
var screenHeight = window.screen.height;

let currentIndex = 0;
let currentIndex1 = 0;
let currentIndex2 = 0;
let currentContainer = iconListContainer; // Store the current container
/*
function playVideo(videoSource) {
	var play = videojs('hls-example');
   play.stop();
    const videoPlayer = document.getElementById('hls-example');
   // alert(videoSource);
    videoPlayer.src = videoSource;
    videoPlayer.load();
    videoPlayer.play();
}
*/
/*
function playVideo(videoSource) {
  var videoPlayer = document.getElementById('hls-example');
   var play;
  if (nCurrentContent == CHANNEL)
  {
  	alert(videoSource);
	   videoPlayer.innerHTML='<source type="application/x-mpegURL" src="'+videoSource+'">';
	  play = videojs('hls-example');
	   play.play();
   }else
   {
   	play = videojs('hls-example');
   	play.pause();
videoPlayer = document.getElementById('hls-example');
   	 videoPlayer.innerHTML='<source type="application/x-mpegURL" src="'+videoSource+'">';
	  play = videojs('hls-example');
	   play.play();
   }
}
*/
function alertmessage(message)
{
	if (isAndroid())
	{
		Android.AlertMessage(message);
	}else
	{
		alert(message);
	}
}
function playVideo(videoSource) {
  if (isAndroid()) {
            // Use Android-specific methods
            //Android.AlertMessage(videoSource);
            //Android.AlertMessage(screenWidth);
            Android.playVideo(videoSource,(screenWidth-320),20,640,320);
  }else
  {
	  var currentSource = videoPlayer.src();
	  videoPlayer.muted(true);
	  if (nCurrentContent == CHANNEL) {
	    // If the current content is a channel, play the HLS stream
	    if (currentSource !== videoSource) {
	      videoPlayer.src({ type: 'application/x-mpegURL', src: videoSource });
	      videoPlayer.play();
	    }
	  } else {
	    // If the current content is not a channel, play the MP4 video
	    if (currentSource !== videoSource) {   
	    		
	      videoPlayer.src({ type: 'video/mp4', src: videoSource });
	      videoPlayer.play();
	    }
	  }
  }
}

function handleIconClick(contentname) {
     var episode_string = null;
     
    if (nCurrentContent == SERIES || nCurrentContent == FILTER_SERIES) {
        get_episodes_list(contentname);
    } else {
        if (nCurrentContent == EPISODES) {
		if (isAndroid()) {
		// Use Android-specific methods
			Android.playVideo(contentname,0,0,0,0);
		}else
			{
    // alert(contentname);
			playVideo(contentname);
		}
	}
//g_focusedElementId = document.activeElement.id;
 
         g_contentname=contentname;

        if (isAndroid()) {
            // Use Android-specific methods
          //  videoPlayer.pause();
        //    Android.playVideo(contentname,20,20,640,320);
            Android.playVideo(contentname,0,0,0,0);
            bAndroidFullScreen=true;
        }else 
        {
       		var videoElement = videoPlayer.el(); // Get the video element
	           videoPlayer.controls(true);
	        videoPlayer.muted(false);
	    	if (videoElement.requestFullscreen) {
	            videoElement.requestFullscreen();
	        } else if (videoElement.mozRequestFullScreen) { // Firefox
	            videoElement.mozRequestFullScreen();
	        } else if (videoElement.webkitRequestFullscreen) { // Chrome, Safari and Opera
	            videoElement.webkitRequestFullscreen();
	        } else if (videoElement.msRequestFullscreen) { // IE/Edge
	            videoElement.msRequestFullscreen();
	        }
        }
    }
}

function isAndroid() {
    // Check if the user agent indicates Android
    return /Android/i.test(navigator.userAgent);
}


function getEPGInfo(channel_name) {
    var cgi_url;
    document.getElementById('content_name').innerText = channel_name;

    cgi_url = g_server_http_ip_port + "/server/get_epg_list_json?token=" + g_token + "&name=" + channel_name + "&flag=" + Math.random();
    xmlHttp.open("GET", cgi_url, true);
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) {
            var response = xmlHttp.responseText;
            var jsonInfo = JSON.parse(response);
            
            // Clear previous content
            document.getElementById('content_info').innerHTML = '';
            
            // Display each epg listing
            for (var i = 0; i < jsonInfo.epg_listings.length; i++) {
                var listing = jsonInfo.epg_listings[i];
                var listingHTML = '<h1 style="font-size:24px;">' +
                    listing.start.slice(11, 16) + ' ~ ' +
                    listing.end.slice(11, 16) + ' ' +
                    listing.title +
                    '</h1><br>';
                document.getElementById('content_info').innerHTML += listingHTML;
                if (i==2) break;
            }
            document.getElementById('content_runnning_description').innerHTML='';
            for (var i = 0; i < jsonInfo.epg_listings.length; i++) {
                var listing = jsonInfo.epg_listings[i];
                var listingHTML = '<h1 style="font-size:24px;">&nbsp;&nbsp;&nbsp;' +
                    listing.start.slice(11, 16) + ' ~ ' +
                    listing.end.slice(11, 16) + ' ' +
                    listing.title +
                    '</h1>';
                document.getElementById('content_runnning_description').innerHTML += listingHTML;
            }
        }
    };
    xmlHttp.send(null);
}

function getMovieInfo(movie_name)
{
	var cgi_url;
	document.getElementById('content_name').innerText=movie_name;
	
	cgi_url = g_server_http_ip_port+"/server/get_movie_info_json?token="+g_token+"&name="+movie_name+"&flag="+Math.random();
	xmlHttp.open("GET", cgi_url, true);
	xmlHttp.onreadystatechange  = function()
		{
			if (xmlHttp.readyState == 4) 
			{
				//nCurrentContent = MOVIE;
				var response = xmlHttp.responseText;
				//alert(response)
				var jsonMovieInfot = JSON.parse(response);
				//alert(jsonMovieInfot.description);
				//alert(window.innerWidth);
				document.getElementById('content_info').innerHTML='<h1 style="font-size:24px;">Duration: '+jsonMovieInfot.duration+' Min.<br>'+
				'Quality: '+jsonMovieInfot.quality+'<br><br>'+
				jsonMovieInfot.description+'</h1>';
				document.getElementById('content_runnning_description').innerText=jsonMovieInfot.description;
				
			}
		};
	xmlHttp.send(null);
}
function getSeriesInfo(series_name)
{
	var cgi_url;
	document.getElementById('content_name').innerText=series_name;
	//alert(series_name);
	
	cgi_url = g_server_http_ip_port+"/server/get_series_info_json?token="+g_token+"&name="+series_name+"&flag="+Math.random();
	xmlHttp.open("GET", cgi_url, true);
	xmlHttp.onreadystatechange  = function()
		{
			if (xmlHttp.readyState == 4) 
			{
				//nCurrentContent = SERIES;
				var response = xmlHttp.responseText;
				//alert(response)
				var jsonSeriesInfo = JSON.parse(response);
				//alert(jsonMovieInfot.description);
				//alert(window.innerWidth);
				document.getElementById('content_info').innerHTML='<h1 style="font-size:24px;">Season No.: '+jsonSeriesInfo.season_no+'<br>'+
				'Release Date: '+jsonSeriesInfo.released_date+'<br>'+
				'Rating: '+jsonSeriesInfo.rating+'<br><br>'+
				jsonSeriesInfo.description+'</h1>';
				document.getElementById('content_runnning_description').innerText=jsonSeriesInfo.description;
				
			}
		};
	xmlHttp.send(null);
}
function updateImageIcons(container, icons, currentIndex,categoryIndex) {
    var iconsToShow = icons.slice(currentIndex, currentIndex + 9);
    var iconsHTML;
    var contentName = null;
    var contentLink = null;
    var seasonindex=categoryIndex+1;
    var fwdURL=null;
    

    if (container.id == "iconlist") {
    	if (nCurrentContent == EPISODES)
    	{
    		iconsToShow = icons.slice(currentIndex, currentIndex + 20);
    	}
        iconsHTML = iconsToShow.map((icon, index) => {
        
            const borderStyle = index === 0 ? "border: 5px solid yellow;" : "";
              
            
          //  alert(contentName);
          g_server_streaming_ip_port="http://"+g_serverip+":"+g_httpport;
          if (nCurrentContent == CHANNEL)
          {
          	contentName = transformedChannelCategory.categories[categoryIndex].items[currentIndex + index].name;
          	fwdURL = transformedChannelCategory.categories[categoryIndex].items[currentIndex + index].fwdURL;
          	
          	if (isAndroid())
          	{
          		contentLink = `${g_server_streaming_ip_port}/${escape(contentName)}`+"?token="+g_token;
          	}else
          	{
          		if (fwdURL!=null)
          		{
          			contentLink=fwdURL;
          		}else
          		{
          			contentLink = `${g_server_streaming_ip_port}/${contentName}`+".m3u8?token="+g_token;
          		}
          	}
          	
          	if (transformedChannelCategory.categories[categoryIndex].items[currentIndex + index].icon=="")
          	{
          		return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle} text-align: center;" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"><font color=#ffffff>${contentName}</font></div>`;
          	}else
          	{
	        	return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle}" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
	        }
          }else if (nCurrentContent == MOVIE)
   	  {
          	contentName = transformedMovieCategory.categories[categoryIndex].items[currentIndex + index].name;
   		contentLink = `${g_server_streaming_ip_port}/${escape(contentName)}`+"?token="+g_token;
   		if (transformedMovieCategory.categories[categoryIndex].items[currentIndex + index].icon=="")
   		{
   			
   			return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle} text-align: center;" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"><font color=#ffffff>${contentName}</font></div>`;
   		}else
   		{
	        	return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle}" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
	        }
   	  }else if (nCurrentContent == SERIES)
   	  {
          	contentName = transformedSeriesCategory.categories[categoryIndex].items[currentIndex + index].name;
   		contentLink = contentName;
   		//alert(contentLink);
   		if (transformedSeriesCategory.categories[categoryIndex].items[currentIndex + index].cover=="")
   		{
   			return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle} text-align: center;" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"><font color=#ffffff>${contentName}</font></div>`;
	        }else
   		{
	        	return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle}" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
	        }
 	  }else if (nCurrentContent == EPISODES) {
 	 	
       		contentName = g_cur_series_name + " S" + seasonindex.toString().padStart(2, '0') + " E" + icon.toString().padStart(2, '0');
       		//alert(contentName);
        	contentLink = g_server_streaming_ip_port + "/" + escape(contentName) + "?token=" + g_token;
		return `<div class="episode-grid" style="${borderStyle} font-family: Arial;font-weight: bold; font-size:32px; color: white;" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0">${icon}</div>`;
	  }else if (nCurrentContent == FILTER_MOVIE)
	  
	  {
          	contentName = filteredCategory.categories[categoryIndex].items[currentIndex + index].name;
   		contentLink = `${g_server_streaming_ip_port}/${contentName}`+"?token="+g_token;
	        return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle}" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
	  }else if (nCurrentContent == FILTER_SERIES)	  
	  {
          	contentName = filteredCategory.categories[categoryIndex].items[currentIndex + index].name;
   		contentLink = contentName;
   		//alert(contentLink);
	        return `<div class="image-icon" style="background-image: url('${icon}'); ${borderStyle}" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
	  }

          //  alert(contentLink);
 
         });
    } else {
        iconsHTML = iconsToShow.map((icon, index) => {
            const borderStyle = index === 0 ? "border: 2px solid white;" : "";
         //  alert(contentName);
         g_server_streaming_ip_port="http://"+g_serverip+":"+g_httpport;
          if (nCurrentContent == CHANNEL)
          {
          	contentName = transformedChannelCategory.categories[categoryIndex].items[currentIndex + index].name;
          	if (isAndroid())
          	{
          		contentLink = `${g_server_streaming_ip_port}/${contentName}`+"?token="+g_token;
          	}else
          	{
          		if (fwdURL!=null)
          		{
          			contentLink=fwdURL;
          		}else
          		{
            			contentLink = `${g_server_streaming_ip_port}/${contentName}`+".m3u8?token="+g_token;
            		}
            	}
            	
        	return `<div class="image-icon2" style="background-image: url('${icon}'); " onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
          }else if (nCurrentContent == MOVIE)
          {
          	contentName = transformedMovieCategory.categories[categoryIndex].items[currentIndex + index].name;
            	contentLink = `${g_server_streaming_ip_port}/${contentName}`+"?token="+g_token;;
         	return `<div class="image-icon2" style="background-image: url('${icon}'); " onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
          }else if (nCurrentContent == SERIES)
          {
          	contentName = transformedSeriesCategory.categories[categoryIndex].items[currentIndex + index].name;
            	contentLink = `${g_server_streaming_ip_port}/${contentName}`+"?token="+g_token;;
	        return `<div class="image-icon2" style="background-image: url('${icon}');" onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0"></div>`;
         }else if (nCurrentContent == EPISODES) {
 	 	
       		contentName = g_cur_series_name + " S" + seasonindex.toString().padStart(2, '0') + " E" + icon.toString().padStart(2, '0');
       		//alert(contentName);
        	contentLink = g_server_streaming_ip_port + "/" + contentName + "?token=" + g_token;
		return `<div class="episode-grid2" style="color: white;font-family: Arial;font-weight: bold; font-size:32px;"  onclick="handleIconClick('${contentLink}')" onkeydown="if(event.key==='Enter'){handleIconClick('${contentLink}')}" tabindex="0">${icon}</div>`;
	 }

             //  alert(contentLink);
        
         });
    }

    container.innerHTML = iconsHTML.join('');
    if (container.id === "iconlist")
    {
	    g_focusedElementId = container.querySelector("[tabindex='0']");
	    if (g_focusedElementId) {
	        g_focusedElementId.focus();
	        if (nCurrentContent == CHANNEL)
          	{
	         	contentName = transformedChannelCategory.categories[categoryIndex].items[currentIndex].name;
	          	if (isAndroid())
	          	{
	          		contentLink = `${g_server_streaming_ip_port}/${escape(contentName)}`+"?token="+g_token;;
	            	}else
	          	{
	          		if (fwdURL!=null)
	          		{
	          			contentLink=fwdURL;
	          		}else
	          		{
	            			contentLink = `${g_server_streaming_ip_port}/${contentName}`+".m3u8?token="+g_token;;
	            		}
	            	}
	            	//document.getElementById(content_description).innerText=contentName;
		      // 	alert(contentLink);
			//document.getElementById('content_name').innerText=contentName;
			getEPGInfo(contentName);
	   		playVideo(contentLink);
	 	}else if (nCurrentContent == MOVIE)
          	{
	             	contentName = transformedMovieCategory.categories[categoryIndex].items[currentIndex].name;
	            	contentLink = `${g_server_streaming_ip_port}/${escape(contentName)}`+"?token="+g_token;
	            	//alert(document.getElementById('content_name'));
	            	//document.getElementById(content_runnning_description).innerText=transformedMovieCategory.categories[categoryIndex].items[currentIndex].
	            	//alert(document.getElementById('content_runnning_description'));
		       	//alert(contentLink);
		        getMovieInfo(contentName);
			
	   		playVideo(contentLink);
	       	}else  if (nCurrentContent == SERIES)
	       	{
	       		contentName = transformedSeriesCategory.categories[categoryIndex].items[currentIndex].name;
//	       		document.getElementById('content_name').innerText=contentName;
			//document.getElementById('content_name').innerText=contentName;
			getSeriesInfo(contentName)
	       	}else if (nCurrentContent == EPISODES) 
       		{
       			contentName = g_cur_series_name + " S" + seasonindex.toString().padStart(2, '0');
        			
	            	document.getElementById('content_name').innerText=contentName;
      		}else if (nCurrentContent == FILTER_MOVIE)
      		{
	             	contentName = filteredCategory.categories[categoryIndex].items[currentIndex].name;
	            	contentLink = `${g_server_streaming_ip_port}/${contentName}`+"?token="+g_token;
		        getMovieInfo(contentName);
			playVideo(contentLink);
      		}else if (nCurrentContent == FILTER_SERIES)
      		{
	             	contentName = filteredCategory.categories[categoryIndex].items[currentIndex].name;
	            	//contentLink = `${g_server_streaming_ip_port}/${contentName}`+"?token="+g_token;
		        getSeriesInfo(contentName);
			
      		}
             	
	    }
    }
}

function handleArrowKeys(event) {
    var Category_text=null;
    var transformedCategory;
    var keyCode = event.keyCode || event.which;
 //   alert(keyCode);
  //  alert(currentIndex);
    if (keyCode === 461)
    {
    	if ((document.fullscreenElement || // Standard
	            document.webkitFullscreenElement || // Chrome, Safari, and Opera
	            document.mozFullScreenElement || // Firefox
	            document.msFullscreenElement))
	{
	            videoPlayer.muted(true);
	            if (document.exitFullscreen) {
	                    document.exitFullscreen();
	                } else if (document.webkitExitFullscreen) {
	                    document.webkitExitFullscreen();
	                } else if (document.mozCancelFullScreen) {
	                    document.mozCancelFullScreen();
	                } else if (document.msExitFullscreen) {
	                    document.msExitFullscreen();
	            }
	          
	            return;
	}else
	{
		 webOS.platformBack();
		 return;
	}
    }else 
    	
    if ((event.key === 'Enter') && (currentIndex >= 0) && (nCurrentContent != SERIES))
    {
     	handleIconClick(g_contentname);
     	return;
    }
/*    else if ((isAndroid()) && (event.key === 'ArrowLeft') && (bAndroidFullScreen==true))
    {
    	
     	//videoPlayer.muted(true);
   	Android.playVideo(g_contentname,400,20,640,320);
   	return;

	}
*/	
/*else if ((event.key === 'ArrowLeft') && (document.fullscreenElement || // Standard
	            document.webkitFullscreenElement || // Chrome, Safari, and Opera
	            document.mozFullScreenElement || // Firefox
	            document.msFullscreenElement))
	{
	
		//var videoPlayer = videojs('hls-example');
	            // Video is in fullscreen mode
	           // alert('Video is in fullscreen mode');
		
	            videoPlayer.muted(true);
	            if (document.exitFullscreen) {
	                    document.exitFullscreen();
	                } else if (document.webkitExitFullscreen) {
	                    document.webkitExitFullscreen();
	                } else if (document.mozCancelFullScreen) {
	                    document.mozCancelFullScreen();
	                } else if (document.msExitFullscreen) {
	                    document.msExitFullscreen();
	            }
	          
	            return;
	
	else if (nCurrentContent == CHANNEL)
	{
		transformedCategory=transformedChannelCategory;
	}else if (nCurrentContent == MOVIE)
	{
		transformedCategory=transformedMovieCategory;
	}else if (nCurrentContent == SERIES)
	{
		transformedCategory=transformedSeriesCategory;
	}else if (nCurrentContent == FILTER_MOVIE)
	{
		transformedCategory=filteredCategory;
	}else if (nCurrentContent == FILTER_SERIES)
	{
		transformedCategory=filteredCategory;
	}else if (nCurrentContent == EPISODES) 
	{
	}else
	{
		
		return;
		
	}

	*/
	if (nCurrentContent == CHANNEL)
	{
		transformedCategory=transformedChannelCategory;
	}else if (nCurrentContent == MOVIE)
	{
		transformedCategory=transformedMovieCategory;
	}else if (nCurrentContent == SERIES)
	{
		transformedCategory=transformedSeriesCategory;
	}else if (nCurrentContent == FILTER_MOVIE)
	{
		transformedCategory=filteredCategory;
	}else if (nCurrentContent == FILTER_SERIES)
	{
		transformedCategory=filteredCategory;
	}else if (nCurrentContent == EPISODES) 
	{
	}
    if (event.key === 'ArrowRight')
    {
    	
    	if (currentIndex>=0)
    	{
    		
	    	if (currentIndex + 1 < imageIcons.length) {
	        	currentIndex += 1;
	        	updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
	        }
        }else
        {
        	
        	currentIndex += 1;
        	updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
        	menuid="button"+menuindex;
	         document.getElementById(menuid).style.border="";
	         
        }
    //    updateImageIcons(currentContainer, currentContainer.id === "iconlist" ? imageIcons : imageIcons2, currentIndex,currentContainer.id === "iconlist" ? nCurrentCategoryFirstIndex : nCurrentCategorySecondIndex);
    } else if (event.key === 'ArrowLeft')
	{
		if (currentIndex - 1 >= 0) 
		{
		        currentIndex -= 1;     
		        updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
	        }else
	        {
		        currentIndex -= 1;     
		       // alert(currentIndex);
		        //menuindex=0;
		        menuid="button"+menuindex;
		       document.getElementById(menuid).focus();
	        	document.getElementById(menuid).style.border = "5px solid yellow";

	        }
  //      updateImageIcons(currentContainer, currentContainer.id === "iconlist" ? imageIcons : imageIcons2, currentIndex,currentContainer.id === "iconlist" ? nCurrentCategoryFirstIndex : nCurrentCategorySecondIndex);
} else if (event.key === 'ArrowDown') {
	if (currentIndex < 0)
	{
		 menuid="button"+menuindex;
	         document.getElementById(menuid).style.border="";
	         if (isAndroid())
	         {
	         	menuindex=(menuindex+1)%6;
		 }else
	         {
		 	menuindex=(menuindex+1)%5;
		 }
		 menuid="button"+menuindex;
		 document.getElementById(menuid).focus();
	         document.getElementById(menuid).style.border = "5px solid yellow";

	}else
	{
		if (nCurrentContent == EPISODES) 
		{
			if (jsonSeriesEpisodesList.seasons.length>=2)
			{
				currentIndex = 0;
				nCurrentCategoryFirstIndex=(nCurrentCategoryFirstIndex+1)% nContentCategoriesTotalNo;
				//alert(nCurrentCategoryFirstIndex);
				imageIcons = Array.from({ length: jsonSeriesEpisodesList.seasons[nCurrentCategoryFirstIndex].episode_count }, (_, index) => index + 1);
					
				
				//alert(imageIcons);
				Category_text = document.getElementById("FirstCategory");
				Category_text.innerText="Season "+(nCurrentCategoryFirstIndex+1);
			
				nCurrentCategorySecondIndex=(nCurrentCategorySecondIndex+1)% nContentCategoriesTotalNo;
				//alert(nCurrentCategorySecondIndex);
				imageIcons2 = Array.from({ length: jsonSeriesEpisodesList.seasons[nCurrentCategorySecondIndex].episode_count }, (_, index) => index + 1);
				
				
				
				Category_text = document.getElementById("SecondCategory");
				Category_text.innerText="Season "+(nCurrentCategorySecondIndex+1);
			
			       // alert(imageIcons2);
			        updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
			        updateImageIcons(iconListContainer2, imageIcons2, currentIndex,nCurrentCategorySecondIndex);	
			}
		}else
		{
		
			if (transformedCategory.categories.length>=2)
			{
			        currentIndex = 0;
				nCurrentCategoryFirstIndex=(nCurrentCategoryFirstIndex+1)% nContentCategoriesTotalNo;
				//alert(nCurrentCategoryFirstIndex);
				if (nCurrentContent == SERIES)
				{
					imageIcons = transformedCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.cover);
				}else
				{
					imageIcons = transformedCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.icon);
				}
				//alert(imageIcons);
				Category_text = document.getElementById("FirstCategory");
				Category_text.innerText=transformedCategory.categories[nCurrentCategoryFirstIndex].name;
			
				nCurrentCategorySecondIndex=(nCurrentCategorySecondIndex+1)% nContentCategoriesTotalNo;
				//alert(nCurrentCategorySecondIndex);
				if (nCurrentContent == SERIES)
				{
					imageIcons2 = transformedCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.cover);
				}else
				{
					imageIcons2 = transformedCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.icon);
				}
				
				Category_text = document.getElementById("SecondCategory");
				Category_text.innerText=transformedCategory.categories[nCurrentCategorySecondIndex].name;
			
			       // alert(imageIcons2);
			        updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
			        updateImageIcons(iconListContainer2, imageIcons2, currentIndex,nCurrentCategorySecondIndex);
		        }
	        }
        }
    } else if (event.key === 'ArrowUp') {
    	if (currentIndex < 0)
	{
		
		 menuid="button"+menuindex;
	         document.getElementById(menuid).style.border="";
	         if (isAndroid())
	         {
	         	menuindex=(menuindex-1+6)%6;
		 }else
	         {
			menuindex=(menuindex-1+5)%5;
		 }
		
		 menuid="button"+menuindex;
		// alert(menuid);
	         document.getElementById(menuid).focus();
	         document.getElementById(menuid).style.border = "5px solid yellow";
	}else
	{
		if (nCurrentContent == EPISODES) 
		{
			if (jsonSeriesEpisodesList.seasons.length>=2)
			{
				currentIndex = 0;
				nCurrentCategoryFirstIndex=(nCurrentCategoryFirstIndex-1+nContentCategoriesTotalNo)% nContentCategoriesTotalNo;
			 	//alert(nCurrentCategoryFirstIndex);
				imageIcons = Array.from({ length: jsonSeriesEpisodesList.seasons[nCurrentCategoryFirstIndex].episode_count }, (_, index) => index + 1);
					
				
				//alert(imageIcons);
				Category_text = document.getElementById("FirstCategory");
				Category_text.innerText="Season "+(nCurrentCategoryFirstIndex+1);
			
				nCurrentCategorySecondIndex=(nCurrentCategorySecondIndex-1+nContentCategoriesTotalNo)% nContentCategoriesTotalNo;
				//alert(nCurrentCategorySecondIndex);
				imageIcons2 = Array.from({ length: jsonSeriesEpisodesList.seasons[nCurrentCategorySecondIndex].episode_count }, (_, index) => index + 1);
				
				
				
				Category_text = document.getElementById("SecondCategory");
				Category_text.innerText="Season "+(nCurrentCategorySecondIndex+1);
			
			       // alert(imageIcons2);
			        updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
			        updateImageIcons(iconListContainer2, imageIcons2, currentIndex,nCurrentCategorySecondIndex);
			        currentContainer = iconListContainer;	
			}
		}else
		{
		    	if (transformedCategory.categories.length>=2)
			{
			    	currentIndex = 0;
			        nCurrentCategoryFirstIndex=(nCurrentCategoryFirstIndex-1+nContentCategoriesTotalNo)% nContentCategoriesTotalNo;
			 	//alert(nCurrentCategoryFirstIndex);
			 	if (nCurrentContent == SERIES)
				{
					imageIcons = transformedCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.cover);
				}else
				{
					imageIcons = transformedCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.icon);
				}
				Category_text = document.getElementById("FirstCategory");
				
				Category_text.innerText=transformedCategory.categories[nCurrentCategoryFirstIndex].name;
			
				nCurrentCategorySecondIndex=(nCurrentCategorySecondIndex-1+nContentCategoriesTotalNo)% nContentCategoriesTotalNo;
				//alert(nCurrentCategorySecondIndex);
				if (nCurrentContent == SERIES)
				{
					imageIcons2 = transformedCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.cover);
				}else
				{
					imageIcons2 = transformedCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.icon);
				}
				Category_text = document.getElementById("SecondCategory");
				Category_text.innerText=transformedCategory.categories[nCurrentCategorySecondIndex].name;
				
			        updateImageIcons(currentContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
			        updateImageIcons(iconListContainer2, imageIcons2, currentIndex,nCurrentCategorySecondIndex);
			        currentContainer = iconListContainer;
		        }
	        }
        }
    }
}

// Initial update
//updateImageIcons(iconListContainer, imageIcons, currentIndex);
//updateImageIcons(iconListContainer2, imageIcons2, currentIndex2);

// Event listener for arrow keys
//document.addEventListener('keydown', handleArrowKeys);

function find_cookie_value(keystrinp)
{ 
	var restring;
	var str;
	var substr1;
	var pos1, pos2;
	
	str=document.cookie;
	//alert(str);
	//alert(keystr);
	keystr=keystrinp+location.hostname
	pos1=str.indexOf(keystr);
	//alert(pos1);
	subchar=str.substring(pos1+keystr.length,pos1+keystr.length+1);
	//alert(subchar);
	if (subchar==';')
	{
		return 0;
	}else
	{
		substr1=str.substring(pos1+keystr.length+2,str.length);
		//alert(substr1);
		pos1=substr1.indexOf(']');
		restring=substr1.substring(0,pos1);
		//alert(restring);
		return restring;
	}
	
	
}
function add_cookie_value(keystr,keyvalue)
{
	//alert(document.cookie);
	document.cookie=keystr+location.hostname+'=['+keyvalue+']';
}
function Clear_cookie()
{
	document.cookie='token'+location.hostname+'=';
	document.cookie='userid'+location.hostname+'=';
	document.cookie='password'+location.hostname+'=';
	document.cookie='dir_path'+location.hostname+'=';
	document.cookie='video_path'+location.hostname+'=';

}
function encode64(input) {  

 var keyStr = "ABCDEFGHIJKLMNOP" +  

              "QRSTUVWXYZabcdef" +  

              "ghijklmnopqrstuv" +  

              "wxyz0123456789+/" +  

              "=";  
  // input = encodeURI(input);  

    var output = "";  

    var chr1, chr2, chr3 = "";  

    var enc1, enc2, enc3, enc4 = "";  

    var i = 0; 
  
 
    do {  

       chr1 = input.charCodeAt(i++);  

       chr2 = input.charCodeAt(i++);  

       chr3 = input.charCodeAt(i++);  

  

       enc1 = chr1 >> 2;  

       enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);  

       enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);  

       enc4 = chr3 & 63;  

  

    /*   if (isNaN(chr2)) {  

          enc3 = enc4 = 64;  

       } else if (isNaN(chr3)) {  

          enc4 = 64;  

       }  
*/
  

       output = output +  

          keyStr.charAt(enc1) +  

          keyStr.charAt(enc2) +  

          keyStr.charAt(enc3) +  

          keyStr.charAt(enc4);  
  
       chr1 = chr2 = chr3 = "";  

       enc1 = enc2 = enc3 = enc4 = "";  

    } while (i < input.length);  

  

    return output;  

}  
 function closeModal() {
        document.getElementById('UserLogin').style.display = 'none';
    }
 function closeSignupModal() {
        document.getElementById('UserSignup').style.display = 'none';
        document.getElementById('user_id').focus();
        document.getElementById('user_id').style.background="yellow";        
        document.getElementById("sign_button").style.background="#cccccc";
        document.getElementById("SignUp_Cancel").style.background="#cccccc";
        
    }
 function closeSearchModal(cancelflag) {
 	
        document.getElementById('SearchMenu').style.display = 'none';
        if (cancelflag==false)
        {
        }else
        {
        	document.getElementById("button0").style.border = "5px solid yellow";
        }

    }
    
function login()
{
	var cgi_url;
	var encrypt_str;
	var userid_pass;
	g_user_id = document.getElementById("user_id").value;
	g_password = document.getElementById("password").value;
	userid_pass=g_user_id+':'+g_password;
	encrypt_str=encode64(userid_pass);
	videoPlayer = videojs('hls-example', {
	    controls: false,  // Disable default controls
	    contextmenu: false // Disable context menu
	  });  

	cgi_url = g_server_http_ip_port+"/token/createtokenbased64_json?encrpty="+encodeURI(encrypt_str)+"&flag="+Math.random();
	xmlHttp.open("GET", cgi_url);
	xmlHttp.onreadystatechange = function(){
		var login_status = document.getElementById("login_status");
		var login_password_text = document.getElementById("login_password_text");
		
		var browser_name;
		//var content = parent.document.getElementById("main_screen");
		//Android.AlertMessage(g_user_id);
		if (xmlHttp.readyState == 4) 
		{
			var response = xmlHttp.responseText;
			//alert(response);
			const ResponseObj = JSON.parse(response);
			if (ResponseObj.token=="-1")
			{
				//id_check_flag=0;
				alertmessage("Parameter error");
				//login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>Parameter error.</b></font>';
			} else if (ResponseObj.token=="-2")
			{
				alertmessage("Wrong user name or password");
				//id_check_flag=0;
				//login_password_text.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000">Enter your passowrd</font>';
				//login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>Wrong user name or password.</b></font>';
			} else if (ResponseObj.token=="-3")
			{
				//id_check_flag=0;
				alertmessage("Time expired");
				login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>User time expired. Contact panel owner.</b></font>';
			} 
			else
			{
				/*
				if (isAndroid())
				{
					Android.HideVideo(1);
				}
				*/
				if (isAndroid())
				{
					document.getElementById('content_player').innerHTML="";
					Android.PutUserProfile(g_user_id,g_password);
				}
				document.getElementById('sign_button').innerText="Cancel";
				var modal = document.getElementById('UserLogin');
				modal.style.display = "none";
				g_token=ResponseObj.token;
				g_httpport=ResponseObj.httpport;
				daysleft=ResponseObj.daysleft;
				/* alert(g_token);
				alert(g_httpport);
				alert(daysleft);
				*/
				add_cookie_value("token",g_token);
				add_cookie_value("userid",g_user_id);
				add_cookie_value("password",g_password);
				//logout();
				get_channel_list();
				document.addEventListener('keydown', handleArrowKeys);
				//get_movie_list();
				//get_series_list();
				//get_http_streaming_port();
				
			}
		}
	
	};
	
	xmlHttp.send(null);
}
function logout()
{
	var cgi_url;
  
  	 cgi_url = g_server_http_ip_port+"/token/destroytoken_json?token="+g_token+"&flag="+Math.random();
	 xmlHttp.open("GET", cgi_url, true);
	 xmlHttp.onreadystatechange = function(){
	 	if (xmlHttp.readyState == 4) 
		{
			var response = xmlHttp.responseText;
			alertmessage(response);
			var jsonToken = JSON.parse(response);
			alertmessage(jsonToken.token);
			g_token=null;
		}
	 };	
	 xmlHttp.send(null);

}
function tv(){
	document.getElementById("button1").style.border="";
	get_channel_list();
	

}
function films(){
	document.getElementById("button2").style.border="";
	get_movie_list();
}
function series(){
	document.getElementById("button3").style.border="";
	get_series_list();
}
function setting(){
	document.getElementById("button4").style.border="";
	if (isAndroid())
	{
		Android.SystemSetting();
	}
}


async function searchContent(SearchString)
{
	var transformedCategory;
	filteredCategory = {
	categories: []
	};
	//alert(nContentType);
	//alert(SearchString);
	
	if (nCurrentContent == FILTER_MOVIE)
	{
		//alert(transformedMovieCategory.categories.length);
		if (transformedMovieCategory.categories.length==0)
		{
			await get_movie_list();
			nCurrentContent = FILTER_MOVIE;
		}
		transformedCategory = transformedMovieCategory;
	}else if (nCurrentContent == FILTER_SERIES)
	{
		//alert(transformedSeriesCategory.categories.length);
		if (transformedSeriesCategory.categories.length==0)
		{
			await get_series_list();
			nCurrentContent = FILTER_SERIES;
		}
		transformedCategory = transformedSeriesCategory;
	}
	
	//alert(transformedCategory.categories.length);
	filteredCategory = {
                categories: []
            };

	    // Convert the grouped channels into the desired format
	    for (const category of transformedCategory.categories) {
                // Filter items based on partial match with testString
                
                var filteredItems = category.items.filter(content => content.name.includes(SearchString));
                // Only include categories that have matching items
                if (filteredItems.length > 0) {
                    filteredCategory.categories.push({
                        name: category.name,
                        items: filteredItems
                    });
                }
            }
        
	//alert(filteredCategory.categories.length);
        var Category_text = document.getElementById("FirstCategory");
 	Category_text.innerText="Resutls";
 	if (nCurrentContent == FILTER_MOVIE)
	{
		imageIcons = filteredCategory.categories.flatMap(category => category.items.map(item => item.icon));
	}else if (nCurrentContent == FILTER_SERIES)
	{
		imageIcons = filteredCategory.categories.flatMap(category => category.items.map(item => item.cover));
	}
	//alert(imageIcons);
	// Update the icons in the iconListContainer
	updateImageIcons(iconListContainer, imageIcons, 0,0);
	
	// Clear 2nd row
	Category_text = document.getElementById("SecondCategory");
	Category_text.innerText= null;
	imageIcons2.length=0;
	updateImageIcons(iconListContainer2, imageIcons2, 0,0);

	closeSearchModal(false);
	if (isAndroid())
	{
		Android.HideVideo(1);
	}
					       
}
function SearchMovie()
{
	var str=document.getElementById("SearchText").value;
	nCurrentContent = FILTER_MOVIE;
	searchContent(str);
}
function SearchSeries()
{
	var str=document.getElementById("SearchText").value;
	nCurrentContent = FILTER_SERIES;
	searchContent(str);
}
function get_channel_list(){
	var cgi_url;
	cgi_url = g_server_http_ip_port+"/server/get_content_list_json?token="+g_token+"&type=channel"+"&flag="+Math.random();
	xmlHttp.open("GET", cgi_url, true);
	xmlHttp.onreadystatechange  = function()
		{
			if (xmlHttp.readyState == 4) 
			{
				nCurrentContent = CHANNEL;
				var response = xmlHttp.responseText;
				//prompt("channel:", response);
				//alert(response);
				var jsonContentList = JSON.parse(response);

				// Create an empty object to store the transformed data
				
				// Group channels by category_name
				var groupedContent = jsonContentList.content.reduce((acc, content) => {
				  if (!acc[content.category_name]) {
				    acc[content.category_name] = [];
				  }
				  acc[content.category_name].push(content);
				  return acc;
				}, {});
				nCurrentCategoryFirstIndex=0;
				currentIndex=0;
				currentIndex2=0;
	
				transformedChannelCategory.categories.length=0;			
				// Convert the grouped channels into the desired format
				for (const category in groupedContent) {
				  transformedChannelCategory.categories.push({
				    name: category,
				    items: groupedContent[category].map(content => ({
				      name: unescape(content.name),
				     // genre: content.genre,
				      icon: content.stream_icon,
				      fwdURL: content.location,
				      epg_channel_id: content.epg_channel_id
				    }))
				  });
				}
				//alert(transformedChannelCategory.categories[0].name);
				//alert(transformedChannelCategory.categories[0].items[0].genre[1].location);
				//alert(transformedChannelCategory.categories[1].items[0].genre[1].location);
				//document.getElementById("content_description").hidden=true;
				//document.getElementById("content_runnning_description").style.display = 'none';
				//alert(transformedChannelCategory.categories[0].items[0].genre[1].id);
				//alert(transformedChannelCategory.categories[0].items[0].genre[1].name);
				//alert(transformedChannelCategory.categories[2].items[1].name);
				//alert(transformedChannelCategory.categories[2].items[1].icon);
				//alert(transformedChannelCategory.categories[2].items[1].epg_channel_id);
				//alert(transformedChannelCategory.categories.length);
				if (transformedChannelCategory.categories.length>0)
				{
					var Category_text = document.getElementById("FirstCategory");
					Category_text.innerText=transformedChannelCategory.categories[nCurrentCategoryFirstIndex].name;
					imageIcons = transformedChannelCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.icon);
					
					// Update the icons in the iconListContainer
					updateImageIcons(iconListContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
					if (transformedChannelCategory.categories.length>=2)
					{
						nCurrentCategorySecondIndex=nCurrentCategoryFirstIndex+1;
						Category_text = document.getElementById("SecondCategory");
						Category_text.innerText=transformedChannelCategory.categories[nCurrentCategorySecondIndex].name;
						imageIcons2 = transformedChannelCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.icon);
						//alert(imageIcons2);
						// Update the icons in the iconListContainer
						updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
					}else
					{
						Category_text = document.getElementById("SecondCategory");
						Category_text.innerText= null;
						imageIcons2.length=0;
						updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
					}
					nContentCategoriesTotalNo=transformedChannelCategory.categories.length;
				}
				

				
			}
		};
	xmlHttp.send(null);

}
function get_movie_list(){
	return new Promise(function (resolve, reject) {
		var cgi_url;
		cgi_url = g_server_http_ip_port+"/server/get_content_list_json?token="+g_token+"&type=movie"+"&flag="+Math.random();
		xmlHttp.open("GET", cgi_url, true);
		xmlHttp.onreadystatechange  = function()
			{
				if (xmlHttp.readyState == 4) 
				{
					nCurrentContent = MOVIE;
					var response = xmlHttp.responseText;
					//alert(response)
					var jsonContentList = JSON.parse(response);
	
					// Create an empty object to store the transformed data
					
					// Group channels by category_name
					var groupedContent = jsonContentList.content.reduce((acc, content) => {
					  if (!acc[content.category_name]) {
					    acc[content.category_name] = [];
					  }
					  acc[content.category_name].push(content);
					  return acc;
					}, {});
					nCurrentCategoryFirstIndex=0;
					currentIndex=0;
					currentIndex2=0;
					transformedMovieCategory.categories.length=0;
					// Convert the grouped channels into the desired format
					for (const category in groupedContent) {
					  transformedMovieCategory.categories.push({
					    name: category,
					    items: groupedContent[category].map(content => ({
					      name: unescape(content.name),
					      fwdURL: content.location,
					      icon: content.stream_icon,
					      rating: content.rating
					    }))
					  });
					}
					resolve(transformedMovieCategory);
					//document.getElementById("content_description").hidden=false;
					//document.getElementById("content_runnning_description").style.display = 'block';
	
					//alert(transformedMovieCategory.categories[0].items[1].name);
					//alert(transformedMovieCategory.categories[0].items[1].icon);
					//alert(transformedMovieCategory.categories[0].items[1].rating);
					var Category_text = document.getElementById("FirstCategory");
					//alert(transformedMovieCategory.categories.length);
					if (transformedMovieCategory.categories.length>0)
					{
						Category_text.innerText=transformedMovieCategory.categories[nCurrentCategoryFirstIndex].name;
						imageIcons = transformedMovieCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.icon);
						//alert(imageIcons);
						// Update the icons in the iconListContainer
						updateImageIcons(iconListContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
						if (transformedMovieCategory.categories.length>=2)
						{
							nCurrentCategorySecondIndex=nCurrentCategoryFirstIndex+1;
							Category_text = document.getElementById("SecondCategory");
							Category_text.innerText=transformedMovieCategory.categories[nCurrentCategorySecondIndex].name;
							imageIcons2 = transformedMovieCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.icon);
							//alert(imageIcons2);
							// Update the icons in the iconListContainer
							updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
						}else
						{
							Category_text = document.getElementById("SecondCategory");
							Category_text.innerText= null;
							imageIcons2.length=0;
							updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
						}
						nContentCategoriesTotalNo=transformedMovieCategory.categories.length;
					}
							
				}
			};
		xmlHttp.send(null);
	});

}
function get_series_list(){
	return new Promise(function (resolve, reject) {
		var cgi_url;
		cgi_url = g_server_http_ip_port+"/server/get_content_list_json?token="+g_token+"&type=series"+"&flag="+Math.random();
		xmlHttp.open("GET", cgi_url, true);
		xmlHttp.onreadystatechange  = function()
			{
				if (xmlHttp.readyState == 4) 
				{
					nCurrentContent = SERIES;
					var response = xmlHttp.responseText;
					//alert(response);
					var jsonContentList = JSON.parse(response);
	
					// Create an empty object to store the transformed data
					
					// Group channels by category_name
					var groupedContent = jsonContentList.content.reduce((acc, content) => {
					  if (!acc[content.category_name]) {
					    acc[content.category_name] = [];
					  }
					  acc[content.category_name].push(content);
					  return acc;
					}, {});
					nCurrentCategoryFirstIndex=0;
					currentIndex=0;
					currentIndex2=0;
	
					transformedSeriesCategory.categories.length=0;
					// Convert the grouped channels into the desired format
					for (const category in groupedContent) {
					  transformedSeriesCategory.categories.push({
					    name: category,
					    items: groupedContent[category].map(content => ({
					      name: unescape(content.name),
					      cover: content.cover,
					      releaseDate: content.releaseDate
					    }))
					  });
					}
					resolve(transformedSeriesCategory);
					//document.getElementById("content_description").hidden=false;
					//document.getElementById("content_runnning_description").style.display = 'block';
	
					//alert(transformedSeriesCategory.categories[1].items[1].name);
					//alert(transformedSeriesCategory.categories[1].items[1].cover);
					//alert(transformedSeriesCategory.categories[1].items[1].releaseDate);
					var Category_text = document.getElementById("FirstCategory");
					if (transformedSeriesCategory.categories.length>0)
					{
						Category_text.innerText=transformedSeriesCategory.categories[nCurrentCategoryFirstIndex].name;
						imageIcons = transformedSeriesCategory.categories[nCurrentCategoryFirstIndex].items.map(item => item.cover);
						//alert(imageIcons);
						// Update the icons in the iconListContainer
						updateImageIcons(iconListContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
						if (transformedSeriesCategory.categories.length>=2)
						{
							nCurrentCategorySecondIndex=nCurrentCategoryFirstIndex+1;
							Category_text = document.getElementById("SecondCategory");
							Category_text.innerText=transformedSeriesCategory.categories[nCurrentCategorySecondIndex].name;
							imageIcons2 = transformedSeriesCategory.categories[nCurrentCategorySecondIndex].items.map(item => item.cover);
							//alert(imageIcons2);
							// Update the icons in the iconListContainer
							updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
						}else
						{
							Category_text = document.getElementById("SecondCategory");
							Category_text.innerText= null;
							imageIcons2.length=0;
							updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
						}
						nContentCategoriesTotalNo=transformedSeriesCategory.categories.length;
					}
					
							
				}
			};
		xmlHttp.send(null);
	});

}
function get_episodes_list(series_name){
	var cgi_url;
	cgi_url = g_server_http_ip_port+"/server/get_content_list_json?token="+g_token+"&type=episodes"+"&name="+series_name+"&flag="+Math.random();
	xmlHttp.open("GET", cgi_url, true);
	xmlHttp.onreadystatechange  = function()
		{
			if (xmlHttp.readyState == 4) 
			{
				nCurrentContent = EPISODES;
				var response = xmlHttp.responseText;
				//alert(response);
		                var iconlist=document.getElementById("iconlist");
		                iconlist.innerHTML="";
		                document.getElementById("FirstCategory").innerHTML="";
		                document.getElementById("SecondCategory").innerHTML="";
		                document.getElementById("iconlist2").innerHTML="";
		                var i=0;
		                var j=0;
		                var k=1;
		                var m=1;
		                var contentName=null;
		                var contentLink=null;
		                //alert(iconlist);
				jsonSeriesEpisodesList = JSON.parse(response);
				nCurrentCategoryFirstIndex=0;
				currentIndex=0;
				currentIndex2=0;
				g_cur_series_name=series_name;
				

				 //document.getElementById("content_description").hidden=false;
				//document.getElementById("content_runnning_description").hidden=false;

				var Category_text = document.getElementById("FirstCategory");
				if (jsonSeriesEpisodesList.seasons.length>0) 
				{
					if (jsonSeriesEpisodesList.seasons[0].episode_count>0)
					
					Category_text.innerText="Season 1";
					imageIcons = Array.from({ length: jsonSeriesEpisodesList.seasons[0].episode_count }, (_, index) => index + 1);
					//alert(imageIcons);
					// Update the icons in the iconListContainer
					updateImageIcons(iconListContainer, imageIcons, currentIndex,nCurrentCategoryFirstIndex);
					if (jsonSeriesEpisodesList.seasons.length>=2)
					{
						nCurrentCategorySecondIndex=nCurrentCategoryFirstIndex+1;
						Category_text = document.getElementById("SecondCategory");
						Category_text.innerText="Season 2";
						imageIcons2 = Array.from({ length: jsonSeriesEpisodesList.seasons[1].episode_count }, (_, index) => index + 1);
						//alert(imageIcons2);
						// Update the icons in the iconListContainer
						updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
					}else
					{
						Category_text = document.getElementById("SecondCategory");
						Category_text.innerText= null;
						imageIcons2.length=0;
						updateImageIcons(iconListContainer2, imageIcons2, currentIndex2,nCurrentCategorySecondIndex);
					}
					nContentCategoriesTotalNo=jsonSeriesEpisodesList.seasons.length;
				}
				
				
						
			}
		};
	xmlHttp.send(null);

}
function search()
{
	if (isAndroid())
	{
		Android.HideVideo(0);
	}
	var modal = document.getElementById('SearchMenu');
	modal.style.display = "block";
	document.getElementById("button0").style.border="";
	document.getElementById('SearchText').focus();	
	document.getElementById('SearchText').style.background="yellow"; 
	//nCurrentContent=0;
	
}
function login_dialog(bShow)
{
	if (!isAndroid())
	{
		document.getElementById('button5').style.visibility = 'hidden';
	}else
	{
		if (bShow==1)
		{
			if (isAndroid())
			{
				Android.HideVideo(0);
			}
		}
		var userDataString=Android.GetUserProfile();
		var userData = JSON.parse(userDataString);
		g_user_id=userData.username;
		g_password=userData.password;
		
		
	}
	document.removeEventListener('keydown', handleArrowKeys);

	if ((g_user_id!="") && (bShow==0))
	{
		var modal = document.getElementById('UserLogin');
		modal.style.display = "block";
		if (g_serverip.length>0)
	        {
	          	g_server_http_ip_port="http://"+g_serverip+":"+g_apiport;
	        }else
	        {
	          	g_server_http_ip_port='';
	          	g_serverip=location.hostname;
	        }
	        //alert(g_user_id);
	        document.getElementById('user_id').focus();
		document.getElementById("user_id").value=g_user_id;
		document.getElementById("password").value=g_password;
		login();
	}else
	{
		
		
		var modal = document.getElementById('UserLogin');
		modal.style.display = "block";
		if (g_serverip.length>0)
	        {
	          	g_server_http_ip_port="http://"+g_serverip+":"+g_apiport;
	        }else
	        {
	          	g_server_http_ip_port='';
	          	g_serverip=location.hostname;
	         }
		document.getElementById("button4").style.border="";
	
		document.getElementById('user_id').focus();
		document.getElementById('user_id').style.background="yellow"; 
	}
}
	
function sign_dialog()
{
	if (document.getElementById('sign_button').innerText=="Cancel")
	{
		closeModal();
		document.addEventListener('keydown', handleArrowKeys);
	}else
	{
		var modal = document.getElementById('UserSignup');
		modal.style.display = "block";
		document.getElementById('sign_user_id').focus();
		document.getElementById('sign_user_id').style.background="yellow"; 
	}
}
function ShowPassword()
{
	var x=document.getElementById("password");
	if (x.type === "password") {
	    x.type = "text";
	  } else {
	    x.type = "password";
	  }
	var x=document.getElementById("sign_password");
	if (x.type === "password") {
	    x.type = "text";
	  } else {
	    x.type = "password";
	  }
	var xc=document.getElementById("confirmed_password");
	if (xc.type === "password") {
	    xc.type = "text";
	  } else {
	    xc.type = "password";
	  }
	  
}

function MenuSignUp()
{
	myEmail = document.getElementById("signup_email").value;

	var encrypt_str;
	var userid_pass;
	g_user_id = document.getElementById("sign_user_id").value;
	g_password = document.getElementById("sign_password").value;
	var confirmed_password = document.getElementById("confirmed_password").value;
	if (g_password != confirmed_password)
	{
		
		var login_confirmed_password_text = document.getElementById("login_confirmed_password_text");
		login_confirmed_password_text.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000">Password not matched</font>';
		return;
	}
	userid_pass=g_user_id+':'+g_password;
	encrypt_str=encode64(userid_pass);
	cgi_url = g_server_http_ip_port+"/token/signupbased64_json?encrpty="+encodeURI(encrypt_str)+"&email="+myEmail+"&flag="+Math.random();

	xmlHttp.open("GET", cgi_url);
	xmlHttp.onreadystatechange = function(){
		var login_status = document.getElementById("login_status");
		var login_password_text = document.getElementById("login_password_text");
		
		var browser_name;
		
		if (xmlHttp.readyState == 4) 
		{
			var response = xmlHttp.responseText;
			const ResponseObj = JSON.parse(response);
			//alert(ResponseObj.iret);
			if (ResponseObj.iret=="-1")
			{
				alertmessage("Parameter error");
				//id_check_flag=0;
				//login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>Parameter error.</b></font>';
			} else if (ResponseObj.iret=="-2")
			{
				alertmessage("Wrong user name or password");
				//id_check_flag=0;
				//login_password_text.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000">Enter your passowrd</font>';
				//login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>Wrong user name or password.</b></font>';
			} else if (ResponseObj.iret=="-3")
			{
				alertmessage("Time expired");
				//id_check_flag=0;
				//login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>User time expired. Contact panel owner.</b></font>';
			}  else if (ResponseObj.iret=="3")
			{
				alertmessage("Username existed");
				//id_check_flag=0;
				//login_status.innerHTML='<p style="margin-left: 25; margin-top: 0"><font face="Arial" size="2" color="#ff0000"><b>Username existed.</b></font>';
			}else
			{
				//document.getElementById("confirmed_password").style.background="red";
				
				alertmessage("24 hours for trial");
				var modal = document.getElementById('UserSignup');
				modal.style.display = "none";
				//id_check_flag=1;
				closeSignupModal();
				
			}
			
		}
	
	};
	
	xmlHttp.send(null);
}
function moveLeftRight(event, currentInputId, nextInputId, prevInputId) {
    switch (event.key) {
        case "ArrowLeft":
            // Focus on the previous input field when the left arrow key is pressed
            document.getElementById(prevInputId).focus();
            document.getElementById(prevInputId).style.background="yellow";
            document.getElementById(currentInputId).style.background="#cccccc";
            break;
        case "ArrowRight":
            // Focus on the next input field when the right arrow key is pressed
            document.getElementById(nextInputId).focus();
           document.getElementById(nextInputId).style.background="yellow";
           document.getElementById(currentInputId).style.background="#cccccc";
            break;
    }
}

function moveUpDown(event, currentInputId, nextInputId, prevInputId) {
    switch (event.key) {
        case "Enter":
            // Prevent the default form submission behavior
            event.preventDefault();

            // Get the current active element
            var activeElement = document.activeElement;

            // Check if the active element is a button or checkbox
           // if (activeElement.tagName === "BUTTON") {
           if (activeElement.tagName === "BUTTON" || activeElement.type === "checkbox") {
                // Execute the button's click event or toggle checkbox state
                activeElement.click();
            } else {
                // Focus on the next input field
                document.getElementById(nextInputId).focus();
                document.getElementById(nextInputId).style.background="yellow";;
                document.getElementById(currentInputId).style.background="#cccccc";
            }
            break;
        case "ArrowDown":
            // Focus on the next input field when the down arrow key is pressed
            document.getElementById(nextInputId).focus();
            document.getElementById(nextInputId).style.background="yellow";
            document.getElementById(currentInputId).style.background="#cccccc";
            break;
        case "ArrowUp":
            // Focus on the previous input field when the up arrow key is pressed
            document.getElementById(prevInputId).focus();
            document.getElementById(prevInputId).style.background="yellow";
            document.getElementById(currentInputId).style.background="#cccccc";
            break;
        case "ArrowLeft":
        case "ArrowRight":
            // Handle left/right arrow keys for moving to the previous/next input field
            moveLeftRight(event, currentInputId, nextInputId, prevInputId);
            break;
    }
}
function ShowPassword()
{
	x=document.getElementById("password");
	if (x.type === "password") {
	    x.type = "text";
	  } else {
	    x.type = "password";
	  }
}
function ShowSignPassword()
{
	x=document.getElementById("sign_password");
	if (x.type === "password") {
	    x.type = "text";
	  } else {
	    x.type = "password";
	  }
	x=document.getElementById("confirmed_password");
	if (x.type === "password") {
	    x.type = "text";
	  } else {
	    x.type = "password";
	  }
}

