var country_glob = "";
var def_stream_server = "mms://69.172.226.39"; 
var live_stream_server = "69.172.226.39"; 
var def_stream_proto = "mms://"; 
var link_Glob = "";
var short_name_Glob = "";
var timer;
var timeZone_Glob;
var httpObject = null;
var key = "";
var userId = 0;
var pageisloaded=0; 

var serversArr = new Array(
"69.172.226.4",
"69.172.226.5",
"69.172.226.15",
"69.172.226.16",
"69.172.226.26",
"69.172.226.27"
);  

function onLoad(country, timeZone, showPreview, _userId)
{	
	userId = _userId;
	country_glob = country;    
	
	if (showPreview=='true')
	{	
		pageisloaded=1;
		
		document.getElementById("preview").innerHTML = "Channel preview";
		
		if (country == "ua")	
			GoAndShow("http://69.172.226.39", "ukrainian", false, false, country_glob);
		
		if (country == "ru")	
			GoAndShow("http://69.172.226.39", "russian", false, false, country_glob);
		
		if (country == "pl")	
			GoAndShow("http://69.172.226.39", "polish", false, false, country_glob);			
	}
    else
    {
		document.getElementById("preview").innerHTML = "";		
    }
    SetTimeZone(timeZone);
    pageisloaded=1;
}

function onLoadSport(_userId)
{    
    userId = _userId;    
}

function SetTimeZone_Play(timeZone)
{	
	timeZone_Glob = timeZone;	
	if(link_Glob.length > 0) GoAndShow(link_Glob, short_name_Glob, false, true, country_glob);
	SetTimeZone(timeZone);
}

function getPlayer()
{
   return document.getElementById("player");		  
}


function setFullScreen(size)
{	
	if (size)
	{	
		var player = getPlayer();
		player.fullScreen = true;
	}
}

function setMSIEPlayer(tv_link)
{	
	var player = document.getElementById("player");
	if (!player)
	{
	document.getElementById("video_player").innerHTML =  
	   '<object id="player" classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" type="application/x-ms-wmp" width="520" height="440">'+
   	   '<param name="url" value="' + tv_link + '">' +
   	   '<param name="autostart" value="true">' +
   	   '<param name="volume" value="50">' +
   	   '<param name="balance" value="0">' +
   	   '<param name="uimode" value="mini">' +
   	  // '<param name="enablecontextmenu" value="true">' +
   	   '</object>';
	}
	else
	{ 
		player.stop();
		player.url = tv_link;
	}	
}

function setFirefoxPlayer(tv_link)
{	
   document.getElementById("video_player").innerHTML =  
   '<object id="oplayer" classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" type="application/x-oleobject" width="520" height="440">'+
   '<param name="url" value="' + tv_link + '">' +
   '<param name="autostart" value="true">' +
   '<param name="volume" value="50">' +
   '<param name="balance" value="0">' +
   '<param name="uimode" value="mini">' +
   '<param name="enablecontextmenu" value="false">' +  
   '<embed type="application/x-mplayer2" enablecontextmenu=0 autostart=1 id="player" name="player" width="520" height="440" ' + 
   'src="' + tv_link + '">' +
   '</object>';
}

function setOperaPlayer(tv_link)
{	
   document.getElementById("video_player").innerHTML =  
   '<embed type="application/x-ms-wmp" enablecontextmenu=0 autostart=1 id="player" name="player" width="520" height="440" ' + 
   'src="' + tv_link + '">';	
}

function setSafariPlayer(tv_link)
{
   document.getElementById("video_player").innerHTML =  
		'<embed type="application/x-vlc-plugin"' +
         'name="player"'+
         'autoplay="yes" loop="no" showdisplay="yes" width="520" height="440"'+
         'target="'+ tv_link + '" />';
         
  /*  '<OBJECT classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" '+
        'codebase="http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab" '+
        'width="520" height="440" id="vlc" name="vlc" events="True">'+
      '<param name="Src" value="'+ tv_link +'" />'+
      '<param name="ShowDisplay" value="True" />'+
      '<param name="AutoLoop" value="False" />'+
      '<param name="AutoPlay" value="True" />'+
      '<param name="Volume" value="100">'+
    '</OBJECT>';*/

	  
}

