Code viewer for World: Translation
  $('body').css( "margin", "20px" );
  $('body').css( "padding", "20px" );


// This is the first page, which allows users to input a password to join the same room.
document.write  ( ` 
    <div id=maindiv>
    <h1> A Translation Websocket World </h1>  
    A Websocket World that only certain users can join. <br>
    You enter a password. You only join with users who enter the same password (not with all users of the World). <br>
    The first user to run the World can enter any password! But other users must know what password they will use.
    <p>

	Enter password: 
	<input    style='width:25vw;'    maxlength='2000'   NAME="p"    id="p"       VALUE='' >  
	<button onclick='start();'  class=ab-normbutton >Start</button>
	<p>  
	
	<div id=errordiv name=errordiv> </div> 
	</div> ` );
	

var apikey = ""; // Variable which holds the API key.


function start()        // user has entered a password 
{
	var  password =  jQuery("input#p").val();
	password = password.trim();
	
	if ( ! alphanumeric ( password ) )
	{
	    $("#errordiv").html( "<font color=red> <B> Error: Password must be alphanumeric. </b></font> " );
	    return;
	}
	
	// else we have a password, start the socket run with this password 
    AB.socketStart ( password );  
    
    // The second page where users can see who else is in the room.
    // As well as being able to send messages in the chosen languages.
    // If source language is set to 'detect' then the API will automatically look for the language it is translating from.
    // The users must agree on a target language to be able to understand each other.
    $("#maindiv").html ( `
        <h1>Translation World</h1>
        
        <div id=enterkey style="width:60vw; background-color:white; margin:20;">
        Enter API key: 
	        <input    style='width:25vw;'    maxlength='2000'   NAME="apikey"    id="apikey"       VALUE='' >  
	        <button onclick='setkey();'  class=ab-normbutton >Set API key</button>
        </div>
        
        <br>
        
        <div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Me </h3>
            <INPUT style="width:50vw;" id=textToTranslate >
            <button onclick="sendchat();"     class=ab-normbutton > Send </button>
            <p id="confidence"></p>
        </div>
        
        <!-- Source Language -->
        <label for="sourceLanguage">Source Language:</label>
        <select id="sourceLanguage">
            <option value="detect">Detect</option>
            <option value="en">English</option>
            <option value="fr">French</option>
            <option value="es">Spanish</option>
            <option value="it">Italian</option>
            <option value="de">German</option>
            <option value="ja">Japanese</option>
            <option value="zh">Chinese</option>
            <option value="ro">Romanian</option>
            <option value="fil">Filipino</option>
        </select>
        
        <!-- Target Language -->
        <label for="targetLanguage">Target Language:</label>
        <select id="targetLanguage">
            <option value="en">English</option>
            <option value="fr">French</option>
            <option value="es">Spanish</option>
            <option value="it">Italian</option>
            <option value="de">German</option>
            <option value="ja">Japanese</option>
            <option value="zh">Chinese</option>
            <option value="ro">Romanian</option>
            <option value="fil">Filipino</option>
        </select>

        <div style="width:60vw; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Them </h3>
            <div id=them > </div>
        </div>

        <div style="width:60vw; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Users online </h3>
            <div id=themlist > </div>
        </div>

        <script src="script.js"></script>
    ` );
}

// This function sets the API key entered by the user.
function setkey()          
{
	apikey =  jQuery("input#apikey").val();
	apikey = apikey.trim();
	$("#enterkey").html ( "<b> API key has been set. </b>" );
}

  
function alphanumeric ( str ) 				// return if string is just alphanumeric   
{
	var rc = str.match(/^[0-9a-zA-Z]+$/); 			// start of line  "[0-9a-zA-Z]+"  end of line 
	
	if ( rc ) return true;
	else      return false; 
}


AB.socketUserlist = function ( a )      // when told users I am sharing with
{ 
    console.log ( JSON.stringify ( a, null, ' ' ) );
}

