var URLCoder = new Object();

URLCoder.SAFECHARS =
 "0123456789" +					// Numeric
 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
 "abcdefghijklmnopqrstuvwxyz" +
 "-_.!~*'()"; // RFC2396 Mark characters
 
URLCoder.HEX = "0123456789ABCDEF";

function URLCoder_encode(plaintext)
{
  var charCode, ch, i, encoded = "", alerted = false;
  for (i = 0; i < plaintext.length; i++)
  {
    ch = plaintext.charAt(i);
    if (ch == " ")
    {
      encoded += "+";				// x-www-urlencoded, rather than %20
    }
    else if (URLCoder.SAFECHARS.indexOf(ch) != -1)
    {
      encoded += ch;
    }
    else
    {
      charCode= ch.charCodeAt(0);
      if (charCode > 255)
      {
        if (!alerted)
        {
          alert( "Unicode Character '" 
                 + ch 
                 + "' cannot be encoded using standard URL encoding.\n" +
                 "(URL encoding only supports 8-bit characters.)\n" +
                 "A space (+) will be substituted." );
          alerted = true;
        }
        encoded += "+";
      }
      else
      {
        encoded += "%";
        encoded += URLCoder.HEX.charAt((charCode >> 4) & 0xF);
        encoded += URLCoder.HEX.charAt(charCode & 0xF);
      }
    }
  }
  return encoded;
}
URLCoder.encode = URLCoder_encode;

function URLCoder_decode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var ch, c1, c2, i, plaintext = "", alert = false;
   
   if ((encoded == null) || (encoded.length == 0))
   {
     return "";
   }
   
   for (i = 0; i < encoded.length; i++)
   {
     ch = encoded.charAt(i);
     if (ch == "+")
     {
       plaintext += " ";
     }
     else if (ch == "%")
     {
       if (i < (encoded.length - 2))
       {
         c1 = URLCoder.HEX.indexOf(encoded.charAt(i+1).toUpperCase());
         c2 = URLCoder.HEX.indexOf(encoded.charAt(i+2).toUpperCase());
         if ((c1 != -1) && (c2 != -1))
         {
           plaintext += String.fromCharCode((16 * c1) + c2);
           i += 2;
         }
         else
         {
           if (!alerted)
           {
             alert( 'Bad escape combination near ...' + encoded.substr(i) );
             plaintext += "%[ERROR]";
             alerted = true;
           }
         }
       }
     }
     else
     {
       plaintext += ch;
     }
   }
   return plaintext;
}
URLCoder.decode = URLCoder_decode;

function URLCoder_decodeGET()
{
   var i, pairs, vals;
   URLCoder.get = new Array();
   
   if (window.location.search.length)
   {
     pairs = window.location.search.substring(1).split("&");
     for (i = 0; i < pairs.length; i++)
     {
       vals = pairs[i].split("=");
       URLCoder.get[vals[0]] = URLCoder.decode(vals[1]);
     }
   }
}
URLCoder.decodeGET = URLCoder_decodeGET;
URLCoder.decodeGET();