function Set_Player(tv_link, size)
{        
 
	 var player = document.getElementById("player"); 
	 
	 if (player != null)
	 {
		 player.stop();		 
	 }
	 
     if (isGoogleChrom())
     {
	     setSafariPlayer(tv_link);
     }
	 else if (navigator.userAgent.indexOf("Opera") != -1) 
     {
         setOperaPlayer(tv_link)
     }
     else if (navigator.userAgent.indexOf("MSIE") != -1) 
     { 	
         setMSIEPlayer(tv_link)
     }
     else
     {
 	     setFirefoxPlayer(tv_link);
     }
     pageisloaded=1;
     scroll(200);
}

function SetTimeZone(timeZone)
{                                                                                                 
	timeZone_Glob = timeZone;
	var curDateTime = new Date();
  	var curUTChour = curDateTime.getUTCHours();
	// This is regular time for no difference between Europe and NA 
	//var UTCoffset = curUTChour - curDateTime.getHours();
	//This is temporary time when the difference exists between Eu and NA on spring
	var UTCoffset = curUTChour - (curDateTime.getHours() - 1);
	if(UTCoffset < 0)	UTCoffset += 24;
	var milisec = curDateTime.getTime()
	var zoneDateTime = new Date(milisec + ((UTCoffset - timeZone) * 3600000));
	var dateStart = zoneDateTime.toString().substring(0, 10);
	dateStart = dateStart.replace(/^\s+|\s+$/g,"");
	
	document.getElementById("dateLab").innerHTML = dateStart;
	document.getElementById("yearLab").innerHTML = zoneDateTime.getFullYear(); 
	document.getElementById("timeLab").innerHTML = (zoneDateTime.getHours() < 10 ? "0" : "") + zoneDateTime.getHours() + ":" +
		(zoneDateTime.getMinutes() < 10 ? "0" : "") + zoneDateTime.getMinutes() + ":" + 
		(zoneDateTime.getSeconds() < 10 ? "0" : "") + zoneDateTime.getSeconds();
	clearTimeout(timer);
    timer = setTimeout("SetTimeZone(" + timeZone + ")", 1000);
}

var tvLinkForTimeOut = "";

function setPlayerAfterTimeOut()
{		
	Set_Player(tvLinkForTimeOut);	
}

var _link_4_GAS;
var _check_4_GAS;

function GoAndShow(link, short_name, size, check, country)
{     
  if (!pageisloaded) return;
  
  pageisloaded=0;	
  
  if (check && !userId)
  {
	 window.location = "/user/login.php";    
	 return;
  }	
  
  link_Glob = link;
  short_name_Glob = short_name;    
  
  if (check)
  {
	  country_glob = country;  
	  document.getElementById("video_player").innerHTML = "<div style='padding: 20px;  font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: medium; color: #FF0000'>Connecting to stream...</div>";         
	  _check_4_GAS = check;
	  if  (link_Glob.length > 0 && link_Glob != " ") //live channels
	  {  
	     var currServer = def_stream_proto + live_stream_server;
	  }
	  else
	  {
	     var serv_index = Math.floor((serversArr.length-1)*Math.random());  
	     var currServer = def_stream_proto + serversArr[serv_index];  
	  }
	  document.getElementById("serverAlias").innerHTML = "Stream: " + currServer.substr(currServer.length - 2, 2);    

	  if(link_Glob.length == 0 || link_Glob.indexOf(def_stream_proto, 0) < 0)
	      link_Glob = currServer + link_Glob; 
	           
	  scroll(0, 200); 
      setTimeout("doGoAndShow()", 1000);
  }  
  else
  {
  	doGoAndShow(); 
  }
}