// This function translates and sends a message to all the users in the same room.
function sendchat() {
    // It grabs the inputs the user makes.
    const textToTranslate = document.getElementById('textToTranslate').value;
    const sourceLanguage = document.getElementById('sourceLanguage').value;
    const targetLanguage = document.getElementById('targetLanguage').value;

    // Checks whether some text for translation and a target language is entered.
    if (!textToTranslate || !targetLanguage) {
        alert('Please enter text to translate and target language.');
        return;
    }
    
    const translateAPIUrl = `https://translation.googleapis.com/language/translate/v2?key=${apikey}`; // The API URL for the translate method on Google Cloud Translation API
    const detectAPIUrl = `https://translation.googleapis.com/language/translate/v2/detect?key=${apikey}`; // The API URL for the detect method on Google Cloud Translation API

    // Depending on the input by the user, construct the data as follows for the POST request.
   let data;
   if (sourceLanguage == "detect") {
        data = {
            q: textToTranslate,
            target: targetLanguage,
        };  
   } else {
        data = {
            q: textToTranslate,
            source: sourceLanguage,
            target: targetLanguage,
        };
   }
   
   // This POST request is for calculating the 'confidence' that the API has in it's detected translation.
   if (sourceLanguage == "detect") {
       const detectData = {
           q: textToTranslate,
       };
       fetch(detectAPIUrl, {
           method: 'POST',
           body: JSON.stringify(detectData),
           headers: {
               'Content-Type': 'application/json',
           },
       })
       .then(response => response.json())
        .then(data => {
            const confidence = (data.data.detections[0][0].confidence) * 100;
            document.getElementById("confidence").innerHTML = "The confidence of the translation is " + confidence.toFixed(2) + "%";
        });
   }

    // This POST request is for the translation.
    fetch(translateAPIUrl, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json',
        },
    })
    .then(response => response.json())
    .then(data => {
        const translationResult = data.data.translations[0].translatedText;

        var messageData = {
            userid: AB.myuserid,
            username: AB.myusername,
            line: translationResult
        };

        AB.socketOut(messageData); // server gets this, and sends the data to all clients running this World
    })
    .catch(error => console.error('Error:', error));
}


// given AB userid, username, construct a link to that user 
// if not run logged in, userid = "none"

function userlink ( userid, username )
{
   if ( userid == "none" ) return ( "Anon user" );
   else                    return ( "<a target='_blank' href='https://ancientbrain.com/user.php?userid=" + userid + "'>" + username + "</a>" );
}


// --- re-define AB socket handler functions -------------------------------------
// re-define these handler functions from default (which is do nothing)

// When someone else enters text, server will trigger AB.socketIn.
// Here I define what to do for it.

AB.socketIn = function(data)
{
   var userhtml = userlink ( data.userid, data.username );
   $("#them").html ( userhtml + ": " + data.line );
};


// At startup, and when list of users changes, server will trigger AB.socketUserlist.  
// Here I define what to do for it.

AB.socketUserlist = function ( a ) 
{ 
    console.log ( "Got user list: " );
    console.log ( JSON.stringify ( a, null, ' ' ) );

    if ( a.length < 2 )  
    { 
        $("#themlist").html ( "<h3 style='color:red'> You are alone. Get someone else to run this World. </h3>"); 
        return; 
    }
    
    // else  
    var str = " <ol> ";
    for (var i = 0; i < a.length; i++) 
    {
        var userhtml = userlink ( a[i][0], a[i][1] );
        str = str + " <li> " + userhtml ;
    }
    $("#themlist").html ( str + " </ol> " );
};


/* References:
[1] https://ancientbrain.com/world.php?world=2423445528 // Websocket Password
[2] https://ancientbrain.com/world.php?world=5280355402 // Websocket Chat
[3] https://ancientbrain.com/world.php?world=2850716357 // API Key part
*/