/* comments of modify byteEncode and byteDecode
1. if you modify byteEnocde or byteDecode function, you must modify the corresponding method in Tool.java .

2. There is a copy of byteEnocde function in find.js(Encapulased in the document.write code) in order to avoid a strange bug if we include encodeUtil.js in the find window. So don't forget to modify find.js if you modify the byteEncode function.
*/
/**
 *
 * @param isEncodeAll true it will encode all characters including English.
 */
function byteEncode(str, isEncodeAll) {
   if((str == null) || (str == "")) {
     return "";
   }

   if(isEncodeAll == null) { // default value is false
      isEncodeAll = false;
   }

   var ret = '';

   for(var i=0; i < str.length; i++) {
      var ch = str.charAt(i);
      var code = str.charCodeAt(i);

      if(code < 128 && ch != '[' && !isEncodeAll && ch != '\'' && ch != '=') {
         ret += ch;
      }
      else {
         ret += "[" + code.toString(16) + "]";
      }
   }

   return ret;
}

function byteEncode2(str) {
   var ret = '';

   for(var i = 0; i < str.length; i++) {
      var ch = str.charAt(i);
      var code = str.charCodeAt(i);

      if(code < 128 && ch != '[' && ch != '/' && ch != '\'' &&
         ch != '=' && ch != '%' && ch != '&' && ch != '?' &&
         ch != '#' && ch != '"' && ch != '<' && ch != '>' &&
         ch != ',' && ch != '\\' && ch != '+')
      {
         ret += ch;
      }
      else {
         ret += "[" + code.toString(16) + "]";
      }
   }

   return ret;
}

/**
 * It will encode the character '/'.
 * @param isEncodeAll true it will encode all characters including English.
 */
function byteEncodeURL(str, isEncodeAll) {
   if((str == null) || (str == "")) {
     return "";
   }

   if(isEncodeAll == null) { // default value is false
      isEncodeAll = false;
   }

   var ret = '';

   for(var i = 0; i < str.length; i++) {
      var ch = str.charAt(i);
      var code = str.charCodeAt(i);

      if(code < 128 && ch != '[' && !isEncodeAll && ch != '/') {
         ret += ch;
      }
      else {
         ret += "[" + code.toString(16) + "]";
      }
   }

   return ret;
}

function byteDecode(encString) {
   if((encString == null) || (encString == '')) {
      return "";
   }

   var str = '';

   for(var i = 0; i < encString.length; i++) {
      var ch = encString.charAt(i);

      if(ch == '[') {
         var idx = encString.indexOf(']', i + 1);

         if(idx > i + 1) {
            ch = String.fromCharCode(parseInt(encString.substring(i + 1, idx),
                                              16));
            i = idx;
         }
      }

      str += ch;
   }

   return str;
}