function doGoAndShow()
{  
  var tv_link = "";
  var countryUpp = country_glob.toUpperCase();
  
  if(_check_4_GAS)
  {  
  	  //**** Ajax session ****  
      doWork();
      //**** end of Ajax session **** 
      if (key.length > 0) //user is logged in
  	  {               	 	 
		 if (key.indexOf("broken") >= 0)
		 {
		 	window.location = "/user/login.php";
		 }
		 else if (key.indexOf("undefined") >=0 )
		 {
			 switch(countryUpp)
			 {
				 case "UA": 
				 	document.getElementById("video_player").innerHTML = '<div style="padding: 20px;  border: thin solid #800000; font-family: Arial, Helvetica, sans-serif; font-size: small; line-height: normal; font-weight: bold; font-size: medium; color: #FF0000">' +
				 	                                                    '<strong>Увага!<br /></strong>'+
				 	                                                    'Цей User Login вже використовується для перегляду на нашому сайті. Допускається лише 1 одночасний перегляд для 1 користувача.'+
				 	                                                    '</div>'
				 	break;
				 case "RU": 
				 	document.getElementById("video_player").innerHTML = '<div style="padding: 20px;  border: thin solid #800000; font-family: Arial, Helvetica, sans-serif; font-size: small; line-height: normal; font-weight: bold; font-size: medium; color: #FF0000">' +
				 	                                                    '<strong>Внимание!<br /></strong>'+  
				 	                                                    'В настоящий момент данная учетная запись уже используется для просмотра. Допускается только 1 одновременный просмотр для 1 пользователя.' +
				 	                                                    '</div>'
				 	break;
			      /* case "PL": 
				 	document.getElementById("video_player").innerHTML = ""; 	 	
				 	break; */
				 default:	
				 	document.getElementById("video_player").innerHTML = '<div style="padding: 20px;  border: thin solid #800000; font-family: Arial, Helvetica, sans-serif; font-size: small; line-height: normal; font-weight: bold; font-size: medium; color: #FF0000">' +
				 	                                                    '<strong>Attention!<br /></strong>'+
				 	                                                    'This usrename is currently being used to stream. Please wait for the user to log out and try again.' +
				 	                                                    '</div>'
			 }
			 
		 }
		 else
		 {
			 if(link_Glob.indexOf(".wmv", 0) > 0)
	  		 { 
	  	 		tv_link = link_Glob + "?key=" + key.replace(/(^\s+)|(\s+$)/g, "") + "&did=1";
	  		 }
	  		 else
	  		 {
	  	 		tv_link = link_Glob + '/' + timeZone_Glob + '_' + countryUpp + '_' + short_name_Glob + '.wmv?key=' + key + "&did=1"; 
	  		 }	
		     tvLinkForTimeOut = tv_link;		     
		     Set_Player(tv_link);	    
		     document.getElementById("resize").innerHTML = "<button onclick='javascript:setFullScreen(true);'>Click here for Full Screen </button>";			 
		 }
     }
  	 else
  	 {
       window.location = "/user/login.php";
  	 }
  }
  else
  {
  	 tv_link = link_Glob + '/' + short_name_Glob; 
   	 tvLinkForTimeOut = tv_link;   
   	 Set_Player(tv_link);
  }	
}

function GoAndShowS(link)
{
	if (!userId)
    {
        window.location = "/user/login.php"; 
    }
    else
    {
        document.getElementById("video_player").innerHTML = "<div style='padding: 20px;  font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: medium; color: #FF0000'>Connecting to stream...</div>";
	    _link_4_GAS = link;
	    scroll(0, 200); 
        setTimeout("doGoAndShowS()", 1000);
    }
}

