/**
 * Encodes plaintext submitted through a form in base64
 *
 * Written by sfyn (sfyn@riot-nrrd.info)
 * Based on original work by Herbert Hanewinkel (http://www.hanewin.net/encrypt/)
 * Licensed under the GPLv2
 */

var base64 = function () {

  // Index of characters in our base64 set
  var base64Index = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
 
  // Read in the input values
  var text = $('#encode-text').val();
  var displayElement = $('#encode-text');
  var subtext = text;

  // Used to calculate the base64 character to use
  var code;
  var asc;

  // Used in iteration
  var count = 0;
  var len=text.length;
  var keepGoing = 1;

  // Stores encrypted text for output
  var output='';

  // Keeps track of our position in the encrypted string
  var pos=0;

  // Determines which of 4 characters representing 3 octets we are writing
  var cPos=0;

  // Put the appropriate character in output and set up values for the next one
  function base64Char() { 
    asc = text.charCodeAt(count);
    switch (cPos) {
      case 0:
        output+=base64Index.charAt((asc>>2)&63);
        code=(asc&3)<<4;
        break;
      case 1:
        output+=base64Index.charAt((code|(asc>>4)&15));
        code=(asc&15)<<2;
        break;
      case 2:
        output+=base64Index.charAt(code|((asc>>6)&3));
        pos+=1;
        if((pos%60)==0) output+="\n";
        output+=base64Index.charAt(asc&63);
        break;
    }
    pos+=1;
    if((pos%60)==0) output+="\n";
    cPos+=1;
    if(cPos==3) cPos=0;
    count+=1;
    if (count>=len) keepGoing = 0;
  }

  function base64End() {
    // We are at the end of the string so append a =, unless
    // the last group was a full four characters
    if(cPos>0) {
      output+=base64Index.charAt(code);
      pos+=1;
      if((pos%60)==0) output+="\n";
      output+='=';
      pos+=1;
    }

    // Append an additional = if the last group was only two characters
    if(cPos==1)
    {
      if((pos%60)==0) output+="\n";
      output+='=';
    }
  }

  return {
    // Iterate through the submitted text and update the encoding as it happens
    encode: function() {
      base64Char();
      subtext = text.substring(count);
      if (keepGoing) setTimeout("base64.encode()", 100);
      else base64End();
      displayElement.val(output + subtext);
    },

    // Set some different values for the encoding
    init: function(element) {
      text = element.val();
      subtext = text;
      displayElement = element;
      len = text.length;
      count = pos = cPos = code = asc = 0;
      keepGoing = 1;
      output = '';
      base64.encode();
    }
  };
}();

$('input.encoder').click( function(event) {
  event.preventDefault();
  base64.init($('#encode-text'));
});
