/*	ENCIPHER.JS		1-18-2011		JavaScript
	JavaScript Version.
	Copyright (C)1994-1996, 2007, 2008, 2011 Steven Whitney.
	Initially published by http://25yearsofprogramming.com.

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License (GPL)
	Version 3 as published by the Free Software Foundation.
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

	Creates substitution ciphers by randomly rearranging the alphabet.
*/
function Encipher(mode)	
{
var letters = new Array();  //translation table
var outtext = "";			//for building the output text
var i, j, shiftcount, ch;
var source = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(i = 0 ; i < 26 ; i++)	// FIRST FILL WITH TRANSLATION LETTERS
{
	letters.push(new Object());
	letters[i].trans = letters[i].orig = source.charAt(i);
	letters[i].sequence = Math.random();
}
switch(mode)
{
	case 0:			// Caesar cipher shifts alphabet
		shift = 1 + (Math.floor(Math.random() * 25));
		for(i = 0 ; i < 26 ; i++)
			letters[i].trans = source.charAt(i + shift);
		break;
	case 1:			// random substitution cipher
		// MIX THEM UP BY SORTING ON THE RANDOM NUMBERS
		letters.sort(function(a,b){return a.sequence - b.sequence;}); 
		//NOW ASSIGN ORIG, IN PROPER ORDER
		//This leaves the array elements in order of source letters ABC..., 
		//with each one tied to a random and unique translation letter.
		for(i = 0 ; i < 26 ; i++)				
			letters[i].orig = source.charAt(i);
		break;
	case 2:			// alphabet reversal cipher
		for(i = 0 ; i < 26 ; i++)
			letters[i].trans = source.charAt(25 - i);
		break;
}
// Incorporates basic HTML cleaning, even though textarea does not allow auto-conversion of hyperlinks
var buf = document.getElementById("PlainTextIn").value.replace(/[<>&/%\\#]/g,".").toUpperCase();

for(j = 0 ; j < buf.length ; j++)		// for each letter in buffer,
{
	ch = buf.charAt(j);       			
	for(i = 0 ; i < 26 ; i++)			// LOOK IT UP,
		if(ch == letters[i].orig)
		{
			ch = letters[i].trans;		// AND TRANSLATE IT
			break;
		}
	outtext += ch;
}
//write text to output textarea
//innerHTML is not good because HTML compresses spaces and removes line ends.
//document.getElementById("CipheredTextOut").innerHTML = outtext; 
document.getElementById("CipheredTextOut").value = outtext;
}