function doGoAndShowS()
{
  //**** Ajax session ****  
  doWork();
  //**** end of Ajax session ****	
  countryUpp = "CA";
 if (key.length > 0) //user is logged in
 {               
     if (key.indexOf("undefined") < 0)
	 {
		 tv_link = _link_4_GAS + '?key=' + key + '&did=1';
		 Set_Player(tv_link);	    
	 }
	 else
	 {
		 switch(countryUpp)
		 {
			 case "UA": 
				document.getElementById("video_player").innerHTML = '<div style="padding: 20px;  border: thin solid #800000; font-family: Arial, Helvetica, sans-serif; font-size: small; line-height: normal; font-weight: bold; font-size: medium; color: #FF0000">' +
				 	                                                '<strong>Увага!<br /></strong>'+
				 	                                                'Цей User Login вже використовується для перегляду на нашому сайті. Допускається лише 1 одночасний перегляд для 1 користувача.'+
				 	                                                '</div>'
				break;
			 case "RU": 
				document.getElementById("video_player").innerHTML = '<div style="padding: 20px;  border: thin solid #800000; font-family: Arial, Helvetica, sans-serif; font-size: small; line-height: normal; font-weight: bold; font-size: medium; color: #FF0000">' +
				 	                                                '<strong>Внимание!<br /></strong>'+  
				 	                                                'В настоящий момент данная учетная запись уже используется для просмотра. Допускается только 1 одновременный просмотр для 1 пользователя.' +
				 	                                                '</div>'
				break;
			  /* case "PL": 
				document.getElementById("video_player").innerHTML = ""; 	 	
				break; */
			 default:	
				document.getElementById("video_player").innerHTML = '<div style="padding: 20px;  border: thin solid #800000; font-family: Arial, Helvetica, sans-serif; font-size: small; line-height: normal; font-weight: bold; font-size: medium; color: #FF0000">' +
				 	                                                '<strong>Attention!<br /></strong>'+
				 	                                                'This usrename is currently being used to stream. Please wait for the user to log out and try again.' +
				 	                                                '</div>'
		 }
		 
	 }
 }
 else
 {
     window.location = "/user/login.php";
 }
}


MS_PROGIDS = new Array( 
"Microsoft.XMLHTTP",
"msxml2.xmlhttp",
"msxml2.xmlhttp.7.0", 
"msxml2.xmlhttp.6.0", 
"msxml2.xmlhttp.5.0", 
"msxml2.xmlhttp.4.0", 
"msxml2.xmlhttp.3.0"
); 

var isNative = -1;

// Get the HTTP Object  
function getHTTPObject(){
	
	// Create the appropriate HttpRequest object for the browser. 	
	var httpRequest = null;
    if (window.XMLHttpRequest!= null) 
    {
        httpRequest = new window.XMLHttpRequest(); 
        //alert("GoogleChrom here");
        if (isGoogleChrom())
        isNative = 0;
        else
        isNative = 1;
        
    }	
	else 
	{ 
		// Must be IE, find the right ActiveXObject. 
		for (var i = 0; i < MS_PROGIDS.length; i++) 
		{ 
			try 
			{ 
				if (httpRequest = new window.ActiveXObject(MS_PROGIDS[i]))
				{
					isNative = 0;
                	break;
				}
			} 
			catch (ex) {
			} 
		} 
	}
	
    if (httpRequest == null)
	{
		// If we couldn't create one, display an error and exit 
		alert("Error in HttpRequest():\n\nCannot create an XMLHttpRequest object.\n\nUpgrade your browser to the recent version."); 
	}
	
	return httpRequest; 
} 

function setNewKey(){
   
   	key = "";
   
   if ((httpObject != null) && (httpObject.readyState == 4))
   {
     key = httpObject.responseText;
     httpObject = null;
   }
   else
   {
	   if (httpObject == null)
	   {
		  alert(navigator.userAgent + "\nMethod1: httpObject is null"); 
	   }	   
   }
}

// Implement business logic
function doWork(){
	if (userId != 'new')
    {
        httpObject = getHTTPObject();
	    if (httpObject != null) {				
		    
		    var url = "/lib/ajax/ajax_channelChanged1.php?order=" + userId + "&t=" + Math.random() + "&ch=" +  short_name_Glob;
	    
		    try{			
			    httpObject.open("GET", url, false);
		    } catch (e) 
		    {
			    alert(e);
		    }
		    
	  	    if (isNative == 1)
	  	    {
	  	    	httpObject.onload = setNewKey ; 	    
	   	    	httpObject.onreadystatechange = setNewKey;
			}
			else if (isNative == 0)
			{
				httpObject.onreadystatechange = setNewKey;
			}
	        else
	        {
	            alert("Error in HttpRequest():\n\nCannot create an XMLHttpRequest object.\n\nUpgrade your browser to the recent version."); 
	          	return;
			}
			
		    try
		    {
			    httpObject.send(null);
		    }
		    catch (e)
		    {
			    alert("Error in send function");
		    }
	    }
	 	    else {
 		    alert("Method2: httpObject is null");
 		    return null;
	    }
    }
}

function isGoogleChrom()
{	
	return navigator.userAgent.indexOf('AppleWebKit') > 0;	
}